babylon.max.js 3.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. 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;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var Color3 = (function () {
  23. /**
  24. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  25. */
  26. function Color3(r, g, b) {
  27. if (r === void 0) { r = 0; }
  28. if (g === void 0) { g = 0; }
  29. if (b === void 0) { b = 0; }
  30. this.r = r;
  31. this.g = g;
  32. this.b = b;
  33. }
  34. /**
  35. * Returns a string with the Color3 current values.
  36. */
  37. Color3.prototype.toString = function () {
  38. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  39. };
  40. /**
  41. * Returns the string "Color3".
  42. */
  43. Color3.prototype.getClassName = function () {
  44. return "Color3";
  45. };
  46. /**
  47. * Returns the Color3 hash code.
  48. */
  49. Color3.prototype.getHashCode = function () {
  50. var hash = this.r || 0;
  51. hash = (hash * 397) ^ (this.g || 0);
  52. hash = (hash * 397) ^ (this.b || 0);
  53. return hash;
  54. };
  55. // Operators
  56. /**
  57. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  58. * Returns the Color3.
  59. */
  60. Color3.prototype.toArray = function (array, index) {
  61. if (index === undefined) {
  62. index = 0;
  63. }
  64. array[index] = this.r;
  65. array[index + 1] = this.g;
  66. array[index + 2] = this.b;
  67. return this;
  68. };
  69. /**
  70. * Returns a new Color4 object from the current Color3 and the passed alpha.
  71. */
  72. Color3.prototype.toColor4 = function (alpha) {
  73. if (alpha === void 0) { alpha = 1; }
  74. return new Color4(this.r, this.g, this.b, alpha);
  75. };
  76. /**
  77. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  78. */
  79. Color3.prototype.asArray = function () {
  80. var result = [];
  81. this.toArray(result, 0);
  82. return result;
  83. };
  84. /**
  85. * Returns the luminance value (float).
  86. */
  87. Color3.prototype.toLuminance = function () {
  88. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  89. };
  90. /**
  91. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  92. * Returns this new object.
  93. */
  94. Color3.prototype.multiply = function (otherColor) {
  95. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  96. };
  97. /**
  98. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  99. * Returns the current Color3.
  100. */
  101. Color3.prototype.multiplyToRef = function (otherColor, result) {
  102. result.r = this.r * otherColor.r;
  103. result.g = this.g * otherColor.g;
  104. result.b = this.b * otherColor.b;
  105. return this;
  106. };
  107. /**
  108. * Boolean : True if the rgb values are equal to the passed ones.
  109. */
  110. Color3.prototype.equals = function (otherColor) {
  111. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  112. };
  113. /**
  114. * Boolean : True if the rgb values are equal to the passed ones.
  115. */
  116. Color3.prototype.equalsFloats = function (r, g, b) {
  117. return this.r === r && this.g === g && this.b === b;
  118. };
  119. /**
  120. * Multiplies in place each rgb value by scale.
  121. * Returns the updated Color3.
  122. */
  123. Color3.prototype.scale = function (scale) {
  124. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  125. };
  126. /**
  127. * Multiplies the rgb values by scale and stores the result into "result".
  128. * Returns the unmodified current Color3.
  129. */
  130. Color3.prototype.scaleToRef = function (scale, result) {
  131. result.r = this.r * scale;
  132. result.g = this.g * scale;
  133. result.b = this.b * scale;
  134. return this;
  135. };
  136. /**
  137. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  138. */
  139. Color3.prototype.add = function (otherColor) {
  140. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  141. };
  142. /**
  143. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  144. * Returns the unmodified current Color3.
  145. */
  146. Color3.prototype.addToRef = function (otherColor, result) {
  147. result.r = this.r + otherColor.r;
  148. result.g = this.g + otherColor.g;
  149. result.b = this.b + otherColor.b;
  150. return this;
  151. };
  152. /**
  153. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  154. */
  155. Color3.prototype.subtract = function (otherColor) {
  156. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  157. };
  158. /**
  159. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  160. * Returns the unmodified current Color3.
  161. */
  162. Color3.prototype.subtractToRef = function (otherColor, result) {
  163. result.r = this.r - otherColor.r;
  164. result.g = this.g - otherColor.g;
  165. result.b = this.b - otherColor.b;
  166. return this;
  167. };
  168. /**
  169. * Returns a new Color3 copied the current one.
  170. */
  171. Color3.prototype.clone = function () {
  172. return new Color3(this.r, this.g, this.b);
  173. };
  174. /**
  175. * Copies the rgb values from the source in the current Color3.
  176. * Returns the updated Color3.
  177. */
  178. Color3.prototype.copyFrom = function (source) {
  179. this.r = source.r;
  180. this.g = source.g;
  181. this.b = source.b;
  182. return this;
  183. };
  184. /**
  185. * Updates the Color3 rgb values from the passed floats.
  186. * Returns the Color3.
  187. */
  188. Color3.prototype.copyFromFloats = function (r, g, b) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. };
  194. /**
  195. * Updates the Color3 rgb values from the passed floats.
  196. * Returns the Color3.
  197. */
  198. Color3.prototype.set = function (r, g, b) {
  199. return this.copyFromFloats(r, g, b);
  200. };
  201. /**
  202. * Returns the Color3 hexadecimal code as a string.
  203. */
  204. Color3.prototype.toHexString = function () {
  205. var intR = (this.r * 255) | 0;
  206. var intG = (this.g * 255) | 0;
  207. var intB = (this.b * 255) | 0;
  208. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  209. };
  210. /**
  211. * Returns a new Color3 converted to linear space.
  212. */
  213. Color3.prototype.toLinearSpace = function () {
  214. var convertedColor = new Color3();
  215. this.toLinearSpaceToRef(convertedColor);
  216. return convertedColor;
  217. };
  218. /**
  219. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  220. * Returns the unmodified Color3.
  221. */
  222. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  223. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  224. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  225. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  226. return this;
  227. };
  228. /**
  229. * Returns a new Color3 converted to gamma space.
  230. */
  231. Color3.prototype.toGammaSpace = function () {
  232. var convertedColor = new Color3();
  233. this.toGammaSpaceToRef(convertedColor);
  234. return convertedColor;
  235. };
  236. /**
  237. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  238. * Returns the unmodified Color3.
  239. */
  240. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  241. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  242. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  243. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  244. return this;
  245. };
  246. // Statics
  247. /**
  248. * Creates a new Color3 from the string containing valid hexadecimal values.
  249. */
  250. Color3.FromHexString = function (hex) {
  251. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  252. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  253. return new Color3(0, 0, 0);
  254. }
  255. var r = parseInt(hex.substring(1, 3), 16);
  256. var g = parseInt(hex.substring(3, 5), 16);
  257. var b = parseInt(hex.substring(5, 7), 16);
  258. return Color3.FromInts(r, g, b);
  259. };
  260. /**
  261. * Creates a new Vector3 from the startind index of the passed array.
  262. */
  263. Color3.FromArray = function (array, offset) {
  264. if (offset === void 0) { offset = 0; }
  265. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  266. };
  267. /**
  268. * Creates a new Color3 from integer values ( < 256).
  269. */
  270. Color3.FromInts = function (r, g, b) {
  271. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  272. };
  273. /**
  274. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  275. */
  276. Color3.Lerp = function (start, end, amount) {
  277. var r = start.r + ((end.r - start.r) * amount);
  278. var g = start.g + ((end.g - start.g) * amount);
  279. var b = start.b + ((end.b - start.b) * amount);
  280. return new Color3(r, g, b);
  281. };
  282. Color3.Red = function () { return new Color3(1, 0, 0); };
  283. Color3.Green = function () { return new Color3(0, 1, 0); };
  284. Color3.Blue = function () { return new Color3(0, 0, 1); };
  285. Color3.Black = function () { return new Color3(0, 0, 0); };
  286. Color3.White = function () { return new Color3(1, 1, 1); };
  287. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  288. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  289. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  290. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  291. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  292. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  293. return Color3;
  294. }());
  295. BABYLON.Color3 = Color3;
  296. var Color4 = (function () {
  297. /**
  298. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  299. */
  300. function Color4(r, g, b, a) {
  301. if (r === void 0) { r = 0; }
  302. if (g === void 0) { g = 0; }
  303. if (b === void 0) { b = 0; }
  304. if (a === void 0) { a = 1; }
  305. this.r = r;
  306. this.g = g;
  307. this.b = b;
  308. this.a = a;
  309. }
  310. // Operators
  311. /**
  312. * Adds in place the passed Color4 values to the current Color4.
  313. * Returns the updated Color4.
  314. */
  315. Color4.prototype.addInPlace = function (right) {
  316. this.r += right.r;
  317. this.g += right.g;
  318. this.b += right.b;
  319. this.a += right.a;
  320. return this;
  321. };
  322. /**
  323. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  324. */
  325. Color4.prototype.asArray = function () {
  326. var result = [];
  327. this.toArray(result, 0);
  328. return result;
  329. };
  330. /**
  331. * Stores from the starting index in the passed array the Color4 successive values.
  332. * Returns the Color4.
  333. */
  334. Color4.prototype.toArray = function (array, index) {
  335. if (index === undefined) {
  336. index = 0;
  337. }
  338. array[index] = this.r;
  339. array[index + 1] = this.g;
  340. array[index + 2] = this.b;
  341. array[index + 3] = this.a;
  342. return this;
  343. };
  344. /**
  345. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  346. */
  347. Color4.prototype.add = function (right) {
  348. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  349. };
  350. /**
  351. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  352. */
  353. Color4.prototype.subtract = function (right) {
  354. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  355. };
  356. /**
  357. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  358. * Returns the Color4.
  359. */
  360. Color4.prototype.subtractToRef = function (right, result) {
  361. result.r = this.r - right.r;
  362. result.g = this.g - right.g;
  363. result.b = this.b - right.b;
  364. result.a = this.a - right.a;
  365. return this;
  366. };
  367. /**
  368. * Creates a new Color4 with the current Color4 values multiplied by scale.
  369. */
  370. Color4.prototype.scale = function (scale) {
  371. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  372. };
  373. /**
  374. * Multiplies the current Color4 values by scale and stores the result in "result".
  375. * Returns the Color4.
  376. */
  377. Color4.prototype.scaleToRef = function (scale, result) {
  378. result.r = this.r * scale;
  379. result.g = this.g * scale;
  380. result.b = this.b * scale;
  381. result.a = this.a * scale;
  382. return this;
  383. };
  384. /**
  385. * Multipy an RGBA Color4 value by another and return a new Color4 object
  386. * @param color The Color4 (RGBA) value to multiply by
  387. * @returns A new Color4.
  388. */
  389. Color4.prototype.multiply = function (color) {
  390. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  391. };
  392. /**
  393. * Multipy an RGBA Color4 value by another and push the result in a reference value
  394. * @param color The Color4 (RGBA) value to multiply by
  395. * @param result The Color4 (RGBA) to fill the result in
  396. * @returns the result Color4.
  397. */
  398. Color4.prototype.multiplyToRef = function (color, result) {
  399. result.r = this.r * color.r;
  400. result.g = this.g * color.g;
  401. result.b = this.b * color.b;
  402. result.a = this.a * color.a;
  403. return result;
  404. };
  405. /**
  406. * Returns a string with the Color4 values.
  407. */
  408. Color4.prototype.toString = function () {
  409. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  410. };
  411. /**
  412. * Returns the string "Color4"
  413. */
  414. Color4.prototype.getClassName = function () {
  415. return "Color4";
  416. };
  417. /**
  418. * Return the Color4 hash code as a number.
  419. */
  420. Color4.prototype.getHashCode = function () {
  421. var hash = this.r || 0;
  422. hash = (hash * 397) ^ (this.g || 0);
  423. hash = (hash * 397) ^ (this.b || 0);
  424. hash = (hash * 397) ^ (this.a || 0);
  425. return hash;
  426. };
  427. /**
  428. * Creates a new Color4 copied from the current one.
  429. */
  430. Color4.prototype.clone = function () {
  431. return new Color4(this.r, this.g, this.b, this.a);
  432. };
  433. /**
  434. * Copies the passed Color4 values into the current one.
  435. * Returns the updated Color4.
  436. */
  437. Color4.prototype.copyFrom = function (source) {
  438. this.r = source.r;
  439. this.g = source.g;
  440. this.b = source.b;
  441. this.a = source.a;
  442. return this;
  443. };
  444. /**
  445. * Copies the passed float values into the current one.
  446. * Returns the updated Color4.
  447. */
  448. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  449. this.r = r;
  450. this.g = g;
  451. this.b = b;
  452. this.a = a;
  453. return this;
  454. };
  455. /**
  456. * Copies the passed float values into the current one.
  457. * Returns the updated Color4.
  458. */
  459. Color4.prototype.set = function (r, g, b, a) {
  460. return this.copyFromFloats(r, g, b, a);
  461. };
  462. /**
  463. * Returns a string containing the hexadecimal Color4 code.
  464. */
  465. Color4.prototype.toHexString = function () {
  466. var intR = (this.r * 255) | 0;
  467. var intG = (this.g * 255) | 0;
  468. var intB = (this.b * 255) | 0;
  469. var intA = (this.a * 255) | 0;
  470. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  471. };
  472. /**
  473. * Returns a new Color4 converted to linear space.
  474. */
  475. Color4.prototype.toLinearSpace = function () {
  476. var convertedColor = new Color4();
  477. this.toLinearSpaceToRef(convertedColor);
  478. return convertedColor;
  479. };
  480. /**
  481. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  482. * Returns the unmodified Color4.
  483. */
  484. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  485. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  486. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  487. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  488. convertedColor.a = this.a;
  489. return this;
  490. };
  491. /**
  492. * Returns a new Color4 converted to gamma space.
  493. */
  494. Color4.prototype.toGammaSpace = function () {
  495. var convertedColor = new Color4();
  496. this.toGammaSpaceToRef(convertedColor);
  497. return convertedColor;
  498. };
  499. /**
  500. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  501. * Returns the unmodified Color4.
  502. */
  503. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  504. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  505. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  506. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  507. convertedColor.a = this.a;
  508. return this;
  509. };
  510. // Statics
  511. /**
  512. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  513. */
  514. Color4.FromHexString = function (hex) {
  515. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  516. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  517. return new Color4(0.0, 0.0, 0.0, 0.0);
  518. }
  519. var r = parseInt(hex.substring(1, 3), 16);
  520. var g = parseInt(hex.substring(3, 5), 16);
  521. var b = parseInt(hex.substring(5, 7), 16);
  522. var a = parseInt(hex.substring(7, 9), 16);
  523. return Color4.FromInts(r, g, b, a);
  524. };
  525. /**
  526. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  527. */
  528. Color4.Lerp = function (left, right, amount) {
  529. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  530. Color4.LerpToRef(left, right, amount, result);
  531. return result;
  532. };
  533. /**
  534. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  535. */
  536. Color4.LerpToRef = function (left, right, amount, result) {
  537. result.r = left.r + (right.r - left.r) * amount;
  538. result.g = left.g + (right.g - left.g) * amount;
  539. result.b = left.b + (right.b - left.b) * amount;
  540. result.a = left.a + (right.a - left.a) * amount;
  541. };
  542. /**
  543. * Creates a new Color4 from the starting index element of the passed array.
  544. */
  545. Color4.FromArray = function (array, offset) {
  546. if (offset === void 0) { offset = 0; }
  547. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  548. };
  549. /**
  550. * Creates a new Color4 from the passed integers ( < 256 ).
  551. */
  552. Color4.FromInts = function (r, g, b, a) {
  553. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  554. };
  555. Color4.CheckColors4 = function (colors, count) {
  556. // Check if color3 was used
  557. if (colors.length === count * 3) {
  558. var colors4 = [];
  559. for (var index = 0; index < colors.length; index += 3) {
  560. var newIndex = (index / 3) * 4;
  561. colors4[newIndex] = colors[index];
  562. colors4[newIndex + 1] = colors[index + 1];
  563. colors4[newIndex + 2] = colors[index + 2];
  564. colors4[newIndex + 3] = 1.0;
  565. }
  566. return colors4;
  567. }
  568. return colors;
  569. };
  570. return Color4;
  571. }());
  572. BABYLON.Color4 = Color4;
  573. var Vector2 = (function () {
  574. /**
  575. * Creates a new Vector2 from the passed x and y coordinates.
  576. */
  577. function Vector2(x, y) {
  578. this.x = x;
  579. this.y = y;
  580. }
  581. /**
  582. * Returns a string with the Vector2 coordinates.
  583. */
  584. Vector2.prototype.toString = function () {
  585. return "{X: " + this.x + " Y:" + this.y + "}";
  586. };
  587. /**
  588. * Returns the string "Vector2"
  589. */
  590. Vector2.prototype.getClassName = function () {
  591. return "Vector2";
  592. };
  593. /**
  594. * Returns the Vector2 hash code as a number.
  595. */
  596. Vector2.prototype.getHashCode = function () {
  597. var hash = this.x || 0;
  598. hash = (hash * 397) ^ (this.y || 0);
  599. return hash;
  600. };
  601. // Operators
  602. /**
  603. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  604. * Returns the Vector2.
  605. */
  606. Vector2.prototype.toArray = function (array, index) {
  607. if (index === void 0) { index = 0; }
  608. array[index] = this.x;
  609. array[index + 1] = this.y;
  610. return this;
  611. };
  612. /**
  613. * Returns a new array with 2 elements : the Vector2 coordinates.
  614. */
  615. Vector2.prototype.asArray = function () {
  616. var result = [];
  617. this.toArray(result, 0);
  618. return result;
  619. };
  620. /**
  621. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  622. * Returns the updated Vector2.
  623. */
  624. Vector2.prototype.copyFrom = function (source) {
  625. this.x = source.x;
  626. this.y = source.y;
  627. return this;
  628. };
  629. /**
  630. * Sets the Vector2 coordinates with the passed floats.
  631. * Returns the updated Vector2.
  632. */
  633. Vector2.prototype.copyFromFloats = function (x, y) {
  634. this.x = x;
  635. this.y = y;
  636. return this;
  637. };
  638. /**
  639. * Sets the Vector2 coordinates with the passed floats.
  640. * Returns the updated Vector2.
  641. */
  642. Vector2.prototype.set = function (x, y) {
  643. return this.copyFromFloats(x, y);
  644. };
  645. /**
  646. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  647. */
  648. Vector2.prototype.add = function (otherVector) {
  649. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  650. };
  651. /**
  652. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  653. * Returns the Vector2.
  654. */
  655. Vector2.prototype.addToRef = function (otherVector, result) {
  656. result.x = this.x + otherVector.x;
  657. result.y = this.y + otherVector.y;
  658. return this;
  659. };
  660. /**
  661. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.addInPlace = function (otherVector) {
  665. this.x += otherVector.x;
  666. this.y += otherVector.y;
  667. return this;
  668. };
  669. /**
  670. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  671. */
  672. Vector2.prototype.addVector3 = function (otherVector) {
  673. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  674. };
  675. /**
  676. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  677. */
  678. Vector2.prototype.subtract = function (otherVector) {
  679. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  680. };
  681. /**
  682. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  683. * Returns the Vector2.
  684. */
  685. Vector2.prototype.subtractToRef = function (otherVector, result) {
  686. result.x = this.x - otherVector.x;
  687. result.y = this.y - otherVector.y;
  688. return this;
  689. };
  690. /**
  691. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  692. * Returns the updated Vector2.
  693. */
  694. Vector2.prototype.subtractInPlace = function (otherVector) {
  695. this.x -= otherVector.x;
  696. this.y -= otherVector.y;
  697. return this;
  698. };
  699. /**
  700. * Multiplies in place the current Vector2 coordinates by the passed ones.
  701. * Returns the updated Vector2.
  702. */
  703. Vector2.prototype.multiplyInPlace = function (otherVector) {
  704. this.x *= otherVector.x;
  705. this.y *= otherVector.y;
  706. return this;
  707. };
  708. /**
  709. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  710. */
  711. Vector2.prototype.multiply = function (otherVector) {
  712. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  713. };
  714. /**
  715. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  716. * Returns the Vector2.
  717. */
  718. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  719. result.x = this.x * otherVector.x;
  720. result.y = this.y * otherVector.y;
  721. return this;
  722. };
  723. /**
  724. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  725. */
  726. Vector2.prototype.multiplyByFloats = function (x, y) {
  727. return new Vector2(this.x * x, this.y * y);
  728. };
  729. /**
  730. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  731. */
  732. Vector2.prototype.divide = function (otherVector) {
  733. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  734. };
  735. /**
  736. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  737. * Returns the Vector2.
  738. */
  739. Vector2.prototype.divideToRef = function (otherVector, result) {
  740. result.x = this.x / otherVector.x;
  741. result.y = this.y / otherVector.y;
  742. return this;
  743. };
  744. /**
  745. * Returns a new Vector2 with current Vector2 negated coordinates.
  746. */
  747. Vector2.prototype.negate = function () {
  748. return new Vector2(-this.x, -this.y);
  749. };
  750. /**
  751. * Multiply the Vector2 coordinates by scale.
  752. * Returns the updated Vector2.
  753. */
  754. Vector2.prototype.scaleInPlace = function (scale) {
  755. this.x *= scale;
  756. this.y *= scale;
  757. return this;
  758. };
  759. /**
  760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  761. */
  762. Vector2.prototype.scale = function (scale) {
  763. return new Vector2(this.x * scale, this.y * scale);
  764. };
  765. /**
  766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  767. */
  768. Vector2.prototype.equals = function (otherVector) {
  769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  770. };
  771. /**
  772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  773. */
  774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  777. };
  778. // Properties
  779. /**
  780. * Returns the vector length (float).
  781. */
  782. Vector2.prototype.length = function () {
  783. return Math.sqrt(this.x * this.x + this.y * this.y);
  784. };
  785. /**
  786. * Returns the vector squared length (float);
  787. */
  788. Vector2.prototype.lengthSquared = function () {
  789. return (this.x * this.x + this.y * this.y);
  790. };
  791. // Methods
  792. /**
  793. * Normalize the vector.
  794. * Returns the updated Vector2.
  795. */
  796. Vector2.prototype.normalize = function () {
  797. var len = this.length();
  798. if (len === 0)
  799. return this;
  800. var num = 1.0 / len;
  801. this.x *= num;
  802. this.y *= num;
  803. return this;
  804. };
  805. /**
  806. * Returns a new Vector2 copied from the Vector2.
  807. */
  808. Vector2.prototype.clone = function () {
  809. return new Vector2(this.x, this.y);
  810. };
  811. // Statics
  812. /**
  813. * Returns a new Vector2(0, 0)
  814. */
  815. Vector2.Zero = function () {
  816. return new Vector2(0, 0);
  817. };
  818. /**
  819. * Returns a new Vector2(1, 1)
  820. */
  821. Vector2.One = function () {
  822. return new Vector2(1, 1);
  823. };
  824. /**
  825. * Returns a new Vector2 set from the passed index element of the passed array.
  826. */
  827. Vector2.FromArray = function (array, offset) {
  828. if (offset === void 0) { offset = 0; }
  829. return new Vector2(array[offset], array[offset + 1]);
  830. };
  831. /**
  832. * Sets "result" from the passed index element of the passed array.
  833. */
  834. Vector2.FromArrayToRef = function (array, offset, result) {
  835. result.x = array[offset];
  836. result.y = array[offset + 1];
  837. };
  838. /**
  839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  840. */
  841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  842. var squared = amount * amount;
  843. var cubed = amount * squared;
  844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  850. return new Vector2(x, y);
  851. };
  852. /**
  853. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  856. */
  857. Vector2.Clamp = function (value, min, max) {
  858. var x = value.x;
  859. x = (x > max.x) ? max.x : x;
  860. x = (x < min.x) ? min.x : x;
  861. var y = value.y;
  862. y = (y > max.y) ? max.y : y;
  863. y = (y < min.y) ? min.y : y;
  864. return new Vector2(x, y);
  865. };
  866. /**
  867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  868. */
  869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  870. var squared = amount * amount;
  871. var cubed = amount * squared;
  872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  874. var part3 = (cubed - (2.0 * squared)) + amount;
  875. var part4 = cubed - squared;
  876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  882. */
  883. Vector2.Lerp = function (start, end, amount) {
  884. var x = start.x + ((end.x - start.x) * amount);
  885. var y = start.y + ((end.y - start.y) * amount);
  886. return new Vector2(x, y);
  887. };
  888. /**
  889. * Returns the dot product (float) of the vector "left" and the vector "right".
  890. */
  891. Vector2.Dot = function (left, right) {
  892. return left.x * right.x + left.y * right.y;
  893. };
  894. /**
  895. * Returns a new Vector2 equal to the normalized passed vector.
  896. */
  897. Vector2.Normalize = function (vector) {
  898. var newVector = vector.clone();
  899. newVector.normalize();
  900. return newVector;
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Minimize = function (left, right) {
  906. var x = (left.x < right.x) ? left.x : right.x;
  907. var y = (left.y < right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  912. */
  913. Vector2.Maximize = function (left, right) {
  914. var x = (left.x > right.x) ? left.x : right.x;
  915. var y = (left.y > right.y) ? left.y : right.y;
  916. return new Vector2(x, y);
  917. };
  918. /**
  919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  920. */
  921. Vector2.Transform = function (vector, transformation) {
  922. var r = Vector2.Zero();
  923. Vector2.TransformToRef(vector, transformation, r);
  924. return r;
  925. };
  926. /**
  927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  928. */
  929. Vector2.TransformToRef = function (vector, transformation, result) {
  930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  932. result.x = x;
  933. result.y = y;
  934. };
  935. /**
  936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  937. */
  938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  940. var sign = a < 0 ? -1 : 1;
  941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  944. };
  945. /**
  946. * Returns the distance (float) between the vectors "value1" and "value2".
  947. */
  948. Vector2.Distance = function (value1, value2) {
  949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  950. };
  951. /**
  952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  953. */
  954. Vector2.DistanceSquared = function (value1, value2) {
  955. var x = value1.x - value2.x;
  956. var y = value1.y - value2.y;
  957. return (x * x) + (y * y);
  958. };
  959. /**
  960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  961. */
  962. Vector2.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. /**
  968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  969. */
  970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  971. var l2 = Vector2.DistanceSquared(segA, segB);
  972. if (l2 === 0.0) {
  973. return Vector2.Distance(p, segA);
  974. }
  975. var v = segB.subtract(segA);
  976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  977. var proj = segA.add(v.multiplyByFloats(t, t));
  978. return Vector2.Distance(p, proj);
  979. };
  980. return Vector2;
  981. }());
  982. BABYLON.Vector2 = Vector2;
  983. var Vector3 = (function () {
  984. /**
  985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  986. * A Vector3 is the main object used in 3D geometry.
  987. * It can represent etiher the coordinates of a point the space, either a direction.
  988. */
  989. function Vector3(x, y, z) {
  990. this.x = x;
  991. this.y = y;
  992. this.z = z;
  993. }
  994. /**
  995. * Returns a string with the Vector3 coordinates.
  996. */
  997. Vector3.prototype.toString = function () {
  998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  999. };
  1000. /**
  1001. * Returns the string "Vector3"
  1002. */
  1003. Vector3.prototype.getClassName = function () {
  1004. return "Vector3";
  1005. };
  1006. /**
  1007. * Returns the Vector hash code.
  1008. */
  1009. Vector3.prototype.getHashCode = function () {
  1010. var hash = this.x || 0;
  1011. hash = (hash * 397) ^ (this.y || 0);
  1012. hash = (hash * 397) ^ (this.z || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Returns a new array with three elements : the coordinates the Vector3.
  1018. */
  1019. Vector3.prototype.asArray = function () {
  1020. var result = [];
  1021. this.toArray(result, 0);
  1022. return result;
  1023. };
  1024. /**
  1025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1026. * Returns the Vector3.
  1027. */
  1028. Vector3.prototype.toArray = function (array, index) {
  1029. if (index === void 0) { index = 0; }
  1030. array[index] = this.x;
  1031. array[index + 1] = this.y;
  1032. array[index + 2] = this.z;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1037. */
  1038. Vector3.prototype.toQuaternion = function () {
  1039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1044. var cosy = Math.cos(this.y * 0.5);
  1045. var siny = Math.sin(this.y * 0.5);
  1046. result.x = coszMinusx * siny;
  1047. result.y = -sinzMinusx * siny;
  1048. result.z = sinxPlusz * cosy;
  1049. result.w = cosxPlusz * cosy;
  1050. return result;
  1051. };
  1052. /**
  1053. * Adds the passed vector to the current Vector3.
  1054. * Returns the updated Vector3.
  1055. */
  1056. Vector3.prototype.addInPlace = function (otherVector) {
  1057. this.x += otherVector.x;
  1058. this.y += otherVector.y;
  1059. this.z += otherVector.z;
  1060. return this;
  1061. };
  1062. /**
  1063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1064. */
  1065. Vector3.prototype.add = function (otherVector) {
  1066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1067. };
  1068. /**
  1069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1070. * Returns the current Vector3.
  1071. */
  1072. Vector3.prototype.addToRef = function (otherVector, result) {
  1073. result.x = this.x + otherVector.x;
  1074. result.y = this.y + otherVector.y;
  1075. result.z = this.z + otherVector.z;
  1076. return this;
  1077. };
  1078. /**
  1079. * Subtract the passed vector from the current Vector3.
  1080. * Returns the updated Vector3.
  1081. */
  1082. Vector3.prototype.subtractInPlace = function (otherVector) {
  1083. this.x -= otherVector.x;
  1084. this.y -= otherVector.y;
  1085. this.z -= otherVector.z;
  1086. return this;
  1087. };
  1088. /**
  1089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1090. */
  1091. Vector3.prototype.subtract = function (otherVector) {
  1092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1093. };
  1094. /**
  1095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1096. * Returns the current Vector3.
  1097. */
  1098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1099. result.x = this.x - otherVector.x;
  1100. result.y = this.y - otherVector.y;
  1101. result.z = this.z - otherVector.z;
  1102. return this;
  1103. };
  1104. /**
  1105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1106. */
  1107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1108. return new Vector3(this.x - x, this.y - y, this.z - z);
  1109. };
  1110. /**
  1111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1112. * Returns the current Vector3.
  1113. */
  1114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1115. result.x = this.x - x;
  1116. result.y = this.y - y;
  1117. result.z = this.z - z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1122. */
  1123. Vector3.prototype.negate = function () {
  1124. return new Vector3(-this.x, -this.y, -this.z);
  1125. };
  1126. /**
  1127. * Multiplies the Vector3 coordinates by the float "scale".
  1128. * Returns the updated Vector3.
  1129. */
  1130. Vector3.prototype.scaleInPlace = function (scale) {
  1131. this.x *= scale;
  1132. this.y *= scale;
  1133. this.z *= scale;
  1134. return this;
  1135. };
  1136. /**
  1137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1138. */
  1139. Vector3.prototype.scale = function (scale) {
  1140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1141. };
  1142. /**
  1143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1144. * Returns the current Vector3.
  1145. */
  1146. Vector3.prototype.scaleToRef = function (scale, result) {
  1147. result.x = this.x * scale;
  1148. result.y = this.y * scale;
  1149. result.z = this.z * scale;
  1150. return this;
  1151. };
  1152. /**
  1153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1154. */
  1155. Vector3.prototype.equals = function (otherVector) {
  1156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1157. };
  1158. /**
  1159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1160. */
  1161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1163. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1164. };
  1165. /**
  1166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1167. */
  1168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1169. return this.x === x && this.y === y && this.z === z;
  1170. };
  1171. /**
  1172. * Muliplies the current Vector3 coordinates by the passed ones.
  1173. * Returns the updated Vector3.
  1174. */
  1175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1176. this.x *= otherVector.x;
  1177. this.y *= otherVector.y;
  1178. this.z *= otherVector.z;
  1179. return this;
  1180. };
  1181. /**
  1182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1183. */
  1184. Vector3.prototype.multiply = function (otherVector) {
  1185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1186. };
  1187. /**
  1188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1189. * Returns the current Vector3.
  1190. */
  1191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1192. result.x = this.x * otherVector.x;
  1193. result.y = this.y * otherVector.y;
  1194. result.z = this.z * otherVector.z;
  1195. return this;
  1196. };
  1197. /**
  1198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1199. */
  1200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1201. return new Vector3(this.x * x, this.y * y, this.z * z);
  1202. };
  1203. /**
  1204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1205. */
  1206. Vector3.prototype.divide = function (otherVector) {
  1207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1208. };
  1209. /**
  1210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1211. * Returns the current Vector3.
  1212. */
  1213. Vector3.prototype.divideToRef = function (otherVector, result) {
  1214. result.x = this.x / otherVector.x;
  1215. result.y = this.y / otherVector.y;
  1216. result.z = this.z / otherVector.z;
  1217. return this;
  1218. };
  1219. /**
  1220. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.MinimizeInPlace = function (other) {
  1224. if (other.x < this.x)
  1225. this.x = other.x;
  1226. if (other.y < this.y)
  1227. this.y = other.y;
  1228. if (other.z < this.z)
  1229. this.z = other.z;
  1230. return this;
  1231. };
  1232. /**
  1233. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1234. * Returns the updated Vector3.
  1235. */
  1236. Vector3.prototype.MaximizeInPlace = function (other) {
  1237. if (other.x > this.x)
  1238. this.x = other.x;
  1239. if (other.y > this.y)
  1240. this.y = other.y;
  1241. if (other.z > this.z)
  1242. this.z = other.z;
  1243. return this;
  1244. };
  1245. // Properties
  1246. /**
  1247. * Returns the length of the Vector3 (float).
  1248. */
  1249. Vector3.prototype.length = function () {
  1250. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1251. };
  1252. /**
  1253. * Returns the squared length of the Vector3 (float).
  1254. */
  1255. Vector3.prototype.lengthSquared = function () {
  1256. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1257. };
  1258. // Methods
  1259. /**
  1260. * Normalize the current Vector3.
  1261. * Returns the updated Vector3.
  1262. */
  1263. Vector3.prototype.normalize = function () {
  1264. var len = this.length();
  1265. if (len === 0 || len === 1.0)
  1266. return this;
  1267. var num = 1.0 / len;
  1268. this.x *= num;
  1269. this.y *= num;
  1270. this.z *= num;
  1271. return this;
  1272. };
  1273. /**
  1274. * Returns a new Vector3 copied from the current Vector3.
  1275. */
  1276. Vector3.prototype.clone = function () {
  1277. return new Vector3(this.x, this.y, this.z);
  1278. };
  1279. /**
  1280. * Copies the passed vector coordinates to the current Vector3 ones.
  1281. * Returns the updated Vector3.
  1282. */
  1283. Vector3.prototype.copyFrom = function (source) {
  1284. this.x = source.x;
  1285. this.y = source.y;
  1286. this.z = source.z;
  1287. return this;
  1288. };
  1289. /**
  1290. * Copies the passed floats to the current Vector3 coordinates.
  1291. * Returns the updated Vector3.
  1292. */
  1293. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. return this;
  1298. };
  1299. /**
  1300. * Copies the passed floats to the current Vector3 coordinates.
  1301. * Returns the updated Vector3.
  1302. */
  1303. Vector3.prototype.set = function (x, y, z) {
  1304. return this.copyFromFloats(x, y, z);
  1305. };
  1306. // Statics
  1307. /**
  1308. *
  1309. */
  1310. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1311. var d0 = Vector3.Dot(vector0, axis) - size;
  1312. var d1 = Vector3.Dot(vector1, axis) - size;
  1313. var s = d0 / (d0 - d1);
  1314. return s;
  1315. };
  1316. /**
  1317. * Returns a new Vector3 set from the index "offset" of the passed array.
  1318. */
  1319. Vector3.FromArray = function (array, offset) {
  1320. if (!offset) {
  1321. offset = 0;
  1322. }
  1323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1324. };
  1325. /**
  1326. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1327. * This function is deprecated. Use FromArray instead.
  1328. */
  1329. Vector3.FromFloatArray = function (array, offset) {
  1330. return Vector3.FromArray(array, offset);
  1331. };
  1332. /**
  1333. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1334. */
  1335. Vector3.FromArrayToRef = function (array, offset, result) {
  1336. result.x = array[offset];
  1337. result.y = array[offset + 1];
  1338. result.z = array[offset + 2];
  1339. };
  1340. /**
  1341. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1342. * This function is deprecated. Use FromArrayToRef instead.
  1343. */
  1344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1345. return Vector3.FromArrayToRef(array, offset, result);
  1346. };
  1347. /**
  1348. * Sets the passed vector "result" with the passed floats.
  1349. */
  1350. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1351. result.x = x;
  1352. result.y = y;
  1353. result.z = z;
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1357. */
  1358. Vector3.Zero = function () {
  1359. return new Vector3(0.0, 0.0, 0.0);
  1360. };
  1361. /**
  1362. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1363. */
  1364. Vector3.One = function () {
  1365. return new Vector3(1.0, 1.0, 1.0);
  1366. };
  1367. /**
  1368. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1369. */
  1370. Vector3.Up = function () {
  1371. return new Vector3(0.0, 1.0, 0.0);
  1372. };
  1373. /**
  1374. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1375. */
  1376. Vector3.Forward = function () {
  1377. return new Vector3(0.0, 0.0, 1.0);
  1378. };
  1379. /**
  1380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1381. */
  1382. Vector3.Right = function () {
  1383. return new Vector3(1.0, 0.0, 0.0);
  1384. };
  1385. /**
  1386. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1387. */
  1388. Vector3.Left = function () {
  1389. return new Vector3(-1.0, 0.0, 0.0);
  1390. };
  1391. /**
  1392. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1393. * This method computes tranformed coordinates only, not transformed direction vectors.
  1394. */
  1395. Vector3.TransformCoordinates = function (vector, transformation) {
  1396. var result = Vector3.Zero();
  1397. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1398. return result;
  1399. };
  1400. /**
  1401. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1402. * This method computes tranformed coordinates only, not transformed direction vectors.
  1403. */
  1404. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1408. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1409. result.x = x / w;
  1410. result.y = y / w;
  1411. result.z = z / w;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1418. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1419. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1420. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1421. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1422. result.x = rx / rw;
  1423. result.y = ry / rw;
  1424. result.z = rz / rw;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1428. * This methods computes transformed normalized direction vectors only.
  1429. */
  1430. Vector3.TransformNormal = function (vector, transformation) {
  1431. var result = Vector3.Zero();
  1432. Vector3.TransformNormalToRef(vector, transformation, result);
  1433. return result;
  1434. };
  1435. /**
  1436. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1437. * This methods computes transformed normalized direction vectors only.
  1438. */
  1439. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1443. result.x = x;
  1444. result.y = y;
  1445. result.z = z;
  1446. };
  1447. /**
  1448. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1449. * This methods computes transformed normalized direction vectors only.
  1450. */
  1451. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1452. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1453. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1454. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1455. };
  1456. /**
  1457. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1458. */
  1459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1460. var squared = amount * amount;
  1461. var cubed = amount * squared;
  1462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1471. return new Vector3(x, y, z);
  1472. };
  1473. /**
  1474. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1477. */
  1478. Vector3.Clamp = function (value, min, max) {
  1479. var x = value.x;
  1480. x = (x > max.x) ? max.x : x;
  1481. x = (x < min.x) ? min.x : x;
  1482. var y = value.y;
  1483. y = (y > max.y) ? max.y : y;
  1484. y = (y < min.y) ? min.y : y;
  1485. var z = value.z;
  1486. z = (z > max.z) ? max.z : z;
  1487. z = (z < min.z) ? min.z : z;
  1488. return new Vector3(x, y, z);
  1489. };
  1490. /**
  1491. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1492. */
  1493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1494. var squared = amount * amount;
  1495. var cubed = amount * squared;
  1496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1498. var part3 = (cubed - (2.0 * squared)) + amount;
  1499. var part4 = cubed - squared;
  1500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1503. return new Vector3(x, y, z);
  1504. };
  1505. /**
  1506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1507. */
  1508. Vector3.Lerp = function (start, end, amount) {
  1509. var result = new Vector3(0, 0, 0);
  1510. Vector3.LerpToRef(start, end, amount, result);
  1511. return result;
  1512. };
  1513. /**
  1514. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1515. */
  1516. Vector3.LerpToRef = function (start, end, amount, result) {
  1517. result.x = start.x + ((end.x - start.x) * amount);
  1518. result.y = start.y + ((end.y - start.y) * amount);
  1519. result.z = start.z + ((end.z - start.z) * amount);
  1520. };
  1521. /**
  1522. * Returns the dot product (float) between the vectors "left" and "right".
  1523. */
  1524. Vector3.Dot = function (left, right) {
  1525. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1526. };
  1527. /**
  1528. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1529. * The cross product is then orthogonal to both "left" and "right".
  1530. */
  1531. Vector3.Cross = function (left, right) {
  1532. var result = Vector3.Zero();
  1533. Vector3.CrossToRef(left, right, result);
  1534. return result;
  1535. };
  1536. /**
  1537. * Sets the passed vector "result" with the cross product of "left" and "right".
  1538. * The cross product is then orthogonal to both "left" and "right".
  1539. */
  1540. Vector3.CrossToRef = function (left, right, result) {
  1541. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1542. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1543. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1544. result.copyFrom(MathTmp.Vector3[0]);
  1545. };
  1546. /**
  1547. * Returns a new Vector3 as the normalization of the passed vector.
  1548. */
  1549. Vector3.Normalize = function (vector) {
  1550. var result = Vector3.Zero();
  1551. Vector3.NormalizeToRef(vector, result);
  1552. return result;
  1553. };
  1554. /**
  1555. * Sets the passed vector "result" with the normalization of the passed first vector.
  1556. */
  1557. Vector3.NormalizeToRef = function (vector, result) {
  1558. result.copyFrom(vector);
  1559. result.normalize();
  1560. };
  1561. Vector3.Project = function (vector, world, transform, viewport) {
  1562. var cw = viewport.width;
  1563. var ch = viewport.height;
  1564. var cx = viewport.x;
  1565. var cy = viewport.y;
  1566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1567. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1568. var matrix = MathTmp.Matrix[0];
  1569. world.multiplyToRef(transform, matrix);
  1570. matrix.multiplyToRef(viewportMatrix, matrix);
  1571. return Vector3.TransformCoordinates(vector, matrix);
  1572. };
  1573. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1574. var matrix = MathTmp.Matrix[0];
  1575. world.multiplyToRef(transform, matrix);
  1576. matrix.invert();
  1577. source.x = source.x / viewportWidth * 2 - 1;
  1578. source.y = -(source.y / viewportHeight * 2 - 1);
  1579. var vector = Vector3.TransformCoordinates(source, matrix);
  1580. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1581. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1582. vector = vector.scale(1.0 / num);
  1583. }
  1584. return vector;
  1585. };
  1586. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1587. var matrix = MathTmp.Matrix[0];
  1588. world.multiplyToRef(view, matrix);
  1589. matrix.multiplyToRef(projection, matrix);
  1590. matrix.invert();
  1591. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1592. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1593. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1594. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Minimize = function (left, right) {
  1600. var min = left.clone();
  1601. min.MinimizeInPlace(right);
  1602. return min;
  1603. };
  1604. Vector3.Maximize = function (left, right) {
  1605. var max = left.clone();
  1606. max.MaximizeInPlace(right);
  1607. return max;
  1608. };
  1609. /**
  1610. * Returns the distance (float) between the vectors "value1" and "value2".
  1611. */
  1612. Vector3.Distance = function (value1, value2) {
  1613. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1614. };
  1615. /**
  1616. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1617. */
  1618. Vector3.DistanceSquared = function (value1, value2) {
  1619. var x = value1.x - value2.x;
  1620. var y = value1.y - value2.y;
  1621. var z = value1.z - value2.z;
  1622. return (x * x) + (y * y) + (z * z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 located at the center between "value1" and "value2".
  1626. */
  1627. Vector3.Center = function (value1, value2) {
  1628. var center = value1.add(value2);
  1629. center.scaleInPlace(0.5);
  1630. return center;
  1631. };
  1632. /**
  1633. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1634. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1635. * to something in order to rotate it from its local system to the given target system.
  1636. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1637. * Returns a new Vector3.
  1638. */
  1639. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1640. var rotation = Vector3.Zero();
  1641. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1642. return rotation;
  1643. };
  1644. /**
  1645. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1646. */
  1647. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1648. var quat = MathTmp.Quaternion[0];
  1649. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1650. quat.toEulerAnglesToRef(ref);
  1651. };
  1652. return Vector3;
  1653. }());
  1654. BABYLON.Vector3 = Vector3;
  1655. //Vector4 class created for EulerAngle class conversion to Quaternion
  1656. var Vector4 = (function () {
  1657. /**
  1658. * Creates a Vector4 object from the passed floats.
  1659. */
  1660. function Vector4(x, y, z, w) {
  1661. this.x = x;
  1662. this.y = y;
  1663. this.z = z;
  1664. this.w = w;
  1665. }
  1666. /**
  1667. * Returns the string with the Vector4 coordinates.
  1668. */
  1669. Vector4.prototype.toString = function () {
  1670. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1671. };
  1672. /**
  1673. * Returns the string "Vector4".
  1674. */
  1675. Vector4.prototype.getClassName = function () {
  1676. return "Vector4";
  1677. };
  1678. /**
  1679. * Returns the Vector4 hash code.
  1680. */
  1681. Vector4.prototype.getHashCode = function () {
  1682. var hash = this.x || 0;
  1683. hash = (hash * 397) ^ (this.y || 0);
  1684. hash = (hash * 397) ^ (this.z || 0);
  1685. hash = (hash * 397) ^ (this.w || 0);
  1686. return hash;
  1687. };
  1688. // Operators
  1689. /**
  1690. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1691. */
  1692. Vector4.prototype.asArray = function () {
  1693. var result = [];
  1694. this.toArray(result, 0);
  1695. return result;
  1696. };
  1697. /**
  1698. * Populates the passed array from the passed index with the Vector4 coordinates.
  1699. * Returns the Vector4.
  1700. */
  1701. Vector4.prototype.toArray = function (array, index) {
  1702. if (index === undefined) {
  1703. index = 0;
  1704. }
  1705. array[index] = this.x;
  1706. array[index + 1] = this.y;
  1707. array[index + 2] = this.z;
  1708. array[index + 3] = this.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Adds the passed vector to the current Vector4.
  1713. * Returns the updated Vector4.
  1714. */
  1715. Vector4.prototype.addInPlace = function (otherVector) {
  1716. this.x += otherVector.x;
  1717. this.y += otherVector.y;
  1718. this.z += otherVector.z;
  1719. this.w += otherVector.w;
  1720. return this;
  1721. };
  1722. /**
  1723. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1724. */
  1725. Vector4.prototype.add = function (otherVector) {
  1726. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1727. };
  1728. /**
  1729. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1730. * Returns the current Vector4.
  1731. */
  1732. Vector4.prototype.addToRef = function (otherVector, result) {
  1733. result.x = this.x + otherVector.x;
  1734. result.y = this.y + otherVector.y;
  1735. result.z = this.z + otherVector.z;
  1736. result.w = this.w + otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Subtract in place the passed vector from the current Vector4.
  1741. * Returns the updated Vector4.
  1742. */
  1743. Vector4.prototype.subtractInPlace = function (otherVector) {
  1744. this.x -= otherVector.x;
  1745. this.y -= otherVector.y;
  1746. this.z -= otherVector.z;
  1747. this.w -= otherVector.w;
  1748. return this;
  1749. };
  1750. /**
  1751. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1752. */
  1753. Vector4.prototype.subtract = function (otherVector) {
  1754. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1755. };
  1756. /**
  1757. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1758. * Returns the current Vector4.
  1759. */
  1760. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1761. result.x = this.x - otherVector.x;
  1762. result.y = this.y - otherVector.y;
  1763. result.z = this.z - otherVector.z;
  1764. result.w = this.w - otherVector.w;
  1765. return this;
  1766. };
  1767. /**
  1768. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1769. */
  1770. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1771. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1772. };
  1773. /**
  1774. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1775. * Returns the current Vector4.
  1776. */
  1777. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1778. result.x = this.x - x;
  1779. result.y = this.y - y;
  1780. result.z = this.z - z;
  1781. result.w = this.w - w;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1786. */
  1787. Vector4.prototype.negate = function () {
  1788. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1789. };
  1790. /**
  1791. * Multiplies the current Vector4 coordinates by scale (float).
  1792. * Returns the updated Vector4.
  1793. */
  1794. Vector4.prototype.scaleInPlace = function (scale) {
  1795. this.x *= scale;
  1796. this.y *= scale;
  1797. this.z *= scale;
  1798. this.w *= scale;
  1799. return this;
  1800. };
  1801. /**
  1802. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1803. */
  1804. Vector4.prototype.scale = function (scale) {
  1805. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1806. };
  1807. /**
  1808. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1809. * Returns the current Vector4.
  1810. */
  1811. Vector4.prototype.scaleToRef = function (scale, result) {
  1812. result.x = this.x * scale;
  1813. result.y = this.y * scale;
  1814. result.z = this.z * scale;
  1815. result.w = this.w * scale;
  1816. return this;
  1817. };
  1818. /**
  1819. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1820. */
  1821. Vector4.prototype.equals = function (otherVector) {
  1822. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1823. };
  1824. /**
  1825. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1826. */
  1827. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1828. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1829. return otherVector
  1830. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1831. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1832. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1833. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1834. };
  1835. /**
  1836. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1837. */
  1838. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1839. return this.x === x && this.y === y && this.z === z && this.w === w;
  1840. };
  1841. /**
  1842. * Multiplies in place the current Vector4 by the passed one.
  1843. * Returns the updated Vector4.
  1844. */
  1845. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1846. this.x *= otherVector.x;
  1847. this.y *= otherVector.y;
  1848. this.z *= otherVector.z;
  1849. this.w *= otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1854. */
  1855. Vector4.prototype.multiply = function (otherVector) {
  1856. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1857. };
  1858. /**
  1859. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1863. result.x = this.x * otherVector.x;
  1864. result.y = this.y * otherVector.y;
  1865. result.z = this.z * otherVector.z;
  1866. result.w = this.w * otherVector.w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1871. */
  1872. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1873. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1874. };
  1875. /**
  1876. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1877. */
  1878. Vector4.prototype.divide = function (otherVector) {
  1879. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1880. };
  1881. /**
  1882. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1883. * Returns the current Vector4.
  1884. */
  1885. Vector4.prototype.divideToRef = function (otherVector, result) {
  1886. result.x = this.x / otherVector.x;
  1887. result.y = this.y / otherVector.y;
  1888. result.z = this.z / otherVector.z;
  1889. result.w = this.w / otherVector.w;
  1890. return this;
  1891. };
  1892. /**
  1893. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1894. */
  1895. Vector4.prototype.MinimizeInPlace = function (other) {
  1896. if (other.x < this.x)
  1897. this.x = other.x;
  1898. if (other.y < this.y)
  1899. this.y = other.y;
  1900. if (other.z < this.z)
  1901. this.z = other.z;
  1902. if (other.w < this.w)
  1903. this.w = other.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1908. */
  1909. Vector4.prototype.MaximizeInPlace = function (other) {
  1910. if (other.x > this.x)
  1911. this.x = other.x;
  1912. if (other.y > this.y)
  1913. this.y = other.y;
  1914. if (other.z > this.z)
  1915. this.z = other.z;
  1916. if (other.w > this.w)
  1917. this.w = other.w;
  1918. return this;
  1919. };
  1920. // Properties
  1921. /**
  1922. * Returns the Vector4 length (float).
  1923. */
  1924. Vector4.prototype.length = function () {
  1925. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1926. };
  1927. /**
  1928. * Returns the Vector4 squared length (float).
  1929. */
  1930. Vector4.prototype.lengthSquared = function () {
  1931. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1932. };
  1933. // Methods
  1934. /**
  1935. * Normalizes in place the Vector4.
  1936. * Returns the updated Vector4.
  1937. */
  1938. Vector4.prototype.normalize = function () {
  1939. var len = this.length();
  1940. if (len === 0)
  1941. return this;
  1942. var num = 1.0 / len;
  1943. this.x *= num;
  1944. this.y *= num;
  1945. this.z *= num;
  1946. this.w *= num;
  1947. return this;
  1948. };
  1949. /**
  1950. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1951. */
  1952. Vector4.prototype.toVector3 = function () {
  1953. return new Vector3(this.x, this.y, this.z);
  1954. };
  1955. /**
  1956. * Returns a new Vector4 copied from the current one.
  1957. */
  1958. Vector4.prototype.clone = function () {
  1959. return new Vector4(this.x, this.y, this.z, this.w);
  1960. };
  1961. /**
  1962. * Updates the current Vector4 with the passed one coordinates.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFrom = function (source) {
  1966. this.x = source.x;
  1967. this.y = source.y;
  1968. this.z = source.z;
  1969. this.w = source.w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1977. this.x = x;
  1978. this.y = y;
  1979. this.z = z;
  1980. this.w = w;
  1981. return this;
  1982. };
  1983. /**
  1984. * Updates the current Vector4 coordinates with the passed floats.
  1985. * Returns the updated Vector4.
  1986. */
  1987. Vector4.prototype.set = function (x, y, z, w) {
  1988. return this.copyFromFloats(x, y, z, w);
  1989. };
  1990. // Statics
  1991. /**
  1992. * Returns a new Vector4 set from the starting index of the passed array.
  1993. */
  1994. Vector4.FromArray = function (array, offset) {
  1995. if (!offset) {
  1996. offset = 0;
  1997. }
  1998. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1999. };
  2000. /**
  2001. * Updates the passed vector "result" from the starting index of the passed array.
  2002. */
  2003. Vector4.FromArrayToRef = function (array, offset, result) {
  2004. result.x = array[offset];
  2005. result.y = array[offset + 1];
  2006. result.z = array[offset + 2];
  2007. result.w = array[offset + 3];
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2011. */
  2012. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2013. Vector4.FromArrayToRef(array, offset, result);
  2014. };
  2015. /**
  2016. * Updates the passed vector "result" coordinates from the passed floats.
  2017. */
  2018. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2019. result.x = x;
  2020. result.y = y;
  2021. result.z = z;
  2022. result.w = w;
  2023. };
  2024. /**
  2025. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2026. */
  2027. Vector4.Zero = function () {
  2028. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2032. */
  2033. Vector4.One = function () {
  2034. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2035. };
  2036. /**
  2037. * Returns a new normalized Vector4 from the passed one.
  2038. */
  2039. Vector4.Normalize = function (vector) {
  2040. var result = Vector4.Zero();
  2041. Vector4.NormalizeToRef(vector, result);
  2042. return result;
  2043. };
  2044. /**
  2045. * Updates the passed vector "result" from the normalization of the passed one.
  2046. */
  2047. Vector4.NormalizeToRef = function (vector, result) {
  2048. result.copyFrom(vector);
  2049. result.normalize();
  2050. };
  2051. Vector4.Minimize = function (left, right) {
  2052. var min = left.clone();
  2053. min.MinimizeInPlace(right);
  2054. return min;
  2055. };
  2056. Vector4.Maximize = function (left, right) {
  2057. var max = left.clone();
  2058. max.MaximizeInPlace(right);
  2059. return max;
  2060. };
  2061. /**
  2062. * Returns the distance (float) between the vectors "value1" and "value2".
  2063. */
  2064. Vector4.Distance = function (value1, value2) {
  2065. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2066. };
  2067. /**
  2068. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.DistanceSquared = function (value1, value2) {
  2071. var x = value1.x - value2.x;
  2072. var y = value1.y - value2.y;
  2073. var z = value1.z - value2.z;
  2074. var w = value1.w - value2.w;
  2075. return (x * x) + (y * y) + (z * z) + (w * w);
  2076. };
  2077. /**
  2078. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2079. */
  2080. Vector4.Center = function (value1, value2) {
  2081. var center = value1.add(value2);
  2082. center.scaleInPlace(0.5);
  2083. return center;
  2084. };
  2085. /**
  2086. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2087. * This methods computes transformed normalized direction vectors only.
  2088. */
  2089. Vector4.TransformNormal = function (vector, transformation) {
  2090. var result = Vector4.Zero();
  2091. Vector4.TransformNormalToRef(vector, transformation, result);
  2092. return result;
  2093. };
  2094. /**
  2095. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2096. * This methods computes transformed normalized direction vectors only.
  2097. */
  2098. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2099. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2100. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2101. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2102. result.x = x;
  2103. result.y = y;
  2104. result.z = z;
  2105. result.w = vector.w;
  2106. };
  2107. /**
  2108. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2109. * This methods computes transformed normalized direction vectors only.
  2110. */
  2111. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2112. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2113. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2114. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2115. result.w = w;
  2116. };
  2117. return Vector4;
  2118. }());
  2119. BABYLON.Vector4 = Vector4;
  2120. var Size = (function () {
  2121. /**
  2122. * Creates a Size object from the passed width and height (floats).
  2123. */
  2124. function Size(width, height) {
  2125. this.width = width;
  2126. this.height = height;
  2127. }
  2128. // Returns a string with the Size width and height.
  2129. Size.prototype.toString = function () {
  2130. return "{W: " + this.width + ", H: " + this.height + "}";
  2131. };
  2132. /**
  2133. * Returns the string "Size"
  2134. */
  2135. Size.prototype.getClassName = function () {
  2136. return "Size";
  2137. };
  2138. /**
  2139. * Returns the Size hash code.
  2140. */
  2141. Size.prototype.getHashCode = function () {
  2142. var hash = this.width || 0;
  2143. hash = (hash * 397) ^ (this.height || 0);
  2144. return hash;
  2145. };
  2146. /**
  2147. * Updates the current size from the passed one.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.copyFrom = function (src) {
  2151. this.width = src.width;
  2152. this.height = src.height;
  2153. };
  2154. /**
  2155. * Updates in place the current Size from the passed floats.
  2156. * Returns the updated Size.
  2157. */
  2158. Size.prototype.copyFromFloats = function (width, height) {
  2159. this.width = width;
  2160. this.height = height;
  2161. return this;
  2162. };
  2163. /**
  2164. * Updates in place the current Size from the passed floats.
  2165. * Returns the updated Size.
  2166. */
  2167. Size.prototype.set = function (width, height) {
  2168. return this.copyFromFloats(width, height);
  2169. };
  2170. /**
  2171. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2172. */
  2173. Size.prototype.multiplyByFloats = function (w, h) {
  2174. return new Size(this.width * w, this.height * h);
  2175. };
  2176. /**
  2177. * Returns a new Size copied from the passed one.
  2178. */
  2179. Size.prototype.clone = function () {
  2180. return new Size(this.width, this.height);
  2181. };
  2182. /**
  2183. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2184. */
  2185. Size.prototype.equals = function (other) {
  2186. if (!other) {
  2187. return false;
  2188. }
  2189. return (this.width === other.width) && (this.height === other.height);
  2190. };
  2191. Object.defineProperty(Size.prototype, "surface", {
  2192. /**
  2193. * Returns the surface of the Size : width * height (float).
  2194. */
  2195. get: function () {
  2196. return this.width * this.height;
  2197. },
  2198. enumerable: true,
  2199. configurable: true
  2200. });
  2201. /**
  2202. * Returns a new Size set to (0.0, 0.0)
  2203. */
  2204. Size.Zero = function () {
  2205. return new Size(0.0, 0.0);
  2206. };
  2207. /**
  2208. * Returns a new Size set as the addition result of the current Size and the passed one.
  2209. */
  2210. Size.prototype.add = function (otherSize) {
  2211. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2212. return r;
  2213. };
  2214. /**
  2215. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2216. */
  2217. Size.prototype.subtract = function (otherSize) {
  2218. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2223. */
  2224. Size.Lerp = function (start, end, amount) {
  2225. var w = start.width + ((end.width - start.width) * amount);
  2226. var h = start.height + ((end.height - start.height) * amount);
  2227. return new Size(w, h);
  2228. };
  2229. return Size;
  2230. }());
  2231. BABYLON.Size = Size;
  2232. var Quaternion = (function () {
  2233. /**
  2234. * Creates a new Quaternion from the passed floats.
  2235. */
  2236. function Quaternion(x, y, z, w) {
  2237. if (x === void 0) { x = 0.0; }
  2238. if (y === void 0) { y = 0.0; }
  2239. if (z === void 0) { z = 0.0; }
  2240. if (w === void 0) { w = 1.0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. this.z = z;
  2244. this.w = w;
  2245. }
  2246. /**
  2247. * Returns a string with the Quaternion coordinates.
  2248. */
  2249. Quaternion.prototype.toString = function () {
  2250. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2251. };
  2252. /**
  2253. * Returns the string "Quaternion".
  2254. */
  2255. Quaternion.prototype.getClassName = function () {
  2256. return "Quaternion";
  2257. };
  2258. /**
  2259. * Returns the Quaternion hash code.
  2260. */
  2261. Quaternion.prototype.getHashCode = function () {
  2262. var hash = this.x || 0;
  2263. hash = (hash * 397) ^ (this.y || 0);
  2264. hash = (hash * 397) ^ (this.z || 0);
  2265. hash = (hash * 397) ^ (this.w || 0);
  2266. return hash;
  2267. };
  2268. /**
  2269. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2270. */
  2271. Quaternion.prototype.asArray = function () {
  2272. return [this.x, this.y, this.z, this.w];
  2273. };
  2274. /**
  2275. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2276. */
  2277. Quaternion.prototype.equals = function (otherQuaternion) {
  2278. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2279. };
  2280. /**
  2281. * Returns a new Quaternion copied from the current one.
  2282. */
  2283. Quaternion.prototype.clone = function () {
  2284. return new Quaternion(this.x, this.y, this.z, this.w);
  2285. };
  2286. /**
  2287. * Updates the current Quaternion from the passed one coordinates.
  2288. * Returns the updated Quaterion.
  2289. */
  2290. Quaternion.prototype.copyFrom = function (other) {
  2291. this.x = other.x;
  2292. this.y = other.y;
  2293. this.z = other.z;
  2294. this.w = other.w;
  2295. return this;
  2296. };
  2297. /**
  2298. * Updates the current Quaternion from the passed float coordinates.
  2299. * Returns the updated Quaterion.
  2300. */
  2301. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2302. this.x = x;
  2303. this.y = y;
  2304. this.z = z;
  2305. this.w = w;
  2306. return this;
  2307. };
  2308. /**
  2309. * Updates the current Quaternion from the passed float coordinates.
  2310. * Returns the updated Quaterion.
  2311. */
  2312. Quaternion.prototype.set = function (x, y, z, w) {
  2313. return this.copyFromFloats(x, y, z, w);
  2314. };
  2315. /**
  2316. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2317. */
  2318. Quaternion.prototype.add = function (other) {
  2319. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2320. };
  2321. /**
  2322. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2323. */
  2324. Quaternion.prototype.subtract = function (other) {
  2325. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2326. };
  2327. /**
  2328. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2329. */
  2330. Quaternion.prototype.scale = function (value) {
  2331. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2332. };
  2333. /**
  2334. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2335. */
  2336. Quaternion.prototype.multiply = function (q1) {
  2337. var result = new Quaternion(0, 0, 0, 1.0);
  2338. this.multiplyToRef(q1, result);
  2339. return result;
  2340. };
  2341. /**
  2342. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2343. * Returns the current Quaternion.
  2344. */
  2345. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2346. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2347. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2348. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2349. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2350. result.copyFromFloats(x, y, z, w);
  2351. return this;
  2352. };
  2353. /**
  2354. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2355. * Returns the updated Quaternion.
  2356. */
  2357. Quaternion.prototype.multiplyInPlace = function (q1) {
  2358. this.multiplyToRef(q1, this);
  2359. return this;
  2360. };
  2361. /**
  2362. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2363. * Returns the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugateToRef = function (ref) {
  2366. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2367. return this;
  2368. };
  2369. /**
  2370. * Conjugates in place the current Quaternion.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.conjugateInPlace = function () {
  2374. this.x *= -1;
  2375. this.y *= -1;
  2376. this.z *= -1;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2381. */
  2382. Quaternion.prototype.conjugate = function () {
  2383. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2384. return result;
  2385. };
  2386. /**
  2387. * Returns the Quaternion length (float).
  2388. */
  2389. Quaternion.prototype.length = function () {
  2390. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2391. };
  2392. /**
  2393. * Normalize in place the current Quaternion.
  2394. * Returns the updated Quaternion.
  2395. */
  2396. Quaternion.prototype.normalize = function () {
  2397. var length = 1.0 / this.length();
  2398. this.x *= length;
  2399. this.y *= length;
  2400. this.z *= length;
  2401. this.w *= length;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAngles = function (order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var result = Vector3.Zero();
  2410. this.toEulerAnglesToRef(result, order);
  2411. return result;
  2412. };
  2413. /**
  2414. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2415. * Returns the current Quaternion.
  2416. */
  2417. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2418. if (order === void 0) { order = "YZX"; }
  2419. var qz = this.z;
  2420. var qx = this.x;
  2421. var qy = this.y;
  2422. var qw = this.w;
  2423. var sqw = qw * qw;
  2424. var sqz = qz * qz;
  2425. var sqx = qx * qx;
  2426. var sqy = qy * qy;
  2427. var zAxisY = qy * qz - qx * qw;
  2428. var limit = .4999999;
  2429. if (zAxisY < -limit) {
  2430. result.y = 2 * Math.atan2(qy, qw);
  2431. result.x = Math.PI / 2;
  2432. result.z = 0;
  2433. }
  2434. else if (zAxisY > limit) {
  2435. result.y = 2 * Math.atan2(qy, qw);
  2436. result.x = -Math.PI / 2;
  2437. result.z = 0;
  2438. }
  2439. else {
  2440. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2441. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2442. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2443. }
  2444. return this;
  2445. };
  2446. /**
  2447. * Updates the passed rotation matrix with the current Quaternion values.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.toRotationMatrix = function (result) {
  2451. var xx = this.x * this.x;
  2452. var yy = this.y * this.y;
  2453. var zz = this.z * this.z;
  2454. var xy = this.x * this.y;
  2455. var zw = this.z * this.w;
  2456. var zx = this.z * this.x;
  2457. var yw = this.y * this.w;
  2458. var yz = this.y * this.z;
  2459. var xw = this.x * this.w;
  2460. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2461. result.m[1] = 2.0 * (xy + zw);
  2462. result.m[2] = 2.0 * (zx - yw);
  2463. result.m[3] = 0;
  2464. result.m[4] = 2.0 * (xy - zw);
  2465. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2466. result.m[6] = 2.0 * (yz + xw);
  2467. result.m[7] = 0;
  2468. result.m[8] = 2.0 * (zx + yw);
  2469. result.m[9] = 2.0 * (yz - xw);
  2470. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2471. result.m[11] = 0;
  2472. result.m[12] = 0;
  2473. result.m[13] = 0;
  2474. result.m[14] = 0;
  2475. result.m[15] = 1.0;
  2476. result._markAsUpdated();
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed rotation matrix values.
  2481. * Returns the updated Quaternion.
  2482. */
  2483. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2484. Quaternion.FromRotationMatrixToRef(matrix, this);
  2485. return this;
  2486. };
  2487. // Statics
  2488. /**
  2489. * Returns a new Quaternion set from the passed rotation matrix values.
  2490. */
  2491. Quaternion.FromRotationMatrix = function (matrix) {
  2492. var result = new Quaternion();
  2493. Quaternion.FromRotationMatrixToRef(matrix, result);
  2494. return result;
  2495. };
  2496. /**
  2497. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2498. */
  2499. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2500. var data = matrix.m;
  2501. var m11 = data[0], m12 = data[4], m13 = data[8];
  2502. var m21 = data[1], m22 = data[5], m23 = data[9];
  2503. var m31 = data[2], m32 = data[6], m33 = data[10];
  2504. var trace = m11 + m22 + m33;
  2505. var s;
  2506. if (trace > 0) {
  2507. s = 0.5 / Math.sqrt(trace + 1.0);
  2508. result.w = 0.25 / s;
  2509. result.x = (m32 - m23) * s;
  2510. result.y = (m13 - m31) * s;
  2511. result.z = (m21 - m12) * s;
  2512. }
  2513. else if (m11 > m22 && m11 > m33) {
  2514. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2515. result.w = (m32 - m23) / s;
  2516. result.x = 0.25 * s;
  2517. result.y = (m12 + m21) / s;
  2518. result.z = (m13 + m31) / s;
  2519. }
  2520. else if (m22 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2522. result.w = (m13 - m31) / s;
  2523. result.x = (m12 + m21) / s;
  2524. result.y = 0.25 * s;
  2525. result.z = (m23 + m32) / s;
  2526. }
  2527. else {
  2528. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2529. result.w = (m21 - m12) / s;
  2530. result.x = (m13 + m31) / s;
  2531. result.y = (m23 + m32) / s;
  2532. result.z = 0.25 * s;
  2533. }
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2537. */
  2538. Quaternion.Zero = function () {
  2539. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion as the inverted current Quaternion.
  2543. */
  2544. Quaternion.Inverse = function (q) {
  2545. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2546. };
  2547. /**
  2548. * Returns the identity Quaternion.
  2549. */
  2550. Quaternion.Identity = function () {
  2551. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2552. };
  2553. Quaternion.IsIdentity = function (quaternion) {
  2554. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2558. */
  2559. Quaternion.RotationAxis = function (axis, angle) {
  2560. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2561. };
  2562. /**
  2563. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2564. */
  2565. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2566. var sin = Math.sin(angle / 2);
  2567. axis.normalize();
  2568. result.w = Math.cos(angle / 2);
  2569. result.x = axis.x * sin;
  2570. result.y = axis.y * sin;
  2571. result.z = axis.z * sin;
  2572. return result;
  2573. };
  2574. /**
  2575. * Retuns a new Quaternion set from the starting index of the passed array.
  2576. */
  2577. Quaternion.FromArray = function (array, offset) {
  2578. if (!offset) {
  2579. offset = 0;
  2580. }
  2581. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2585. */
  2586. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2587. var q = new Quaternion();
  2588. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2589. return q;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2593. */
  2594. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2595. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2596. var halfRoll = roll * 0.5;
  2597. var halfPitch = pitch * 0.5;
  2598. var halfYaw = yaw * 0.5;
  2599. var sinRoll = Math.sin(halfRoll);
  2600. var cosRoll = Math.cos(halfRoll);
  2601. var sinPitch = Math.sin(halfPitch);
  2602. var cosPitch = Math.cos(halfPitch);
  2603. var sinYaw = Math.sin(halfYaw);
  2604. var cosYaw = Math.cos(halfYaw);
  2605. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2606. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2607. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2608. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2609. };
  2610. /**
  2611. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2612. */
  2613. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2614. var result = new Quaternion();
  2615. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2620. */
  2621. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2622. // Produces a quaternion from Euler angles in the z-x-z orientation
  2623. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2624. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2625. var halfBeta = beta * 0.5;
  2626. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2627. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2628. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2629. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2637. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2639. return quat;
  2640. };
  2641. /**
  2642. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2643. * cf to Vector3.RotationFromAxis() documentation.
  2644. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2645. */
  2646. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2647. var rotMat = MathTmp.Matrix[0];
  2648. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2649. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2650. };
  2651. Quaternion.Slerp = function (left, right, amount) {
  2652. var result = Quaternion.Identity();
  2653. Quaternion.SlerpToRef(left, right, amount, result);
  2654. return result;
  2655. };
  2656. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2657. var num2;
  2658. var num3;
  2659. var num = amount;
  2660. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2661. var flag = false;
  2662. if (num4 < 0) {
  2663. flag = true;
  2664. num4 = -num4;
  2665. }
  2666. if (num4 > 0.999999) {
  2667. num3 = 1 - num;
  2668. num2 = flag ? -num : num;
  2669. }
  2670. else {
  2671. var num5 = Math.acos(num4);
  2672. var num6 = (1.0 / Math.sin(num5));
  2673. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2674. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2675. }
  2676. result.x = (num3 * left.x) + (num2 * right.x);
  2677. result.y = (num3 * left.y) + (num2 * right.y);
  2678. result.z = (num3 * left.z) + (num2 * right.z);
  2679. result.w = (num3 * left.w) + (num2 * right.w);
  2680. };
  2681. /**
  2682. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2683. */
  2684. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2685. var squared = amount * amount;
  2686. var cubed = amount * squared;
  2687. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2688. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2689. var part3 = (cubed - (2.0 * squared)) + amount;
  2690. var part4 = cubed - squared;
  2691. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2692. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2693. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2694. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2695. return new Quaternion(x, y, z, w);
  2696. };
  2697. return Quaternion;
  2698. }());
  2699. BABYLON.Quaternion = Quaternion;
  2700. var Matrix = (function () {
  2701. function Matrix() {
  2702. this._isIdentity = false;
  2703. this._isIdentityDirty = true;
  2704. this.m = new Float32Array(16);
  2705. this._markAsUpdated();
  2706. }
  2707. Matrix.prototype._markAsUpdated = function () {
  2708. this.updateFlag = Matrix._updateFlagSeed++;
  2709. this._isIdentityDirty = true;
  2710. };
  2711. // Properties
  2712. /**
  2713. * Boolean : True is the matrix is the identity matrix
  2714. */
  2715. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2716. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2717. if (this._isIdentityDirty) {
  2718. this._isIdentityDirty = false;
  2719. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2720. this._isIdentity = false;
  2721. }
  2722. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2726. this._isIdentity = false;
  2727. }
  2728. else {
  2729. this._isIdentity = true;
  2730. }
  2731. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2732. this._isIdentity = false;
  2733. }
  2734. }
  2735. return this._isIdentity;
  2736. };
  2737. /**
  2738. * Returns the matrix determinant (float).
  2739. */
  2740. Matrix.prototype.determinant = function () {
  2741. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2742. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2743. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2744. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2745. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2746. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2747. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2748. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2749. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2750. };
  2751. // Methods
  2752. /**
  2753. * Returns the matrix underlying array.
  2754. */
  2755. Matrix.prototype.toArray = function () {
  2756. return this.m;
  2757. };
  2758. /**
  2759. * Returns the matrix underlying array.
  2760. */
  2761. Matrix.prototype.asArray = function () {
  2762. return this.toArray();
  2763. };
  2764. /**
  2765. * Inverts in place the Matrix.
  2766. * Returns the Matrix inverted.
  2767. */
  2768. Matrix.prototype.invert = function () {
  2769. this.invertToRef(this);
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets all the matrix elements to zero.
  2774. * Returns the Matrix.
  2775. */
  2776. Matrix.prototype.reset = function () {
  2777. for (var index = 0; index < 16; index++) {
  2778. this.m[index] = 0.0;
  2779. }
  2780. this._markAsUpdated();
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2785. */
  2786. Matrix.prototype.add = function (other) {
  2787. var result = new Matrix();
  2788. this.addToRef(other, result);
  2789. return result;
  2790. };
  2791. /**
  2792. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2793. * Returns the Matrix.
  2794. */
  2795. Matrix.prototype.addToRef = function (other, result) {
  2796. for (var index = 0; index < 16; index++) {
  2797. result.m[index] = this.m[index] + other.m[index];
  2798. }
  2799. result._markAsUpdated();
  2800. return this;
  2801. };
  2802. /**
  2803. * Adds in place the passed matrix to the current Matrix.
  2804. * Returns the updated Matrix.
  2805. */
  2806. Matrix.prototype.addToSelf = function (other) {
  2807. for (var index = 0; index < 16; index++) {
  2808. this.m[index] += other.m[index];
  2809. }
  2810. this._markAsUpdated();
  2811. return this;
  2812. };
  2813. /**
  2814. * Sets the passed matrix with the current inverted Matrix.
  2815. * Returns the unmodified current Matrix.
  2816. */
  2817. Matrix.prototype.invertToRef = function (other) {
  2818. var l1 = this.m[0];
  2819. var l2 = this.m[1];
  2820. var l3 = this.m[2];
  2821. var l4 = this.m[3];
  2822. var l5 = this.m[4];
  2823. var l6 = this.m[5];
  2824. var l7 = this.m[6];
  2825. var l8 = this.m[7];
  2826. var l9 = this.m[8];
  2827. var l10 = this.m[9];
  2828. var l11 = this.m[10];
  2829. var l12 = this.m[11];
  2830. var l13 = this.m[12];
  2831. var l14 = this.m[13];
  2832. var l15 = this.m[14];
  2833. var l16 = this.m[15];
  2834. var l17 = (l11 * l16) - (l12 * l15);
  2835. var l18 = (l10 * l16) - (l12 * l14);
  2836. var l19 = (l10 * l15) - (l11 * l14);
  2837. var l20 = (l9 * l16) - (l12 * l13);
  2838. var l21 = (l9 * l15) - (l11 * l13);
  2839. var l22 = (l9 * l14) - (l10 * l13);
  2840. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2841. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2842. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2843. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2844. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2845. var l28 = (l7 * l16) - (l8 * l15);
  2846. var l29 = (l6 * l16) - (l8 * l14);
  2847. var l30 = (l6 * l15) - (l7 * l14);
  2848. var l31 = (l5 * l16) - (l8 * l13);
  2849. var l32 = (l5 * l15) - (l7 * l13);
  2850. var l33 = (l5 * l14) - (l6 * l13);
  2851. var l34 = (l7 * l12) - (l8 * l11);
  2852. var l35 = (l6 * l12) - (l8 * l10);
  2853. var l36 = (l6 * l11) - (l7 * l10);
  2854. var l37 = (l5 * l12) - (l8 * l9);
  2855. var l38 = (l5 * l11) - (l7 * l9);
  2856. var l39 = (l5 * l10) - (l6 * l9);
  2857. other.m[0] = l23 * l27;
  2858. other.m[4] = l24 * l27;
  2859. other.m[8] = l25 * l27;
  2860. other.m[12] = l26 * l27;
  2861. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2862. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2863. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2864. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2865. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2866. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2867. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2868. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2869. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2870. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2871. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2872. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2873. other._markAsUpdated();
  2874. return this;
  2875. };
  2876. /**
  2877. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2878. * Returns the updated Matrix.
  2879. */
  2880. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2881. this.m[12] = x;
  2882. this.m[13] = y;
  2883. this.m[14] = z;
  2884. this._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Inserts the translation vector in the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.setTranslation = function (vector3) {
  2892. this.m[12] = vector3.x;
  2893. this.m[13] = vector3.y;
  2894. this.m[14] = vector3.z;
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3 as the extracted translation from the Matrix.
  2900. */
  2901. Matrix.prototype.getTranslation = function () {
  2902. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2903. };
  2904. /**
  2905. * Fill a Vector3 with the extracted translation from the Matrix.
  2906. */
  2907. Matrix.prototype.getTranslationToRef = function (result) {
  2908. result.x = this.m[12];
  2909. result.y = this.m[13];
  2910. result.z = this.m[14];
  2911. return this;
  2912. };
  2913. /**
  2914. * Remove rotation and scaling part from the Matrix.
  2915. * Returns the updated Matrix.
  2916. */
  2917. Matrix.prototype.removeRotationAndScaling = function () {
  2918. this.setRowFromFloats(0, 1, 0, 0, 0);
  2919. this.setRowFromFloats(1, 0, 1, 0, 0);
  2920. this.setRowFromFloats(2, 0, 0, 1, 0);
  2921. return this;
  2922. };
  2923. /**
  2924. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2925. */
  2926. Matrix.prototype.multiply = function (other) {
  2927. var result = new Matrix();
  2928. this.multiplyToRef(other, result);
  2929. return result;
  2930. };
  2931. /**
  2932. * Updates the current Matrix from the passed one values.
  2933. * Returns the updated Matrix.
  2934. */
  2935. Matrix.prototype.copyFrom = function (other) {
  2936. for (var index = 0; index < 16; index++) {
  2937. this.m[index] = other.m[index];
  2938. }
  2939. this._markAsUpdated();
  2940. return this;
  2941. };
  2942. /**
  2943. * Populates the passed array from the starting index with the Matrix values.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.copyToArray = function (array, offset) {
  2947. if (offset === void 0) { offset = 0; }
  2948. for (var index = 0; index < 16; index++) {
  2949. array[offset + index] = this.m[index];
  2950. }
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToRef = function (other, result) {
  2957. this.multiplyToArray(other, result.m, 0);
  2958. result._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2963. */
  2964. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2965. var tm0 = this.m[0];
  2966. var tm1 = this.m[1];
  2967. var tm2 = this.m[2];
  2968. var tm3 = this.m[3];
  2969. var tm4 = this.m[4];
  2970. var tm5 = this.m[5];
  2971. var tm6 = this.m[6];
  2972. var tm7 = this.m[7];
  2973. var tm8 = this.m[8];
  2974. var tm9 = this.m[9];
  2975. var tm10 = this.m[10];
  2976. var tm11 = this.m[11];
  2977. var tm12 = this.m[12];
  2978. var tm13 = this.m[13];
  2979. var tm14 = this.m[14];
  2980. var tm15 = this.m[15];
  2981. var om0 = other.m[0];
  2982. var om1 = other.m[1];
  2983. var om2 = other.m[2];
  2984. var om3 = other.m[3];
  2985. var om4 = other.m[4];
  2986. var om5 = other.m[5];
  2987. var om6 = other.m[6];
  2988. var om7 = other.m[7];
  2989. var om8 = other.m[8];
  2990. var om9 = other.m[9];
  2991. var om10 = other.m[10];
  2992. var om11 = other.m[11];
  2993. var om12 = other.m[12];
  2994. var om13 = other.m[13];
  2995. var om14 = other.m[14];
  2996. var om15 = other.m[15];
  2997. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2998. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2999. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3000. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3001. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3002. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3003. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3004. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3005. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3006. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3007. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3008. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3009. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3010. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3011. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3012. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3013. return this;
  3014. };
  3015. /**
  3016. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3017. */
  3018. Matrix.prototype.equals = function (value) {
  3019. return value &&
  3020. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3021. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3022. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3023. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3024. };
  3025. /**
  3026. * Returns a new Matrix from the current Matrix.
  3027. */
  3028. Matrix.prototype.clone = function () {
  3029. 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]);
  3030. };
  3031. /**
  3032. * Returns the string "Matrix"
  3033. */
  3034. Matrix.prototype.getClassName = function () {
  3035. return "Matrix";
  3036. };
  3037. /**
  3038. * Returns the Matrix hash code.
  3039. */
  3040. Matrix.prototype.getHashCode = function () {
  3041. var hash = this.m[0] || 0;
  3042. for (var i = 1; i < 16; i++) {
  3043. hash = (hash * 397) ^ (this.m[i] || 0);
  3044. }
  3045. return hash;
  3046. };
  3047. /**
  3048. * Decomposes the current Matrix into :
  3049. * - a scale vector3 passed as a reference to update,
  3050. * - a rotation quaternion passed as a reference to update,
  3051. * - a translation vector3 passed as a reference to update.
  3052. * Returns the boolean `true`.
  3053. */
  3054. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3055. translation.x = this.m[12];
  3056. translation.y = this.m[13];
  3057. translation.z = this.m[14];
  3058. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3059. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3060. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3061. if (this.determinant() <= 0) {
  3062. scale.y *= -1;
  3063. }
  3064. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3065. rotation.x = 0;
  3066. rotation.y = 0;
  3067. rotation.z = 0;
  3068. rotation.w = 1;
  3069. return false;
  3070. }
  3071. Matrix.FromValuesToRef(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, MathTmp.Matrix[0]);
  3072. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3073. return true;
  3074. };
  3075. /**
  3076. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3077. */
  3078. Matrix.prototype.getRotationMatrix = function () {
  3079. var result = Matrix.Identity();
  3080. this.getRotationMatrixToRef(result);
  3081. return result;
  3082. };
  3083. /**
  3084. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3085. * Returns the current Matrix.
  3086. */
  3087. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3088. var m = this.m;
  3089. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3090. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3091. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3092. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3093. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3094. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3095. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3096. return this;
  3097. };
  3098. // Statics
  3099. /**
  3100. * Returns a new Matrix set from the starting index of the passed array.
  3101. */
  3102. Matrix.FromArray = function (array, offset) {
  3103. var result = new Matrix();
  3104. if (!offset) {
  3105. offset = 0;
  3106. }
  3107. Matrix.FromArrayToRef(array, offset, result);
  3108. return result;
  3109. };
  3110. /**
  3111. * Sets the passed "result" matrix from the starting index of the passed array.
  3112. */
  3113. Matrix.FromArrayToRef = function (array, offset, result) {
  3114. for (var index = 0; index < 16; index++) {
  3115. result.m[index] = array[index + offset];
  3116. }
  3117. result._markAsUpdated();
  3118. };
  3119. /**
  3120. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3121. */
  3122. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3123. for (var index = 0; index < 16; index++) {
  3124. result.m[index] = array[index + offset] * scale;
  3125. }
  3126. result._markAsUpdated();
  3127. };
  3128. /**
  3129. * Sets the passed matrix "result" with the 16 passed floats.
  3130. */
  3131. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3132. result.m[0] = initialM11;
  3133. result.m[1] = initialM12;
  3134. result.m[2] = initialM13;
  3135. result.m[3] = initialM14;
  3136. result.m[4] = initialM21;
  3137. result.m[5] = initialM22;
  3138. result.m[6] = initialM23;
  3139. result.m[7] = initialM24;
  3140. result.m[8] = initialM31;
  3141. result.m[9] = initialM32;
  3142. result.m[10] = initialM33;
  3143. result.m[11] = initialM34;
  3144. result.m[12] = initialM41;
  3145. result.m[13] = initialM42;
  3146. result.m[14] = initialM43;
  3147. result.m[15] = initialM44;
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Returns the index-th row of the current matrix as a new Vector4.
  3152. */
  3153. Matrix.prototype.getRow = function (index) {
  3154. if (index < 0 || index > 3) {
  3155. return null;
  3156. }
  3157. var i = index * 4;
  3158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3159. };
  3160. /**
  3161. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.setRow = function (index, row) {
  3165. if (index < 0 || index > 3) {
  3166. return this;
  3167. }
  3168. var i = index * 4;
  3169. this.m[i + 0] = row.x;
  3170. this.m[i + 1] = row.y;
  3171. this.m[i + 2] = row.z;
  3172. this.m[i + 3] = row.w;
  3173. this._markAsUpdated();
  3174. return this;
  3175. };
  3176. /**
  3177. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3178. * Returns the updated Matrix.
  3179. */
  3180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3181. if (index < 0 || index > 3) {
  3182. return this;
  3183. }
  3184. var i = index * 4;
  3185. this.m[i + 0] = x;
  3186. this.m[i + 1] = y;
  3187. this.m[i + 2] = z;
  3188. this.m[i + 3] = w;
  3189. this._markAsUpdated();
  3190. return this;
  3191. };
  3192. /**
  3193. * Returns a new Matrix set from the 16 passed floats.
  3194. */
  3195. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3196. var result = new Matrix();
  3197. result.m[0] = initialM11;
  3198. result.m[1] = initialM12;
  3199. result.m[2] = initialM13;
  3200. result.m[3] = initialM14;
  3201. result.m[4] = initialM21;
  3202. result.m[5] = initialM22;
  3203. result.m[6] = initialM23;
  3204. result.m[7] = initialM24;
  3205. result.m[8] = initialM31;
  3206. result.m[9] = initialM32;
  3207. result.m[10] = initialM33;
  3208. result.m[11] = initialM34;
  3209. result.m[12] = initialM41;
  3210. result.m[13] = initialM42;
  3211. result.m[14] = initialM43;
  3212. result.m[15] = initialM44;
  3213. return result;
  3214. };
  3215. /**
  3216. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.Compose = function (scale, rotation, translation) {
  3219. var result = Matrix.Identity();
  3220. Matrix.ComposeToRef(scale, rotation, translation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3225. */
  3226. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3227. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3228. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3229. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3230. result.setTranslation(translation);
  3231. };
  3232. /**
  3233. * Returns a new indentity Matrix.
  3234. */
  3235. Matrix.Identity = function () {
  3236. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3237. };
  3238. /**
  3239. * Sets the passed "result" as an identity matrix.
  3240. */
  3241. Matrix.IdentityToRef = function (result) {
  3242. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3243. };
  3244. /**
  3245. * Returns a new zero Matrix.
  3246. */
  3247. Matrix.Zero = function () {
  3248. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3249. };
  3250. /**
  3251. * Returns a new rotation matrix for "angle" radians around the X axis.
  3252. */
  3253. Matrix.RotationX = function (angle) {
  3254. var result = new Matrix();
  3255. Matrix.RotationXToRef(angle, result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Returns a new Matrix as the passed inverted one.
  3260. */
  3261. Matrix.Invert = function (source) {
  3262. var result = new Matrix();
  3263. source.invertToRef(result);
  3264. return result;
  3265. };
  3266. /**
  3267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3268. */
  3269. Matrix.RotationXToRef = function (angle, result) {
  3270. var s = Math.sin(angle);
  3271. var c = Math.cos(angle);
  3272. result.m[0] = 1.0;
  3273. result.m[15] = 1.0;
  3274. result.m[5] = c;
  3275. result.m[10] = c;
  3276. result.m[9] = -s;
  3277. result.m[6] = s;
  3278. result.m[1] = 0.0;
  3279. result.m[2] = 0.0;
  3280. result.m[3] = 0.0;
  3281. result.m[4] = 0.0;
  3282. result.m[7] = 0.0;
  3283. result.m[8] = 0.0;
  3284. result.m[11] = 0.0;
  3285. result.m[12] = 0.0;
  3286. result.m[13] = 0.0;
  3287. result.m[14] = 0.0;
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationY = function (angle) {
  3294. var result = new Matrix();
  3295. Matrix.RotationYToRef(angle, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3300. */
  3301. Matrix.RotationYToRef = function (angle, result) {
  3302. var s = Math.sin(angle);
  3303. var c = Math.cos(angle);
  3304. result.m[5] = 1.0;
  3305. result.m[15] = 1.0;
  3306. result.m[0] = c;
  3307. result.m[2] = -s;
  3308. result.m[8] = s;
  3309. result.m[10] = c;
  3310. result.m[1] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[6] = 0.0;
  3314. result.m[7] = 0.0;
  3315. result.m[9] = 0.0;
  3316. result.m[11] = 0.0;
  3317. result.m[12] = 0.0;
  3318. result.m[13] = 0.0;
  3319. result.m[14] = 0.0;
  3320. result._markAsUpdated();
  3321. };
  3322. /**
  3323. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZ = function (angle) {
  3326. var result = new Matrix();
  3327. Matrix.RotationZToRef(angle, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3332. */
  3333. Matrix.RotationZToRef = function (angle, result) {
  3334. var s = Math.sin(angle);
  3335. var c = Math.cos(angle);
  3336. result.m[10] = 1.0;
  3337. result.m[15] = 1.0;
  3338. result.m[0] = c;
  3339. result.m[1] = s;
  3340. result.m[4] = -s;
  3341. result.m[5] = c;
  3342. result.m[2] = 0.0;
  3343. result.m[3] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[8] = 0.0;
  3347. result.m[9] = 0.0;
  3348. result.m[11] = 0.0;
  3349. result.m[12] = 0.0;
  3350. result.m[13] = 0.0;
  3351. result.m[14] = 0.0;
  3352. result._markAsUpdated();
  3353. };
  3354. /**
  3355. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxis = function (axis, angle) {
  3358. var result = Matrix.Zero();
  3359. Matrix.RotationAxisToRef(axis, angle, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3364. */
  3365. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3366. var s = Math.sin(-angle);
  3367. var c = Math.cos(-angle);
  3368. var c1 = 1 - c;
  3369. axis.normalize();
  3370. result.m[0] = (axis.x * axis.x) * c1 + c;
  3371. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3372. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3373. result.m[3] = 0.0;
  3374. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3375. result.m[5] = (axis.y * axis.y) * c1 + c;
  3376. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3377. result.m[7] = 0.0;
  3378. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3379. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3380. result.m[10] = (axis.z * axis.z) * c1 + c;
  3381. result.m[11] = 0.0;
  3382. result.m[15] = 1.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3389. var result = new Matrix();
  3390. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3395. */
  3396. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3397. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3398. this._tempQuaternion.toRotationMatrix(result);
  3399. };
  3400. /**
  3401. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.Scaling = function (x, y, z) {
  3404. var result = Matrix.Zero();
  3405. Matrix.ScalingToRef(x, y, z, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3410. */
  3411. Matrix.ScalingToRef = function (x, y, z, result) {
  3412. result.m[0] = x;
  3413. result.m[1] = 0.0;
  3414. result.m[2] = 0.0;
  3415. result.m[3] = 0.0;
  3416. result.m[4] = 0.0;
  3417. result.m[5] = y;
  3418. result.m[6] = 0.0;
  3419. result.m[7] = 0.0;
  3420. result.m[8] = 0.0;
  3421. result.m[9] = 0.0;
  3422. result.m[10] = z;
  3423. result.m[11] = 0.0;
  3424. result.m[12] = 0.0;
  3425. result.m[13] = 0.0;
  3426. result.m[14] = 0.0;
  3427. result.m[15] = 1.0;
  3428. result._markAsUpdated();
  3429. };
  3430. /**
  3431. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.Translation = function (x, y, z) {
  3434. var result = Matrix.Identity();
  3435. Matrix.TranslationToRef(x, y, z, result);
  3436. return result;
  3437. };
  3438. /**
  3439. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3440. */
  3441. Matrix.TranslationToRef = function (x, y, z, result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3446. */
  3447. Matrix.Lerp = function (startValue, endValue, gradient) {
  3448. var result = Matrix.Zero();
  3449. for (var index = 0; index < 16; index++) {
  3450. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3451. }
  3452. result._markAsUpdated();
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix whose values are computed by :
  3457. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3458. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3459. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3460. */
  3461. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3462. var startScale = new Vector3(0, 0, 0);
  3463. var startRotation = new Quaternion();
  3464. var startTranslation = new Vector3(0, 0, 0);
  3465. startValue.decompose(startScale, startRotation, startTranslation);
  3466. var endScale = new Vector3(0, 0, 0);
  3467. var endRotation = new Quaternion();
  3468. var endTranslation = new Vector3(0, 0, 0);
  3469. endValue.decompose(endScale, endRotation, endTranslation);
  3470. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3471. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3472. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3473. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3474. };
  3475. /**
  3476. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3477. * This methods works for a Left-Handed system.
  3478. */
  3479. Matrix.LookAtLH = function (eye, target, up) {
  3480. var result = Matrix.Zero();
  3481. Matrix.LookAtLHToRef(eye, target, up, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3486. * This methods works for a Left-Handed system.
  3487. */
  3488. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3489. // Z axis
  3490. target.subtractToRef(eye, this._zAxis);
  3491. this._zAxis.normalize();
  3492. // X axis
  3493. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3494. if (this._xAxis.lengthSquared() === 0) {
  3495. this._xAxis.x = 1.0;
  3496. }
  3497. else {
  3498. this._xAxis.normalize();
  3499. }
  3500. // Y axis
  3501. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3502. this._yAxis.normalize();
  3503. // Eye angles
  3504. var ex = -Vector3.Dot(this._xAxis, eye);
  3505. var ey = -Vector3.Dot(this._yAxis, eye);
  3506. var ez = -Vector3.Dot(this._zAxis, eye);
  3507. 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);
  3508. };
  3509. /**
  3510. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3511. * This methods works for a Right-Handed system.
  3512. */
  3513. Matrix.LookAtRH = function (eye, target, up) {
  3514. var result = Matrix.Zero();
  3515. Matrix.LookAtRHToRef(eye, target, up, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3520. * This methods works for a Left-Handed system.
  3521. */
  3522. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3523. // Z axis
  3524. eye.subtractToRef(target, this._zAxis);
  3525. this._zAxis.normalize();
  3526. // X axis
  3527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3528. if (this._xAxis.lengthSquared() === 0) {
  3529. this._xAxis.x = 1.0;
  3530. }
  3531. else {
  3532. this._xAxis.normalize();
  3533. }
  3534. // Y axis
  3535. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3536. this._yAxis.normalize();
  3537. // Eye angles
  3538. var ex = -Vector3.Dot(this._xAxis, eye);
  3539. var ey = -Vector3.Dot(this._yAxis, eye);
  3540. var ez = -Vector3.Dot(this._zAxis, eye);
  3541. 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);
  3542. };
  3543. /**
  3544. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3545. */
  3546. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3547. var matrix = Matrix.Zero();
  3548. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3549. return matrix;
  3550. };
  3551. /**
  3552. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3553. */
  3554. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3555. var n = znear;
  3556. var f = zfar;
  3557. var a = 2.0 / width;
  3558. var b = 2.0 / height;
  3559. var c = 2.0 / (f - n);
  3560. var d = -(f + n) / (f - n);
  3561. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3562. };
  3563. /**
  3564. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3565. */
  3566. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3567. var matrix = Matrix.Zero();
  3568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3569. return matrix;
  3570. };
  3571. /**
  3572. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3573. */
  3574. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3575. var n = znear;
  3576. var f = zfar;
  3577. var a = 2.0 / (right - left);
  3578. var b = 2.0 / (top - bottom);
  3579. var c = 2.0 / (f - n);
  3580. var d = -(f + n) / (f - n);
  3581. var i0 = (left + right) / (left - right);
  3582. var i1 = (top + bottom) / (bottom - top);
  3583. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3587. */
  3588. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3589. var matrix = Matrix.Zero();
  3590. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3591. return matrix;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3595. */
  3596. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3597. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3598. result.m[10] *= -1.0;
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3602. */
  3603. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3604. var matrix = Matrix.Zero();
  3605. var n = znear;
  3606. var f = zfar;
  3607. var a = 2.0 * n / width;
  3608. var b = 2.0 * n / height;
  3609. var c = (f + n) / (f - n);
  3610. var d = -2.0 * f * n / (f - n);
  3611. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3616. */
  3617. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3618. var matrix = Matrix.Zero();
  3619. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3620. return matrix;
  3621. };
  3622. /**
  3623. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3624. */
  3625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3627. var n = znear;
  3628. var f = zfar;
  3629. var t = 1.0 / (Math.tan(fov * 0.5));
  3630. var a = isVerticalFovFixed ? (t / aspect) : t;
  3631. var b = isVerticalFovFixed ? t : (t * aspect);
  3632. var c = (f + n) / (f - n);
  3633. var d = -2.0 * f * n / (f - n);
  3634. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3635. };
  3636. /**
  3637. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3638. */
  3639. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3640. var matrix = Matrix.Zero();
  3641. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3642. return matrix;
  3643. };
  3644. /**
  3645. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3646. */
  3647. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3648. //alternatively this could be expressed as:
  3649. // m = PerspectiveFovLHToRef
  3650. // m[10] *= -1.0;
  3651. // m[11] *= -1.0;
  3652. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3653. var n = znear;
  3654. var f = zfar;
  3655. var t = 1.0 / (Math.tan(fov * 0.5));
  3656. var a = isVerticalFovFixed ? (t / aspect) : t;
  3657. var b = isVerticalFovFixed ? t : (t * aspect);
  3658. var c = -(f + n) / (f - n);
  3659. var d = -2 * f * n / (f - n);
  3660. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3661. };
  3662. /**
  3663. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3664. */
  3665. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3666. if (rightHanded === void 0) { rightHanded = false; }
  3667. var rightHandedFactor = rightHanded ? -1 : 1;
  3668. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3669. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3670. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3671. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3672. var xScale = 2.0 / (leftTan + rightTan);
  3673. var yScale = 2.0 / (upTan + downTan);
  3674. result.m[0] = xScale;
  3675. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3676. result.m[5] = yScale;
  3677. result.m[6] = result.m[7] = 0.0;
  3678. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3679. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3680. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3681. result.m[10] = -zfar / (znear - zfar);
  3682. result.m[11] = 1.0 * rightHandedFactor;
  3683. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3684. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3685. // result.m[14] = (znear * zfar) / (znear - zfar);
  3686. result._markAsUpdated();
  3687. };
  3688. /**
  3689. * Returns the final transformation matrix : world * view * projection * viewport
  3690. */
  3691. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3692. var cw = viewport.width;
  3693. var ch = viewport.height;
  3694. var cx = viewport.x;
  3695. var cy = viewport.y;
  3696. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3697. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3698. };
  3699. /**
  3700. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3701. */
  3702. Matrix.GetAsMatrix2x2 = function (matrix) {
  3703. return new Float32Array([
  3704. matrix.m[0], matrix.m[1],
  3705. matrix.m[4], matrix.m[5]
  3706. ]);
  3707. };
  3708. /**
  3709. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3710. */
  3711. Matrix.GetAsMatrix3x3 = function (matrix) {
  3712. return new Float32Array([
  3713. matrix.m[0], matrix.m[1], matrix.m[2],
  3714. matrix.m[4], matrix.m[5], matrix.m[6],
  3715. matrix.m[8], matrix.m[9], matrix.m[10]
  3716. ]);
  3717. };
  3718. /**
  3719. * Compute the transpose of the passed Matrix.
  3720. * Returns a new Matrix.
  3721. */
  3722. Matrix.Transpose = function (matrix) {
  3723. var result = new Matrix();
  3724. result.m[0] = matrix.m[0];
  3725. result.m[1] = matrix.m[4];
  3726. result.m[2] = matrix.m[8];
  3727. result.m[3] = matrix.m[12];
  3728. result.m[4] = matrix.m[1];
  3729. result.m[5] = matrix.m[5];
  3730. result.m[6] = matrix.m[9];
  3731. result.m[7] = matrix.m[13];
  3732. result.m[8] = matrix.m[2];
  3733. result.m[9] = matrix.m[6];
  3734. result.m[10] = matrix.m[10];
  3735. result.m[11] = matrix.m[14];
  3736. result.m[12] = matrix.m[3];
  3737. result.m[13] = matrix.m[7];
  3738. result.m[14] = matrix.m[11];
  3739. result.m[15] = matrix.m[15];
  3740. return result;
  3741. };
  3742. /**
  3743. * Returns a new Matrix as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.Reflection = function (plane) {
  3746. var matrix = new Matrix();
  3747. Matrix.ReflectionToRef(plane, matrix);
  3748. return matrix;
  3749. };
  3750. /**
  3751. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3752. */
  3753. Matrix.ReflectionToRef = function (plane, result) {
  3754. plane.normalize();
  3755. var x = plane.normal.x;
  3756. var y = plane.normal.y;
  3757. var z = plane.normal.z;
  3758. var temp = -2 * x;
  3759. var temp2 = -2 * y;
  3760. var temp3 = -2 * z;
  3761. result.m[0] = (temp * x) + 1;
  3762. result.m[1] = temp2 * x;
  3763. result.m[2] = temp3 * x;
  3764. result.m[3] = 0.0;
  3765. result.m[4] = temp * y;
  3766. result.m[5] = (temp2 * y) + 1;
  3767. result.m[6] = temp3 * y;
  3768. result.m[7] = 0.0;
  3769. result.m[8] = temp * z;
  3770. result.m[9] = temp2 * z;
  3771. result.m[10] = (temp3 * z) + 1;
  3772. result.m[11] = 0.0;
  3773. result.m[12] = temp * plane.d;
  3774. result.m[13] = temp2 * plane.d;
  3775. result.m[14] = temp3 * plane.d;
  3776. result.m[15] = 1.0;
  3777. result._markAsUpdated();
  3778. };
  3779. /**
  3780. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3781. */
  3782. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3783. result.m[0] = xaxis.x;
  3784. result.m[1] = xaxis.y;
  3785. result.m[2] = xaxis.z;
  3786. result.m[3] = 0.0;
  3787. result.m[4] = yaxis.x;
  3788. result.m[5] = yaxis.y;
  3789. result.m[6] = yaxis.z;
  3790. result.m[7] = 0.0;
  3791. result.m[8] = zaxis.x;
  3792. result.m[9] = zaxis.y;
  3793. result.m[10] = zaxis.z;
  3794. result.m[11] = 0.0;
  3795. result.m[12] = 0.0;
  3796. result.m[13] = 0.0;
  3797. result.m[14] = 0.0;
  3798. result.m[15] = 1.0;
  3799. result._markAsUpdated();
  3800. };
  3801. /**
  3802. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3803. */
  3804. Matrix.FromQuaternionToRef = function (quat, result) {
  3805. var xx = quat.x * quat.x;
  3806. var yy = quat.y * quat.y;
  3807. var zz = quat.z * quat.z;
  3808. var xy = quat.x * quat.y;
  3809. var zw = quat.z * quat.w;
  3810. var zx = quat.z * quat.x;
  3811. var yw = quat.y * quat.w;
  3812. var yz = quat.y * quat.z;
  3813. var xw = quat.x * quat.w;
  3814. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3815. result.m[1] = 2.0 * (xy + zw);
  3816. result.m[2] = 2.0 * (zx - yw);
  3817. result.m[3] = 0.0;
  3818. result.m[4] = 2.0 * (xy - zw);
  3819. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3820. result.m[6] = 2.0 * (yz + xw);
  3821. result.m[7] = 0.0;
  3822. result.m[8] = 2.0 * (zx + yw);
  3823. result.m[9] = 2.0 * (yz - xw);
  3824. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. Matrix._tempQuaternion = new Quaternion();
  3833. Matrix._xAxis = Vector3.Zero();
  3834. Matrix._yAxis = Vector3.Zero();
  3835. Matrix._zAxis = Vector3.Zero();
  3836. Matrix._updateFlagSeed = 0;
  3837. return Matrix;
  3838. }());
  3839. BABYLON.Matrix = Matrix;
  3840. var Plane = (function () {
  3841. /**
  3842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3843. */
  3844. function Plane(a, b, c, d) {
  3845. this.normal = new Vector3(a, b, c);
  3846. this.d = d;
  3847. }
  3848. /**
  3849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3850. */
  3851. Plane.prototype.asArray = function () {
  3852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3853. };
  3854. // Methods
  3855. /**
  3856. * Returns a new plane copied from the current Plane.
  3857. */
  3858. Plane.prototype.clone = function () {
  3859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3860. };
  3861. /**
  3862. * Returns the string "Plane".
  3863. */
  3864. Plane.prototype.getClassName = function () {
  3865. return "Plane";
  3866. };
  3867. /**
  3868. * Returns the Plane hash code.
  3869. */
  3870. Plane.prototype.getHashCode = function () {
  3871. var hash = this.normal.getHashCode();
  3872. hash = (hash * 397) ^ (this.d || 0);
  3873. return hash;
  3874. };
  3875. /**
  3876. * Normalize the current Plane in place.
  3877. * Returns the updated Plane.
  3878. */
  3879. Plane.prototype.normalize = function () {
  3880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3881. var magnitude = 0.0;
  3882. if (norm !== 0) {
  3883. magnitude = 1.0 / norm;
  3884. }
  3885. this.normal.x *= magnitude;
  3886. this.normal.y *= magnitude;
  3887. this.normal.z *= magnitude;
  3888. this.d *= magnitude;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3893. */
  3894. Plane.prototype.transform = function (transformation) {
  3895. var transposedMatrix = Matrix.Transpose(transformation);
  3896. var x = this.normal.x;
  3897. var y = this.normal.y;
  3898. var z = this.normal.z;
  3899. var d = this.d;
  3900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3904. return new Plane(normalX, normalY, normalZ, finalD);
  3905. };
  3906. /**
  3907. * Returns the dot product (float) of the point coordinates and the plane normal.
  3908. */
  3909. Plane.prototype.dotCoordinate = function (point) {
  3910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3911. };
  3912. /**
  3913. * Updates the current Plane from the plane defined by the three passed points.
  3914. * Returns the updated Plane.
  3915. */
  3916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3917. var x1 = point2.x - point1.x;
  3918. var y1 = point2.y - point1.y;
  3919. var z1 = point2.z - point1.z;
  3920. var x2 = point3.x - point1.x;
  3921. var y2 = point3.y - point1.y;
  3922. var z2 = point3.z - point1.z;
  3923. var yz = (y1 * z2) - (z1 * y2);
  3924. var xz = (z1 * x2) - (x1 * z2);
  3925. var xy = (x1 * y2) - (y1 * x2);
  3926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3927. var invPyth;
  3928. if (pyth !== 0) {
  3929. invPyth = 1.0 / pyth;
  3930. }
  3931. else {
  3932. invPyth = 0.0;
  3933. }
  3934. this.normal.x = yz * invPyth;
  3935. this.normal.y = xz * invPyth;
  3936. this.normal.z = xy * invPyth;
  3937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3942. */
  3943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3944. var dot = Vector3.Dot(this.normal, direction);
  3945. return (dot <= epsilon);
  3946. };
  3947. /**
  3948. * Returns the signed distance (float) from the passed point to the Plane.
  3949. */
  3950. Plane.prototype.signedDistanceTo = function (point) {
  3951. return Vector3.Dot(point, this.normal) + this.d;
  3952. };
  3953. // Statics
  3954. /**
  3955. * Returns a new Plane from the passed array.
  3956. */
  3957. Plane.FromArray = function (array) {
  3958. return new Plane(array[0], array[1], array[2], array[3]);
  3959. };
  3960. /**
  3961. * Returns a new Plane defined by the three passed points.
  3962. */
  3963. Plane.FromPoints = function (point1, point2, point3) {
  3964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3965. result.copyFromPoints(point1, point2, point3);
  3966. return result;
  3967. };
  3968. /**
  3969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3970. * Note : the vector "normal" is updated because normalized.
  3971. */
  3972. Plane.FromPositionAndNormal = function (origin, normal) {
  3973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3974. normal.normalize();
  3975. result.normal = normal;
  3976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3977. return result;
  3978. };
  3979. /**
  3980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3981. */
  3982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3984. return Vector3.Dot(point, normal) + d;
  3985. };
  3986. return Plane;
  3987. }());
  3988. BABYLON.Plane = Plane;
  3989. var Viewport = (function () {
  3990. /**
  3991. * Creates a Viewport object located at (x, y) and sized (width, height).
  3992. */
  3993. function Viewport(x, y, width, height) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.width = width;
  3997. this.height = height;
  3998. }
  3999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4000. if (renderWidthOrEngine.getRenderWidth) {
  4001. var engine = renderWidthOrEngine;
  4002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4003. }
  4004. var renderWidth = renderWidthOrEngine;
  4005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4006. };
  4007. /**
  4008. * Returns a new Viewport copied from the current one.
  4009. */
  4010. Viewport.prototype.clone = function () {
  4011. return new Viewport(this.x, this.y, this.width, this.height);
  4012. };
  4013. return Viewport;
  4014. }());
  4015. BABYLON.Viewport = Viewport;
  4016. var Frustum = (function () {
  4017. function Frustum() {
  4018. }
  4019. /**
  4020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4021. */
  4022. Frustum.GetPlanes = function (transform) {
  4023. var frustumPlanes = [];
  4024. for (var index = 0; index < 6; index++) {
  4025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4026. }
  4027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4028. return frustumPlanes;
  4029. };
  4030. /**
  4031. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4032. */
  4033. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4034. // Near
  4035. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4036. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4037. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4038. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4039. frustumPlanes[0].normalize();
  4040. // Far
  4041. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4042. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4043. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4044. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4045. frustumPlanes[1].normalize();
  4046. // Left
  4047. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4048. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4049. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4050. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4051. frustumPlanes[2].normalize();
  4052. // Right
  4053. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4054. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4055. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4056. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4057. frustumPlanes[3].normalize();
  4058. // Top
  4059. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4060. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4061. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4062. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4063. frustumPlanes[4].normalize();
  4064. // Bottom
  4065. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4066. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4067. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4068. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4069. frustumPlanes[5].normalize();
  4070. };
  4071. return Frustum;
  4072. }());
  4073. BABYLON.Frustum = Frustum;
  4074. var Space;
  4075. (function (Space) {
  4076. Space[Space["LOCAL"] = 0] = "LOCAL";
  4077. Space[Space["WORLD"] = 1] = "WORLD";
  4078. Space[Space["BONE"] = 2] = "BONE";
  4079. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4080. var Axis = (function () {
  4081. function Axis() {
  4082. }
  4083. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4084. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4085. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4086. return Axis;
  4087. }());
  4088. BABYLON.Axis = Axis;
  4089. ;
  4090. var BezierCurve = (function () {
  4091. function BezierCurve() {
  4092. }
  4093. /**
  4094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4095. */
  4096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4097. // Extract X (which is equal to time here)
  4098. var f0 = 1 - 3 * x2 + 3 * x1;
  4099. var f1 = 3 * x2 - 6 * x1;
  4100. var f2 = 3 * x1;
  4101. var refinedT = t;
  4102. for (var i = 0; i < 5; i++) {
  4103. var refinedT2 = refinedT * refinedT;
  4104. var refinedT3 = refinedT2 * refinedT;
  4105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4107. refinedT -= (x - t) * slope;
  4108. refinedT = Math.min(1, Math.max(0, refinedT));
  4109. }
  4110. // Resolve cubic bezier for the given x
  4111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4113. Math.pow(refinedT, 3);
  4114. };
  4115. return BezierCurve;
  4116. }());
  4117. BABYLON.BezierCurve = BezierCurve;
  4118. var Orientation;
  4119. (function (Orientation) {
  4120. Orientation[Orientation["CW"] = 0] = "CW";
  4121. Orientation[Orientation["CCW"] = 1] = "CCW";
  4122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4123. var Angle = (function () {
  4124. /**
  4125. * Creates an Angle object of "radians" radians (float).
  4126. */
  4127. function Angle(radians) {
  4128. var _this = this;
  4129. /**
  4130. * Returns the Angle value in degrees (float).
  4131. */
  4132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4133. /**
  4134. * Returns the Angle value in radians (float).
  4135. */
  4136. this.radians = function () { return _this._radians; };
  4137. this._radians = radians;
  4138. if (this._radians < 0.0)
  4139. this._radians += (2.0 * Math.PI);
  4140. }
  4141. /**
  4142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4143. */
  4144. Angle.BetweenTwoPoints = function (a, b) {
  4145. var delta = b.subtract(a);
  4146. var theta = Math.atan2(delta.y, delta.x);
  4147. return new Angle(theta);
  4148. };
  4149. /**
  4150. * Returns a new Angle object from the passed float in radians.
  4151. */
  4152. Angle.FromRadians = function (radians) {
  4153. return new Angle(radians);
  4154. };
  4155. /**
  4156. * Returns a new Angle object from the passed float in degrees.
  4157. */
  4158. Angle.FromDegrees = function (degrees) {
  4159. return new Angle(degrees * Math.PI / 180.0);
  4160. };
  4161. return Angle;
  4162. }());
  4163. BABYLON.Angle = Angle;
  4164. var Arc2 = (function () {
  4165. /**
  4166. * Creates an Arc object from the three passed points : start, middle and end.
  4167. */
  4168. function Arc2(startPoint, midPoint, endPoint) {
  4169. this.startPoint = startPoint;
  4170. this.midPoint = midPoint;
  4171. this.endPoint = endPoint;
  4172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4176. 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);
  4177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4179. var a1 = this.startAngle.degrees();
  4180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4182. // angles correction
  4183. if (a2 - a1 > +180.0)
  4184. a2 -= 360.0;
  4185. if (a2 - a1 < -180.0)
  4186. a2 += 360.0;
  4187. if (a3 - a2 > +180.0)
  4188. a3 -= 360.0;
  4189. if (a3 - a2 < -180.0)
  4190. a3 += 360.0;
  4191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4193. }
  4194. return Arc2;
  4195. }());
  4196. BABYLON.Arc2 = Arc2;
  4197. var Path2 = (function () {
  4198. /**
  4199. * Creates a Path2 object from the starting 2D coordinates x and y.
  4200. */
  4201. function Path2(x, y) {
  4202. this._points = new Array();
  4203. this._length = 0.0;
  4204. this.closed = false;
  4205. this._points.push(new Vector2(x, y));
  4206. }
  4207. /**
  4208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4209. * Returns the updated Path2.
  4210. */
  4211. Path2.prototype.addLineTo = function (x, y) {
  4212. if (closed) {
  4213. //Tools.Error("cannot add lines to closed paths");
  4214. return this;
  4215. }
  4216. var newPoint = new Vector2(x, y);
  4217. var previousPoint = this._points[this._points.length - 1];
  4218. this._points.push(newPoint);
  4219. this._length += newPoint.subtract(previousPoint).length();
  4220. return this;
  4221. };
  4222. /**
  4223. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4224. * Returns the updated Path2.
  4225. */
  4226. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4227. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4228. if (closed) {
  4229. //Tools.Error("cannot add arcs to closed paths");
  4230. return this;
  4231. }
  4232. var startPoint = this._points[this._points.length - 1];
  4233. var midPoint = new Vector2(midX, midY);
  4234. var endPoint = new Vector2(endX, endY);
  4235. var arc = new Arc2(startPoint, midPoint, endPoint);
  4236. var increment = arc.angle.radians() / numberOfSegments;
  4237. if (arc.orientation === Orientation.CW)
  4238. increment *= -1;
  4239. var currentAngle = arc.startAngle.radians() + increment;
  4240. for (var i = 0; i < numberOfSegments; i++) {
  4241. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4242. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4243. this.addLineTo(x, y);
  4244. currentAngle += increment;
  4245. }
  4246. return this;
  4247. };
  4248. /**
  4249. * Closes the Path2.
  4250. * Returns the Path2.
  4251. */
  4252. Path2.prototype.close = function () {
  4253. this.closed = true;
  4254. return this;
  4255. };
  4256. /**
  4257. * Returns the Path2 total length (float).
  4258. */
  4259. Path2.prototype.length = function () {
  4260. var result = this._length;
  4261. if (!this.closed) {
  4262. var lastPoint = this._points[this._points.length - 1];
  4263. var firstPoint = this._points[0];
  4264. result += (firstPoint.subtract(lastPoint).length());
  4265. }
  4266. return result;
  4267. };
  4268. /**
  4269. * Returns the Path2 internal array of points.
  4270. */
  4271. Path2.prototype.getPoints = function () {
  4272. return this._points;
  4273. };
  4274. /**
  4275. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4276. */
  4277. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4278. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4279. //Tools.Error("normalized length position should be between 0 and 1.");
  4280. return Vector2.Zero();
  4281. }
  4282. var lengthPosition = normalizedLengthPosition * this.length();
  4283. var previousOffset = 0;
  4284. for (var i = 0; i < this._points.length; i++) {
  4285. var j = (i + 1) % this._points.length;
  4286. var a = this._points[i];
  4287. var b = this._points[j];
  4288. var bToA = b.subtract(a);
  4289. var nextOffset = (bToA.length() + previousOffset);
  4290. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4291. var dir = bToA.normalize();
  4292. var localOffset = lengthPosition - previousOffset;
  4293. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4294. }
  4295. previousOffset = nextOffset;
  4296. }
  4297. //Tools.Error("internal error");
  4298. return Vector2.Zero();
  4299. };
  4300. /**
  4301. * Returns a new Path2 starting at the coordinates (x, y).
  4302. */
  4303. Path2.StartingAt = function (x, y) {
  4304. return new Path2(x, y);
  4305. };
  4306. return Path2;
  4307. }());
  4308. BABYLON.Path2 = Path2;
  4309. var Path3D = (function () {
  4310. /**
  4311. * new Path3D(path, normal, raw)
  4312. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4313. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4314. * path : an array of Vector3, the curve axis of the Path3D
  4315. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4316. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4317. */
  4318. function Path3D(path, firstNormal, raw) {
  4319. this.path = path;
  4320. this._curve = new Array();
  4321. this._distances = new Array();
  4322. this._tangents = new Array();
  4323. this._normals = new Array();
  4324. this._binormals = new Array();
  4325. for (var p = 0; p < path.length; p++) {
  4326. this._curve[p] = path[p].clone(); // hard copy
  4327. }
  4328. this._raw = raw || false;
  4329. this._compute(firstNormal);
  4330. }
  4331. /**
  4332. * Returns the Path3D array of successive Vector3 designing its curve.
  4333. */
  4334. Path3D.prototype.getCurve = function () {
  4335. return this._curve;
  4336. };
  4337. /**
  4338. * Returns an array populated with tangent vectors on each Path3D curve point.
  4339. */
  4340. Path3D.prototype.getTangents = function () {
  4341. return this._tangents;
  4342. };
  4343. /**
  4344. * Returns an array populated with normal vectors on each Path3D curve point.
  4345. */
  4346. Path3D.prototype.getNormals = function () {
  4347. return this._normals;
  4348. };
  4349. /**
  4350. * Returns an array populated with binormal vectors on each Path3D curve point.
  4351. */
  4352. Path3D.prototype.getBinormals = function () {
  4353. return this._binormals;
  4354. };
  4355. /**
  4356. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4357. */
  4358. Path3D.prototype.getDistances = function () {
  4359. return this._distances;
  4360. };
  4361. /**
  4362. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4363. * Returns the same object updated.
  4364. */
  4365. Path3D.prototype.update = function (path, firstNormal) {
  4366. for (var p = 0; p < path.length; p++) {
  4367. this._curve[p].x = path[p].x;
  4368. this._curve[p].y = path[p].y;
  4369. this._curve[p].z = path[p].z;
  4370. }
  4371. this._compute(firstNormal);
  4372. return this;
  4373. };
  4374. // private function compute() : computes tangents, normals and binormals
  4375. Path3D.prototype._compute = function (firstNormal) {
  4376. var l = this._curve.length;
  4377. // first and last tangents
  4378. this._tangents[0] = this._getFirstNonNullVector(0);
  4379. if (!this._raw) {
  4380. this._tangents[0].normalize();
  4381. }
  4382. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4383. if (!this._raw) {
  4384. this._tangents[l - 1].normalize();
  4385. }
  4386. // normals and binormals at first point : arbitrary vector with _normalVector()
  4387. var tg0 = this._tangents[0];
  4388. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4389. this._normals[0] = pp0;
  4390. if (!this._raw) {
  4391. this._normals[0].normalize();
  4392. }
  4393. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4394. if (!this._raw) {
  4395. this._binormals[0].normalize();
  4396. }
  4397. this._distances[0] = 0.0;
  4398. // normals and binormals : next points
  4399. var prev; // previous vector (segment)
  4400. var cur; // current vector (segment)
  4401. var curTang; // current tangent
  4402. // previous normal
  4403. var prevBinor; // previous binormal
  4404. for (var i = 1; i < l; i++) {
  4405. // tangents
  4406. prev = this._getLastNonNullVector(i);
  4407. if (i < l - 1) {
  4408. cur = this._getFirstNonNullVector(i);
  4409. this._tangents[i] = prev.add(cur);
  4410. this._tangents[i].normalize();
  4411. }
  4412. this._distances[i] = this._distances[i - 1] + prev.length();
  4413. // normals and binormals
  4414. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4415. curTang = this._tangents[i];
  4416. prevBinor = this._binormals[i - 1];
  4417. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4418. if (!this._raw) {
  4419. this._normals[i].normalize();
  4420. }
  4421. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4422. if (!this._raw) {
  4423. this._binormals[i].normalize();
  4424. }
  4425. }
  4426. };
  4427. // private function getFirstNonNullVector(index)
  4428. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4429. Path3D.prototype._getFirstNonNullVector = function (index) {
  4430. var i = 1;
  4431. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4432. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4433. i++;
  4434. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4435. }
  4436. return nNVector;
  4437. };
  4438. // private function getLastNonNullVector(index)
  4439. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4440. Path3D.prototype._getLastNonNullVector = function (index) {
  4441. var i = 1;
  4442. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4443. while (nLVector.length() === 0 && index > i + 1) {
  4444. i++;
  4445. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4446. }
  4447. return nLVector;
  4448. };
  4449. // private function normalVector(v0, vt, va) :
  4450. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4451. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4452. Path3D.prototype._normalVector = function (v0, vt, va) {
  4453. var normal0;
  4454. var tgl = vt.length();
  4455. if (tgl === 0.0) {
  4456. tgl = 1.0;
  4457. }
  4458. if (va === undefined || va === null) {
  4459. var point;
  4460. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4461. point = new Vector3(0.0, -1.0, 0.0);
  4462. }
  4463. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4464. point = new Vector3(1.0, 0.0, 0.0);
  4465. }
  4466. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4467. point = new Vector3(0.0, 0.0, 1.0);
  4468. }
  4469. normal0 = Vector3.Cross(vt, point);
  4470. }
  4471. else {
  4472. normal0 = Vector3.Cross(vt, va);
  4473. Vector3.CrossToRef(normal0, vt, normal0);
  4474. }
  4475. normal0.normalize();
  4476. return normal0;
  4477. };
  4478. return Path3D;
  4479. }());
  4480. BABYLON.Path3D = Path3D;
  4481. var Curve3 = (function () {
  4482. /**
  4483. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4484. * A Curve3 is designed from a series of successive Vector3.
  4485. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4486. */
  4487. function Curve3(points) {
  4488. this._length = 0.0;
  4489. this._points = points;
  4490. this._length = this._computeLength(points);
  4491. }
  4492. /**
  4493. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4494. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4495. * @param v1 (Vector3) the control point
  4496. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4500. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4501. var bez = new Array();
  4502. var equation = function (t, val0, val1, val2) {
  4503. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4504. return res;
  4505. };
  4506. for (var i = 0; i <= nbPoints; i++) {
  4507. 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)));
  4508. }
  4509. return new Curve3(bez);
  4510. };
  4511. /**
  4512. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4513. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4514. * @param v1 (Vector3) the first control point
  4515. * @param v2 (Vector3) the second control point
  4516. * @param v3 (Vector3) the end point of the Cubic Bezier
  4517. * @param nbPoints (integer) the wanted number of points in the curve
  4518. */
  4519. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4520. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4521. var bez = new Array();
  4522. var equation = function (t, val0, val1, val2, val3) {
  4523. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4524. return res;
  4525. };
  4526. for (var i = 0; i <= nbPoints; i++) {
  4527. 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)));
  4528. }
  4529. return new Curve3(bez);
  4530. };
  4531. /**
  4532. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4533. * @param p1 (Vector3) the origin point of the Hermite Spline
  4534. * @param t1 (Vector3) the tangent vector at the origin point
  4535. * @param p2 (Vector3) the end point of the Hermite Spline
  4536. * @param t2 (Vector3) the tangent vector at the end point
  4537. * @param nbPoints (integer) the wanted number of points in the curve
  4538. */
  4539. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4540. var hermite = new Array();
  4541. var step = 1.0 / nbPoints;
  4542. for (var i = 0; i <= nbPoints; i++) {
  4543. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4544. }
  4545. return new Curve3(hermite);
  4546. };
  4547. /**
  4548. * Returns a Curve3 object along a CatmullRom Spline curve :
  4549. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4550. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4551. */
  4552. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4553. var totalPoints = new Array();
  4554. totalPoints.push(points[0].clone());
  4555. Array.prototype.push.apply(totalPoints, points);
  4556. totalPoints.push(points[points.length - 1].clone());
  4557. var catmullRom = new Array();
  4558. var step = 1.0 / nbPoints;
  4559. for (var i = 0; i < totalPoints.length - 3; i++) {
  4560. var amount = 0.0;
  4561. for (var c = 0; c < nbPoints; c++) {
  4562. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4563. amount += step;
  4564. }
  4565. }
  4566. i--;
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. return new Curve3(catmullRom);
  4569. };
  4570. /**
  4571. * Returns the Curve3 stored array of successive Vector3
  4572. */
  4573. Curve3.prototype.getPoints = function () {
  4574. return this._points;
  4575. };
  4576. /**
  4577. * Returns the computed length (float) of the curve.
  4578. */
  4579. Curve3.prototype.length = function () {
  4580. return this._length;
  4581. };
  4582. /**
  4583. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4584. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4585. * curveA and curveB keep unchanged.
  4586. */
  4587. Curve3.prototype.continue = function (curve) {
  4588. var lastPoint = this._points[this._points.length - 1];
  4589. var continuedPoints = this._points.slice();
  4590. var curvePoints = curve.getPoints();
  4591. for (var i = 1; i < curvePoints.length; i++) {
  4592. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4593. }
  4594. var continuedCurve = new Curve3(continuedPoints);
  4595. return continuedCurve;
  4596. };
  4597. Curve3.prototype._computeLength = function (path) {
  4598. var l = 0;
  4599. for (var i = 1; i < path.length; i++) {
  4600. l += (path[i].subtract(path[i - 1])).length();
  4601. }
  4602. return l;
  4603. };
  4604. return Curve3;
  4605. }());
  4606. BABYLON.Curve3 = Curve3;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4644. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4645. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4646. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4647. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4648. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4649. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero(),
  4651. Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4653. return Tmp;
  4654. }());
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. MathTmp.Vector3 = [Vector3.Zero()];
  4661. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4662. MathTmp.Quaternion = [Quaternion.Zero()];
  4663. return MathTmp;
  4664. }());
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. var BABYLON;
  4668. (function (BABYLON) {
  4669. var Scalar = (function () {
  4670. function Scalar() {
  4671. }
  4672. /**
  4673. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4674. */
  4675. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4676. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4677. var num = a - b;
  4678. return -epsilon <= num && num <= epsilon;
  4679. };
  4680. /**
  4681. * Returns a string : the upper case translation of the number i to hexadecimal.
  4682. */
  4683. Scalar.ToHex = function (i) {
  4684. var str = i.toString(16);
  4685. if (i <= 15) {
  4686. return ("0" + str).toUpperCase();
  4687. }
  4688. return str.toUpperCase();
  4689. };
  4690. /**
  4691. * Returns -1 if value is negative and +1 is value is positive.
  4692. * Returns the value itself if it's equal to zero.
  4693. */
  4694. Scalar.Sign = function (value) {
  4695. value = +value; // convert to a number
  4696. if (value === 0 || isNaN(value))
  4697. return value;
  4698. return value > 0 ? 1 : -1;
  4699. };
  4700. /**
  4701. * Returns the value itself if it's between min and max.
  4702. * Returns min if the value is lower than min.
  4703. * Returns max if the value is greater than max.
  4704. */
  4705. Scalar.Clamp = function (value, min, max) {
  4706. if (min === void 0) { min = 0; }
  4707. if (max === void 0) { max = 1; }
  4708. return Math.min(max, Math.max(min, value));
  4709. };
  4710. /**
  4711. * Returns the log2 of value.
  4712. */
  4713. Scalar.Log2 = function (value) {
  4714. return Math.log(value) * Math.LOG2E;
  4715. };
  4716. /**
  4717. * Loops the value, so that it is never larger than length and never smaller than 0.
  4718. *
  4719. * This is similar to the modulo operator but it works with floating point numbers.
  4720. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4721. * With t = 5 and length = 2.5, the result would be 0.0.
  4722. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4723. */
  4724. Scalar.Repeat = function (value, length) {
  4725. return value - Math.floor(value / length) * length;
  4726. };
  4727. /**
  4728. * Normalize the value between 0.0 and 1.0 using min and max values
  4729. */
  4730. Scalar.Normalize = function (value, min, max) {
  4731. return (value - min) / (max - min);
  4732. };
  4733. /**
  4734. * Denormalize the value from 0.0 and 1.0 using min and max values
  4735. */
  4736. Scalar.Denormalize = function (normalized, min, max) {
  4737. return (normalized * (max - min) + min);
  4738. };
  4739. /**
  4740. * Calculates the shortest difference between two given angles given in degrees.
  4741. */
  4742. Scalar.DeltaAngle = function (current, target) {
  4743. var num = Scalar.Repeat(target - current, 360.0);
  4744. if (num > 180.0) {
  4745. num -= 360.0;
  4746. }
  4747. return num;
  4748. };
  4749. /**
  4750. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4751. *
  4752. * The returned value will move back and forth between 0 and length
  4753. */
  4754. Scalar.PingPong = function (tx, length) {
  4755. var t = Scalar.Repeat(tx, length * 2.0);
  4756. return length - Math.abs(t - length);
  4757. };
  4758. /**
  4759. * Interpolates between min and max with smoothing at the limits.
  4760. *
  4761. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4762. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4763. */
  4764. Scalar.SmoothStep = function (from, to, tx) {
  4765. var t = Scalar.Clamp(tx);
  4766. t = -2.0 * t * t * t + 3.0 * t * t;
  4767. return to * t + from * (1.0 - t);
  4768. };
  4769. /**
  4770. * Moves a value current towards target.
  4771. *
  4772. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4773. * Negative values of maxDelta pushes the value away from target.
  4774. */
  4775. Scalar.MoveTowards = function (current, target, maxDelta) {
  4776. var result = 0;
  4777. if (Math.abs(target - current) <= maxDelta) {
  4778. result = target;
  4779. }
  4780. else {
  4781. result = current + Scalar.Sign(target - current) * maxDelta;
  4782. }
  4783. return result;
  4784. };
  4785. /**
  4786. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4787. *
  4788. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4789. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4790. */
  4791. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4792. var num = Scalar.DeltaAngle(current, target);
  4793. var result = 0;
  4794. if (-maxDelta < num && num < maxDelta) {
  4795. result = target;
  4796. }
  4797. else {
  4798. target = current + num;
  4799. result = Scalar.MoveTowards(current, target, maxDelta);
  4800. }
  4801. return result;
  4802. };
  4803. /**
  4804. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4805. */
  4806. Scalar.Lerp = function (start, end, amount) {
  4807. return start + ((end - start) * amount);
  4808. };
  4809. /**
  4810. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4811. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4812. */
  4813. Scalar.LerpAngle = function (start, end, amount) {
  4814. var num = Scalar.Repeat(end - start, 360.0);
  4815. if (num > 180.0) {
  4816. num -= 360.0;
  4817. }
  4818. return start + num * Scalar.Clamp(amount);
  4819. };
  4820. /**
  4821. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4822. */
  4823. Scalar.InverseLerp = function (a, b, value) {
  4824. var result = 0;
  4825. if (a != b) {
  4826. result = Scalar.Clamp((value - a) / (b - a));
  4827. }
  4828. else {
  4829. result = 0.0;
  4830. }
  4831. return result;
  4832. };
  4833. /**
  4834. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4835. */
  4836. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4837. var squared = amount * amount;
  4838. var cubed = amount * squared;
  4839. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4840. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4841. var part3 = (cubed - (2.0 * squared)) + amount;
  4842. var part4 = cubed - squared;
  4843. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4844. };
  4845. /**
  4846. * Returns a random float number between and min and max values
  4847. */
  4848. Scalar.RandomRange = function (min, max) {
  4849. if (min === max)
  4850. return min;
  4851. return ((Math.random() * (max - min)) + min);
  4852. };
  4853. /**
  4854. * This function returns percentage of a number in a given range.
  4855. *
  4856. * RangeToPercent(40,20,60) will return 0.5 (50%)
  4857. * RangeToPercent(34,0,100) will return 0.34 (34%)
  4858. */
  4859. Scalar.RangeToPercent = function (number, min, max) {
  4860. return ((number - min) / (max - min));
  4861. };
  4862. /**
  4863. * This function returns number that corresponds to the percentage in a given range.
  4864. *
  4865. * PercentToRange(0.34,0,100) will return 34.
  4866. */
  4867. Scalar.PercentToRange = function (percent, min, max) {
  4868. return ((max - min) * percent + min);
  4869. };
  4870. return Scalar;
  4871. }());
  4872. BABYLON.Scalar = Scalar;
  4873. })(BABYLON || (BABYLON = {}));
  4874. //# sourceMappingURL=babylon.math.scalar.js.map
  4875. //# sourceMappingURL=babylon.mixins.js.map
  4876. var BABYLON;
  4877. (function (BABYLON) {
  4878. var __decoratorInitialStore = {};
  4879. var __mergedStore = {};
  4880. var _copySource = function (creationFunction, source, instanciate) {
  4881. var destination = creationFunction();
  4882. // Tags
  4883. if (BABYLON.Tags) {
  4884. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4885. }
  4886. var classStore = getMergedStore(destination);
  4887. // Properties
  4888. for (var property in classStore) {
  4889. var propertyDescriptor = classStore[property];
  4890. var sourceProperty = source[property];
  4891. var propertyType = propertyDescriptor.type;
  4892. if (sourceProperty !== undefined && sourceProperty !== null) {
  4893. switch (propertyType) {
  4894. case 0: // Value
  4895. case 6:// Mesh reference
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1: // Texture
  4899. case 2: // Color3
  4900. case 3: // FresnelParameters
  4901. case 4: // Vector2
  4902. case 5: // Vector3
  4903. case 7:// Color Curves
  4904. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  4905. break;
  4906. }
  4907. }
  4908. }
  4909. return destination;
  4910. };
  4911. function getDirectStore(target) {
  4912. var classKey = target.getClassName();
  4913. if (!__decoratorInitialStore[classKey]) {
  4914. __decoratorInitialStore[classKey] = {};
  4915. }
  4916. return __decoratorInitialStore[classKey];
  4917. }
  4918. /**
  4919. * Return the list of properties flagged as serializable
  4920. * @param target: host object
  4921. */
  4922. function getMergedStore(target) {
  4923. var classKey = target.getClassName();
  4924. if (__mergedStore[classKey]) {
  4925. return __mergedStore[classKey];
  4926. }
  4927. __mergedStore[classKey] = {};
  4928. var store = __mergedStore[classKey];
  4929. var currentTarget = target;
  4930. var currentKey = classKey;
  4931. while (currentKey) {
  4932. var initialStore = __decoratorInitialStore[currentKey];
  4933. for (var property in initialStore) {
  4934. store[property] = initialStore[property];
  4935. }
  4936. var parent_1 = void 0;
  4937. var done = false;
  4938. do {
  4939. parent_1 = Object.getPrototypeOf(currentTarget);
  4940. if (!parent_1.getClassName) {
  4941. done = true;
  4942. break;
  4943. }
  4944. if (parent_1.getClassName() !== currentKey) {
  4945. break;
  4946. }
  4947. currentTarget = parent_1;
  4948. } while (parent_1);
  4949. if (done) {
  4950. break;
  4951. }
  4952. currentKey = parent_1.getClassName();
  4953. currentTarget = parent_1;
  4954. }
  4955. return store;
  4956. }
  4957. function generateSerializableMember(type, sourceName) {
  4958. return function (target, propertyKey) {
  4959. var classStore = getDirectStore(target);
  4960. if (!classStore[propertyKey]) {
  4961. classStore[propertyKey] = { type: type, sourceName: sourceName };
  4962. }
  4963. };
  4964. }
  4965. function generateExpandMember(setCallback, targetKey) {
  4966. return function (target, propertyKey) {
  4967. var key = targetKey || ("_" + propertyKey);
  4968. Object.defineProperty(target, propertyKey, {
  4969. get: function () {
  4970. return this[key];
  4971. },
  4972. set: function (value) {
  4973. if (this[key] === value) {
  4974. return;
  4975. }
  4976. this[key] = value;
  4977. target[setCallback].apply(this);
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. };
  4983. }
  4984. function expandToProperty(callback, targetKey) {
  4985. return generateExpandMember(callback, targetKey);
  4986. }
  4987. BABYLON.expandToProperty = expandToProperty;
  4988. function serialize(sourceName) {
  4989. return generateSerializableMember(0, sourceName); // value member
  4990. }
  4991. BABYLON.serialize = serialize;
  4992. function serializeAsTexture(sourceName) {
  4993. return generateSerializableMember(1, sourceName); // texture member
  4994. }
  4995. BABYLON.serializeAsTexture = serializeAsTexture;
  4996. function serializeAsColor3(sourceName) {
  4997. return generateSerializableMember(2, sourceName); // color3 member
  4998. }
  4999. BABYLON.serializeAsColor3 = serializeAsColor3;
  5000. function serializeAsFresnelParameters(sourceName) {
  5001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5002. }
  5003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5004. function serializeAsVector2(sourceName) {
  5005. return generateSerializableMember(4, sourceName); // vector2 member
  5006. }
  5007. BABYLON.serializeAsVector2 = serializeAsVector2;
  5008. function serializeAsVector3(sourceName) {
  5009. return generateSerializableMember(5, sourceName); // vector3 member
  5010. }
  5011. BABYLON.serializeAsVector3 = serializeAsVector3;
  5012. function serializeAsMeshReference(sourceName) {
  5013. return generateSerializableMember(6, sourceName); // mesh reference member
  5014. }
  5015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5016. function serializeAsColorCurves(sourceName) {
  5017. return generateSerializableMember(7, sourceName); // color curves
  5018. }
  5019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5020. function serializeAsColor4(sourceName) {
  5021. return generateSerializableMember(8, sourceName); // color 4
  5022. }
  5023. BABYLON.serializeAsColor4 = serializeAsColor4;
  5024. function serializeAsImageProcessingConfiguration(sourceName) {
  5025. return generateSerializableMember(9, sourceName); // image processing
  5026. }
  5027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5028. var SerializationHelper = (function () {
  5029. function SerializationHelper() {
  5030. }
  5031. SerializationHelper.Serialize = function (entity, serializationObject) {
  5032. if (!serializationObject) {
  5033. serializationObject = {};
  5034. }
  5035. // Tags
  5036. if (BABYLON.Tags) {
  5037. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5038. }
  5039. var serializedProperties = getMergedStore(entity);
  5040. // Properties
  5041. for (var property in serializedProperties) {
  5042. var propertyDescriptor = serializedProperties[property];
  5043. var targetPropertyName = propertyDescriptor.sourceName || property;
  5044. var propertyType = propertyDescriptor.type;
  5045. var sourceProperty = entity[property];
  5046. if (sourceProperty !== undefined && sourceProperty !== null) {
  5047. switch (propertyType) {
  5048. case 0:// Value
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:// Texture
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:// Color3
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:// FresnelParameters
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:// Vector2
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:// Vector3
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:// Mesh reference
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:// Color Curves
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:// Color 4
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:// Image Processing
  5076. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. return serializationObject;
  5082. };
  5083. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5084. var destination = creationFunction();
  5085. // Tags
  5086. if (BABYLON.Tags) {
  5087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5088. }
  5089. var classStore = getMergedStore(destination);
  5090. // Properties
  5091. for (var property in classStore) {
  5092. var propertyDescriptor = classStore[property];
  5093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5094. var propertyType = propertyDescriptor.type;
  5095. if (sourceProperty !== undefined && sourceProperty !== null) {
  5096. switch (propertyType) {
  5097. case 0:// Value
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:// Texture
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:// Color3
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:// FresnelParameters
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:// Vector2
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:// Vector3
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:// Mesh reference
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:// Color Curves
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:// Color 4
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:// Image Processing
  5125. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. return destination;
  5131. };
  5132. SerializationHelper.Clone = function (creationFunction, source) {
  5133. return _copySource(creationFunction, source, false);
  5134. };
  5135. SerializationHelper.Instanciate = function (creationFunction, source) {
  5136. return _copySource(creationFunction, source, true);
  5137. };
  5138. return SerializationHelper;
  5139. }());
  5140. BABYLON.SerializationHelper = SerializationHelper;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.decorators.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. /**
  5146. * A class serves as a medium between the observable and its observers
  5147. */
  5148. var EventState = (function () {
  5149. /**
  5150. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5151. */
  5152. function EventState(mask, skipNextObservers) {
  5153. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5154. this.initalize(mask, skipNextObservers);
  5155. }
  5156. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5157. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5158. this.mask = mask;
  5159. this.skipNextObservers = skipNextObservers;
  5160. return this;
  5161. };
  5162. return EventState;
  5163. }());
  5164. BABYLON.EventState = EventState;
  5165. /**
  5166. * Represent an Observer registered to a given Observable object.
  5167. */
  5168. var Observer = (function () {
  5169. function Observer(callback, mask) {
  5170. this.callback = callback;
  5171. this.mask = mask;
  5172. }
  5173. return Observer;
  5174. }());
  5175. BABYLON.Observer = Observer;
  5176. /**
  5177. * The Observable class is a simple implementation of the Observable pattern.
  5178. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5179. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5180. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5181. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5182. */
  5183. var Observable = (function () {
  5184. function Observable() {
  5185. this._observers = new Array();
  5186. this._eventState = new EventState(0);
  5187. }
  5188. /**
  5189. * Create a new Observer with the specified callback
  5190. * @param callback the callback that will be executed for that Observer
  5191. * @param mask the mask used to filter observers
  5192. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5193. */
  5194. Observable.prototype.add = function (callback, mask, insertFirst) {
  5195. if (mask === void 0) { mask = -1; }
  5196. if (insertFirst === void 0) { insertFirst = false; }
  5197. if (!callback) {
  5198. return null;
  5199. }
  5200. var observer = new Observer(callback, mask);
  5201. if (insertFirst) {
  5202. this._observers.unshift(observer);
  5203. }
  5204. else {
  5205. this._observers.push(observer);
  5206. }
  5207. return observer;
  5208. };
  5209. /**
  5210. * Remove an Observer from the Observable object
  5211. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5212. */
  5213. Observable.prototype.remove = function (observer) {
  5214. var index = this._observers.indexOf(observer);
  5215. if (index !== -1) {
  5216. this._observers.splice(index, 1);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. /**
  5222. * Remove a callback from the Observable object
  5223. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5224. */
  5225. Observable.prototype.removeCallback = function (callback) {
  5226. for (var index = 0; index < this._observers.length; index++) {
  5227. if (this._observers[index].callback === callback) {
  5228. this._observers.splice(index, 1);
  5229. return true;
  5230. }
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Notify all Observers by calling their respective callback with the given data
  5236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5237. * @param eventData
  5238. * @param mask
  5239. */
  5240. Observable.prototype.notifyObservers = function (eventData, mask) {
  5241. if (mask === void 0) { mask = -1; }
  5242. var state = this._eventState;
  5243. state.mask = mask;
  5244. state.skipNextObservers = false;
  5245. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5246. var obs = _a[_i];
  5247. if (obs.mask & mask) {
  5248. obs.callback(eventData, state);
  5249. }
  5250. if (state.skipNextObservers) {
  5251. return false;
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. /**
  5257. * return true is the Observable has at least one Observer registered
  5258. */
  5259. Observable.prototype.hasObservers = function () {
  5260. return this._observers.length > 0;
  5261. };
  5262. /**
  5263. * Clear the list of observers
  5264. */
  5265. Observable.prototype.clear = function () {
  5266. this._observers = new Array();
  5267. };
  5268. /**
  5269. * Clone the current observable
  5270. */
  5271. Observable.prototype.clone = function () {
  5272. var result = new Observable();
  5273. result._observers = this._observers.slice(0);
  5274. return result;
  5275. };
  5276. /**
  5277. * Does this observable handles observer registered with a given mask
  5278. * @param {number} trigger - the mask to be tested
  5279. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5280. **/
  5281. Observable.prototype.hasSpecificMask = function (mask) {
  5282. if (mask === void 0) { mask = -1; }
  5283. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5284. var obs = _a[_i];
  5285. if (obs.mask & mask && obs.mask === mask) {
  5286. return true;
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. return Observable;
  5292. }());
  5293. BABYLON.Observable = Observable;
  5294. })(BABYLON || (BABYLON = {}));
  5295. //# sourceMappingURL=babylon.observable.js.map
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var SmartArray = (function () {
  5299. function SmartArray(capacity) {
  5300. this.length = 0;
  5301. this._duplicateId = 0;
  5302. this.data = new Array(capacity);
  5303. this._id = SmartArray._GlobalId++;
  5304. }
  5305. SmartArray.prototype.push = function (value) {
  5306. this.data[this.length++] = value;
  5307. if (this.length > this.data.length) {
  5308. this.data.length *= 2;
  5309. }
  5310. if (!value.__smartArrayFlags) {
  5311. value.__smartArrayFlags = {};
  5312. }
  5313. value.__smartArrayFlags[this._id] = this._duplicateId;
  5314. };
  5315. SmartArray.prototype.forEach = function (func) {
  5316. for (var index = 0; index < this.length; index++) {
  5317. func(this.data[index]);
  5318. }
  5319. };
  5320. SmartArray.prototype.pushNoDuplicate = function (value) {
  5321. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5322. return false;
  5323. }
  5324. this.push(value);
  5325. return true;
  5326. };
  5327. SmartArray.prototype.sort = function (compareFn) {
  5328. this.data.sort(compareFn);
  5329. };
  5330. SmartArray.prototype.reset = function () {
  5331. this.length = 0;
  5332. this._duplicateId++;
  5333. };
  5334. SmartArray.prototype.dispose = function () {
  5335. this.reset();
  5336. if (this.data) {
  5337. this.data.length = 0;
  5338. this.data = null;
  5339. }
  5340. };
  5341. SmartArray.prototype.concat = function (array) {
  5342. if (array.length === 0) {
  5343. return;
  5344. }
  5345. if (this.length + array.length > this.data.length) {
  5346. this.data.length = (this.length + array.length) * 2;
  5347. }
  5348. for (var index = 0; index < array.length; index++) {
  5349. this.data[this.length++] = (array.data || array)[index];
  5350. }
  5351. };
  5352. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5353. if (array.length === 0) {
  5354. return;
  5355. }
  5356. if (this.length + array.length > this.data.length) {
  5357. this.data.length = (this.length + array.length) * 2;
  5358. }
  5359. for (var index = 0; index < array.length; index++) {
  5360. var item = (array.data || array)[index];
  5361. this.pushNoDuplicate(item);
  5362. }
  5363. };
  5364. SmartArray.prototype.indexOf = function (value) {
  5365. var position = this.data.indexOf(value);
  5366. if (position >= this.length) {
  5367. return -1;
  5368. }
  5369. return position;
  5370. };
  5371. SmartArray.prototype.contains = function (value) {
  5372. return this.data.indexOf(value) !== -1;
  5373. };
  5374. // Statics
  5375. SmartArray._GlobalId = 0;
  5376. return SmartArray;
  5377. }());
  5378. BABYLON.SmartArray = SmartArray;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.smartArray.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. // Screenshots
  5384. var screenshotCanvas;
  5385. var cloneValue = function (source, destinationObject) {
  5386. if (!source)
  5387. return null;
  5388. if (source instanceof BABYLON.Mesh) {
  5389. return null;
  5390. }
  5391. if (source instanceof BABYLON.SubMesh) {
  5392. return source.clone(destinationObject);
  5393. }
  5394. else if (source.clone) {
  5395. return source.clone();
  5396. }
  5397. return null;
  5398. };
  5399. var Tools = (function () {
  5400. function Tools() {
  5401. }
  5402. ;
  5403. /**
  5404. * Interpolates between a and b via alpha
  5405. * @param a The lower value (returned when alpha = 0)
  5406. * @param b The upper value (returned when alpha = 1)
  5407. * @param alpha The interpolation-factor
  5408. * @return The mixed value
  5409. */
  5410. Tools.Mix = function (a, b, alpha) {
  5411. return a * (1 - alpha) + b * alpha;
  5412. };
  5413. Tools.Instantiate = function (className) {
  5414. var arr = className.split(".");
  5415. var fn = (window || this);
  5416. for (var i = 0, len = arr.length; i < len; i++) {
  5417. fn = fn[arr[i]];
  5418. }
  5419. if (typeof fn !== "function") {
  5420. return null;
  5421. }
  5422. return fn;
  5423. };
  5424. Tools.SetImmediate = function (action) {
  5425. if (window.setImmediate) {
  5426. window.setImmediate(action);
  5427. }
  5428. else {
  5429. setTimeout(action, 1);
  5430. }
  5431. };
  5432. Tools.IsExponentOfTwo = function (value) {
  5433. var count = 1;
  5434. do {
  5435. count *= 2;
  5436. } while (count < value);
  5437. return count === value;
  5438. };
  5439. /**
  5440. * Find the next highest power of two.
  5441. * @param x Number to start search from.
  5442. * @return Next highest power of two.
  5443. */
  5444. Tools.CeilingPOT = function (x) {
  5445. x--;
  5446. x |= x >> 1;
  5447. x |= x >> 2;
  5448. x |= x >> 4;
  5449. x |= x >> 8;
  5450. x |= x >> 16;
  5451. x++;
  5452. return x;
  5453. };
  5454. /**
  5455. * Find the next lowest power of two.
  5456. * @param x Number to start search from.
  5457. * @return Next lowest power of two.
  5458. */
  5459. Tools.FloorPOT = function (x) {
  5460. x = x | (x >> 1);
  5461. x = x | (x >> 2);
  5462. x = x | (x >> 4);
  5463. x = x | (x >> 8);
  5464. x = x | (x >> 16);
  5465. return x - (x >> 1);
  5466. };
  5467. /**
  5468. * Find the nearest power of two.
  5469. * @param x Number to start search from.
  5470. * @return Next nearest power of two.
  5471. */
  5472. Tools.NearestPOT = function (x) {
  5473. var c = Tools.CeilingPOT(x);
  5474. var f = Tools.FloorPOT(x);
  5475. return (c - x) > (x - f) ? f : c;
  5476. };
  5477. Tools.GetExponentOfTwo = function (value, max, mode) {
  5478. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5479. var pot;
  5480. switch (mode) {
  5481. case BABYLON.Engine.SCALEMODE_FLOOR:
  5482. pot = Tools.FloorPOT(value);
  5483. break;
  5484. case BABYLON.Engine.SCALEMODE_NEAREST:
  5485. pot = Tools.NearestPOT(value);
  5486. break;
  5487. case BABYLON.Engine.SCALEMODE_CEILING:
  5488. pot = Tools.CeilingPOT(value);
  5489. break;
  5490. }
  5491. return Math.min(pot, max);
  5492. };
  5493. Tools.GetFilename = function (path) {
  5494. var index = path.lastIndexOf("/");
  5495. if (index < 0)
  5496. return path;
  5497. return path.substring(index + 1);
  5498. };
  5499. Tools.GetDOMTextContent = function (element) {
  5500. var result = "";
  5501. var child = element.firstChild;
  5502. while (child) {
  5503. if (child.nodeType === 3) {
  5504. result += child.textContent;
  5505. }
  5506. child = child.nextSibling;
  5507. }
  5508. return result;
  5509. };
  5510. Tools.ToDegrees = function (angle) {
  5511. return angle * 180 / Math.PI;
  5512. };
  5513. Tools.ToRadians = function (angle) {
  5514. return angle * Math.PI / 180;
  5515. };
  5516. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5517. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5518. var output = "";
  5519. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5520. var i = 0;
  5521. var bytes = new Uint8Array(buffer);
  5522. while (i < bytes.length) {
  5523. chr1 = bytes[i++];
  5524. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5525. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5526. enc1 = chr1 >> 2;
  5527. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5528. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5529. enc4 = chr3 & 63;
  5530. if (isNaN(chr2)) {
  5531. enc3 = enc4 = 64;
  5532. }
  5533. else if (isNaN(chr3)) {
  5534. enc4 = 64;
  5535. }
  5536. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5537. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5538. }
  5539. return "data:image/png;base64," + output;
  5540. };
  5541. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5542. if (bias === void 0) { bias = null; }
  5543. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5544. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5545. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5546. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5547. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5548. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5549. }
  5550. if (bias) {
  5551. minimum.x -= minimum.x * bias.x + bias.y;
  5552. minimum.y -= minimum.y * bias.x + bias.y;
  5553. minimum.z -= minimum.z * bias.x + bias.y;
  5554. maximum.x += maximum.x * bias.x + bias.y;
  5555. maximum.y += maximum.y * bias.x + bias.y;
  5556. maximum.z += maximum.z * bias.x + bias.y;
  5557. }
  5558. return {
  5559. minimum: minimum,
  5560. maximum: maximum
  5561. };
  5562. };
  5563. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5564. if (bias === void 0) { bias = null; }
  5565. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5566. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5567. if (!stride) {
  5568. stride = 3;
  5569. }
  5570. for (var index = start; index < start + count; index++) {
  5571. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5572. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5573. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5574. }
  5575. if (bias) {
  5576. minimum.x -= minimum.x * bias.x + bias.y;
  5577. minimum.y -= minimum.y * bias.x + bias.y;
  5578. minimum.z -= minimum.z * bias.x + bias.y;
  5579. maximum.x += maximum.x * bias.x + bias.y;
  5580. maximum.y += maximum.y * bias.x + bias.y;
  5581. maximum.z += maximum.z * bias.x + bias.y;
  5582. }
  5583. return {
  5584. minimum: minimum,
  5585. maximum: maximum
  5586. };
  5587. };
  5588. Tools.Vector2ArrayFeeder = function (array) {
  5589. return function (index) {
  5590. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5591. var length = isFloatArray ? array.length / 2 : array.length;
  5592. if (index >= length) {
  5593. return null;
  5594. }
  5595. if (isFloatArray) {
  5596. var fa = array;
  5597. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5598. }
  5599. var a = array;
  5600. return a[index];
  5601. };
  5602. };
  5603. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5604. if (bias === void 0) { bias = null; }
  5605. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5606. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5607. var i = 0;
  5608. var cur = feeder(i++);
  5609. while (cur) {
  5610. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5611. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5612. cur = feeder(i++);
  5613. }
  5614. if (bias) {
  5615. minimum.x -= minimum.x * bias.x + bias.y;
  5616. minimum.y -= minimum.y * bias.x + bias.y;
  5617. maximum.x += maximum.x * bias.x + bias.y;
  5618. maximum.y += maximum.y * bias.x + bias.y;
  5619. }
  5620. return {
  5621. minimum: minimum,
  5622. maximum: maximum
  5623. };
  5624. };
  5625. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5626. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5627. return undefined;
  5628. return Array.isArray(obj) ? obj : [obj];
  5629. };
  5630. // Misc.
  5631. Tools.GetPointerPrefix = function () {
  5632. var eventPrefix = "pointer";
  5633. // Check if pointer events are supported
  5634. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5635. eventPrefix = "mouse";
  5636. }
  5637. return eventPrefix;
  5638. };
  5639. /**
  5640. * @param func - the function to be called
  5641. * @param requester - the object that will request the next frame. Falls back to window.
  5642. */
  5643. Tools.QueueNewFrame = function (func, requester) {
  5644. if (requester === void 0) { requester = window; }
  5645. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5646. /*if(requester.isPresenting) {
  5647. return;
  5648. } else*/ if (requester.requestAnimationFrame)
  5649. requester.requestAnimationFrame(func);
  5650. else if (requester.msRequestAnimationFrame)
  5651. requester.msRequestAnimationFrame(func);
  5652. else if (requester.webkitRequestAnimationFrame)
  5653. requester.webkitRequestAnimationFrame(func);
  5654. else if (requester.mozRequestAnimationFrame)
  5655. requester.mozRequestAnimationFrame(func);
  5656. else if (requester.oRequestAnimationFrame)
  5657. requester.oRequestAnimationFrame(func);
  5658. else {
  5659. window.setTimeout(func, 16);
  5660. }
  5661. };
  5662. Tools.RequestFullscreen = function (element) {
  5663. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5664. if (!requestFunction)
  5665. return;
  5666. requestFunction.call(element);
  5667. };
  5668. Tools.ExitFullscreen = function () {
  5669. if (document.exitFullscreen) {
  5670. document.exitFullscreen();
  5671. }
  5672. else if (document.mozCancelFullScreen) {
  5673. document.mozCancelFullScreen();
  5674. }
  5675. else if (document.webkitCancelFullScreen) {
  5676. document.webkitCancelFullScreen();
  5677. }
  5678. else if (document.msCancelFullScreen) {
  5679. document.msCancelFullScreen();
  5680. }
  5681. };
  5682. Tools.SetCorsBehavior = function (url, img) {
  5683. if (Tools.CorsBehavior) {
  5684. switch (typeof (Tools.CorsBehavior)) {
  5685. case "function":
  5686. var result = Tools.CorsBehavior(url);
  5687. if (result) {
  5688. img.crossOrigin = result;
  5689. }
  5690. break;
  5691. case "string":
  5692. default:
  5693. img.crossOrigin = Tools.CorsBehavior;
  5694. break;
  5695. }
  5696. }
  5697. };
  5698. // External files
  5699. Tools.CleanUrl = function (url) {
  5700. url = url.replace(/#/mg, "%23");
  5701. return url;
  5702. };
  5703. Tools.LoadImage = function (url, onload, onerror, database) {
  5704. if (url instanceof ArrayBuffer) {
  5705. url = Tools.EncodeArrayBufferTobase64(url);
  5706. }
  5707. url = Tools.CleanUrl(url);
  5708. url = Tools.PreprocessUrl(url);
  5709. var img = new Image();
  5710. if (url.substr(0, 5) !== "data:") {
  5711. Tools.SetCorsBehavior(url, img);
  5712. }
  5713. img.onload = function () {
  5714. onload(img);
  5715. };
  5716. img.onerror = function (err) {
  5717. Tools.Error("Error while trying to load image: " + url);
  5718. if (Tools.UseFallbackTexture) {
  5719. img.src = Tools.fallbackTexture;
  5720. onload(img);
  5721. }
  5722. else {
  5723. onerror();
  5724. }
  5725. };
  5726. var noIndexedDB = function () {
  5727. img.src = url;
  5728. };
  5729. var loadFromIndexedDB = function () {
  5730. database.loadImageFromDB(url, img);
  5731. };
  5732. //ANY database to do!
  5733. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5734. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5735. }
  5736. else {
  5737. if (url.indexOf("file:") !== 0) {
  5738. noIndexedDB();
  5739. }
  5740. else {
  5741. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5742. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5743. try {
  5744. var blobURL;
  5745. try {
  5746. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5747. }
  5748. catch (ex) {
  5749. // Chrome doesn't support oneTimeOnly parameter
  5750. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5751. }
  5752. img.src = blobURL;
  5753. }
  5754. catch (e) {
  5755. img.src = null;
  5756. }
  5757. }
  5758. else {
  5759. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5760. img.src = Tools.fallbackTexture;
  5761. }
  5762. }
  5763. }
  5764. return img;
  5765. };
  5766. //ANY
  5767. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5768. url = Tools.CleanUrl(url);
  5769. url = Tools.PreprocessUrl(url);
  5770. var noIndexedDB = function () {
  5771. var request = new XMLHttpRequest();
  5772. var loadUrl = Tools.BaseUrl + url;
  5773. request.open('GET', loadUrl, true);
  5774. if (useArrayBuffer) {
  5775. request.responseType = "arraybuffer";
  5776. }
  5777. request.onprogress = progressCallBack;
  5778. request.onreadystatechange = function () {
  5779. // In case of undefined state in some browsers.
  5780. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5781. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5782. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5783. callback(!useArrayBuffer ? request.responseText : request.response);
  5784. }
  5785. else {
  5786. if (onError) {
  5787. onError(request);
  5788. }
  5789. else {
  5790. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5791. }
  5792. }
  5793. }
  5794. };
  5795. request.send(null);
  5796. };
  5797. var loadFromIndexedDB = function () {
  5798. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5799. };
  5800. if (url.indexOf("file:") !== -1) {
  5801. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5802. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5803. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5804. }
  5805. else {
  5806. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5807. }
  5808. }
  5809. else {
  5810. // Caching all files
  5811. if (database && database.enableSceneOffline) {
  5812. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5813. }
  5814. else {
  5815. noIndexedDB();
  5816. }
  5817. }
  5818. };
  5819. /**
  5820. * Load a script (identified by an url). When the url returns, the
  5821. * content of this file is added into a new script element, attached to the DOM (body element)
  5822. */
  5823. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5824. var head = document.getElementsByTagName('head')[0];
  5825. var script = document.createElement('script');
  5826. script.type = 'text/javascript';
  5827. script.src = scriptUrl;
  5828. var self = this;
  5829. script.onload = function () {
  5830. if (onSuccess) {
  5831. onSuccess();
  5832. }
  5833. };
  5834. script.onerror = function () {
  5835. if (onError) {
  5836. onError();
  5837. }
  5838. };
  5839. head.appendChild(script);
  5840. };
  5841. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5842. var reader = new FileReader();
  5843. reader.onload = function (e) {
  5844. //target doesn't have result from ts 1.3
  5845. callback(e.target['result']);
  5846. };
  5847. reader.onprogress = progressCallback;
  5848. reader.readAsDataURL(fileToLoad);
  5849. };
  5850. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5851. var reader = new FileReader();
  5852. reader.onerror = function (e) {
  5853. Tools.Log("Error while reading file: " + fileToLoad.name);
  5854. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5855. };
  5856. reader.onload = function (e) {
  5857. //target doesn't have result from ts 1.3
  5858. callback(e.target['result']);
  5859. };
  5860. reader.onprogress = progressCallBack;
  5861. if (!useArrayBuffer) {
  5862. // Asynchronous read
  5863. reader.readAsText(fileToLoad);
  5864. }
  5865. else {
  5866. reader.readAsArrayBuffer(fileToLoad);
  5867. }
  5868. };
  5869. //returns a downloadable url to a file content.
  5870. Tools.FileAsURL = function (content) {
  5871. var fileBlob = new Blob([content]);
  5872. var url = window.URL || window.webkitURL;
  5873. var link = url.createObjectURL(fileBlob);
  5874. return link;
  5875. };
  5876. // Misc.
  5877. Tools.Format = function (value, decimals) {
  5878. if (decimals === void 0) { decimals = 2; }
  5879. return value.toFixed(decimals);
  5880. };
  5881. Tools.CheckExtends = function (v, min, max) {
  5882. if (v.x < min.x)
  5883. min.x = v.x;
  5884. if (v.y < min.y)
  5885. min.y = v.y;
  5886. if (v.z < min.z)
  5887. min.z = v.z;
  5888. if (v.x > max.x)
  5889. max.x = v.x;
  5890. if (v.y > max.y)
  5891. max.y = v.y;
  5892. if (v.z > max.z)
  5893. max.z = v.z;
  5894. };
  5895. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5896. for (var prop in source) {
  5897. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5898. continue;
  5899. }
  5900. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5901. continue;
  5902. }
  5903. var sourceValue = source[prop];
  5904. var typeOfSourceValue = typeof sourceValue;
  5905. if (typeOfSourceValue === "function") {
  5906. continue;
  5907. }
  5908. if (typeOfSourceValue === "object") {
  5909. if (sourceValue instanceof Array) {
  5910. destination[prop] = [];
  5911. if (sourceValue.length > 0) {
  5912. if (typeof sourceValue[0] == "object") {
  5913. for (var index = 0; index < sourceValue.length; index++) {
  5914. var clonedValue = cloneValue(sourceValue[index], destination);
  5915. if (destination[prop].indexOf(clonedValue) === -1) {
  5916. destination[prop].push(clonedValue);
  5917. }
  5918. }
  5919. }
  5920. else {
  5921. destination[prop] = sourceValue.slice(0);
  5922. }
  5923. }
  5924. }
  5925. else {
  5926. destination[prop] = cloneValue(sourceValue, destination);
  5927. }
  5928. }
  5929. else {
  5930. destination[prop] = sourceValue;
  5931. }
  5932. }
  5933. };
  5934. Tools.IsEmpty = function (obj) {
  5935. for (var i in obj) {
  5936. return false;
  5937. }
  5938. return true;
  5939. };
  5940. Tools.RegisterTopRootEvents = function (events) {
  5941. for (var index = 0; index < events.length; index++) {
  5942. var event = events[index];
  5943. window.addEventListener(event.name, event.handler, false);
  5944. try {
  5945. if (window.parent) {
  5946. window.parent.addEventListener(event.name, event.handler, false);
  5947. }
  5948. }
  5949. catch (e) {
  5950. // Silently fails...
  5951. }
  5952. }
  5953. };
  5954. Tools.UnregisterTopRootEvents = function (events) {
  5955. for (var index = 0; index < events.length; index++) {
  5956. var event = events[index];
  5957. window.removeEventListener(event.name, event.handler);
  5958. try {
  5959. if (window.parent) {
  5960. window.parent.removeEventListener(event.name, event.handler);
  5961. }
  5962. }
  5963. catch (e) {
  5964. // Silently fails...
  5965. }
  5966. }
  5967. };
  5968. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5969. if (mimeType === void 0) { mimeType = "image/png"; }
  5970. // Read the contents of the framebuffer
  5971. var numberOfChannelsByLine = width * 4;
  5972. var halfHeight = height / 2;
  5973. //Reading datas from WebGL
  5974. var data = engine.readPixels(0, 0, width, height);
  5975. //To flip image on Y axis.
  5976. for (var i = 0; i < halfHeight; i++) {
  5977. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5978. var currentCell = j + i * numberOfChannelsByLine;
  5979. var targetLine = height - i - 1;
  5980. var targetCell = j + targetLine * numberOfChannelsByLine;
  5981. var temp = data[currentCell];
  5982. data[currentCell] = data[targetCell];
  5983. data[targetCell] = temp;
  5984. }
  5985. }
  5986. // Create a 2D canvas to store the result
  5987. if (!screenshotCanvas) {
  5988. screenshotCanvas = document.createElement('canvas');
  5989. }
  5990. screenshotCanvas.width = width;
  5991. screenshotCanvas.height = height;
  5992. var context = screenshotCanvas.getContext('2d');
  5993. // Copy the pixels to a 2D canvas
  5994. var imageData = context.createImageData(width, height);
  5995. var castData = (imageData.data);
  5996. castData.set(data);
  5997. context.putImageData(imageData, 0, 0);
  5998. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5999. };
  6000. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6001. if (mimeType === void 0) { mimeType = "image/png"; }
  6002. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6003. if (successCallback) {
  6004. successCallback(base64Image);
  6005. }
  6006. else {
  6007. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6008. if (("download" in document.createElement("a"))) {
  6009. var a = window.document.createElement("a");
  6010. a.href = base64Image;
  6011. var date = new Date();
  6012. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6013. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6014. window.document.body.appendChild(a);
  6015. a.addEventListener("click", function () {
  6016. a.parentElement.removeChild(a);
  6017. });
  6018. a.click();
  6019. //Or opening a new tab with the image if it is not possible to automatically start download.
  6020. }
  6021. else {
  6022. var newWindow = window.open("");
  6023. var img = newWindow.document.createElement("img");
  6024. img.src = base64Image;
  6025. newWindow.document.body.appendChild(img);
  6026. }
  6027. }
  6028. };
  6029. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6030. if (mimeType === void 0) { mimeType = "image/png"; }
  6031. var width;
  6032. var height;
  6033. // If a precision value is specified
  6034. if (size.precision) {
  6035. width = Math.round(engine.getRenderWidth() * size.precision);
  6036. height = Math.round(width / engine.getAspectRatio(camera));
  6037. }
  6038. else if (size.width && size.height) {
  6039. width = size.width;
  6040. height = size.height;
  6041. }
  6042. else if (size.width && !size.height) {
  6043. width = size.width;
  6044. height = Math.round(width / engine.getAspectRatio(camera));
  6045. }
  6046. else if (size.height && !size.width) {
  6047. height = size.height;
  6048. width = Math.round(height * engine.getAspectRatio(camera));
  6049. }
  6050. else if (!isNaN(size)) {
  6051. height = size;
  6052. width = size;
  6053. }
  6054. else {
  6055. Tools.Error("Invalid 'size' parameter !");
  6056. return;
  6057. }
  6058. if (!screenshotCanvas) {
  6059. screenshotCanvas = document.createElement('canvas');
  6060. }
  6061. screenshotCanvas.width = width;
  6062. screenshotCanvas.height = height;
  6063. var renderContext = screenshotCanvas.getContext("2d");
  6064. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6065. var newWidth = width;
  6066. var newHeight = newWidth / ratio;
  6067. if (newHeight > height) {
  6068. newHeight = height;
  6069. newWidth = newHeight * ratio;
  6070. }
  6071. var offsetX = Math.max(0, width - newWidth) / 2;
  6072. var offsetY = Math.max(0, height - newHeight) / 2;
  6073. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6074. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6075. };
  6076. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6077. if (mimeType === void 0) { mimeType = "image/png"; }
  6078. if (samples === void 0) { samples = 1; }
  6079. var width;
  6080. var height;
  6081. //If a precision value is specified
  6082. if (size.precision) {
  6083. width = Math.round(engine.getRenderWidth() * size.precision);
  6084. height = Math.round(width / engine.getAspectRatio(camera));
  6085. size = { width: width, height: height };
  6086. }
  6087. else if (size.width && size.height) {
  6088. width = size.width;
  6089. height = size.height;
  6090. }
  6091. else if (size.width && !size.height) {
  6092. width = size.width;
  6093. height = Math.round(width / engine.getAspectRatio(camera));
  6094. size = { width: width, height: height };
  6095. }
  6096. else if (size.height && !size.width) {
  6097. height = size.height;
  6098. width = Math.round(height * engine.getAspectRatio(camera));
  6099. size = { width: width, height: height };
  6100. }
  6101. else if (!isNaN(size)) {
  6102. height = size;
  6103. width = size;
  6104. }
  6105. else {
  6106. Tools.Error("Invalid 'size' parameter !");
  6107. return;
  6108. }
  6109. var scene = camera.getScene();
  6110. var previousCamera = null;
  6111. if (scene.activeCamera !== camera) {
  6112. previousCamera = scene.activeCamera;
  6113. scene.activeCamera = camera;
  6114. }
  6115. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6116. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6117. texture.renderList = null;
  6118. texture.samples = samples;
  6119. texture.onAfterRenderObservable.add(function () {
  6120. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6121. });
  6122. scene.incrementRenderId();
  6123. scene.resetCachedMaterial();
  6124. texture.render(true);
  6125. texture.dispose();
  6126. if (previousCamera) {
  6127. scene.activeCamera = previousCamera;
  6128. }
  6129. camera.getProjectionMatrix(true); // Force cache refresh;
  6130. };
  6131. // XHR response validator for local file scenario
  6132. Tools.ValidateXHRData = function (xhr, dataType) {
  6133. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6134. if (dataType === void 0) { dataType = 7; }
  6135. try {
  6136. if (dataType & 1) {
  6137. if (xhr.responseText && xhr.responseText.length > 0) {
  6138. return true;
  6139. }
  6140. else if (dataType === 1) {
  6141. return false;
  6142. }
  6143. }
  6144. if (dataType & 2) {
  6145. // Check header width and height since there is no "TGA" magic number
  6146. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6147. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6148. return true;
  6149. }
  6150. else if (dataType === 2) {
  6151. return false;
  6152. }
  6153. }
  6154. if (dataType & 4) {
  6155. // Check for the "DDS" magic number
  6156. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6157. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6158. return true;
  6159. }
  6160. else {
  6161. return false;
  6162. }
  6163. }
  6164. }
  6165. catch (e) {
  6166. // Global protection
  6167. }
  6168. return false;
  6169. };
  6170. /**
  6171. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6172. * Be aware Math.random() could cause collisions, but:
  6173. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6174. */
  6175. Tools.RandomId = function () {
  6176. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6177. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6178. return v.toString(16);
  6179. });
  6180. };
  6181. Object.defineProperty(Tools, "NoneLogLevel", {
  6182. get: function () {
  6183. return Tools._NoneLogLevel;
  6184. },
  6185. enumerable: true,
  6186. configurable: true
  6187. });
  6188. Object.defineProperty(Tools, "MessageLogLevel", {
  6189. get: function () {
  6190. return Tools._MessageLogLevel;
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. Object.defineProperty(Tools, "WarningLogLevel", {
  6196. get: function () {
  6197. return Tools._WarningLogLevel;
  6198. },
  6199. enumerable: true,
  6200. configurable: true
  6201. });
  6202. Object.defineProperty(Tools, "ErrorLogLevel", {
  6203. get: function () {
  6204. return Tools._ErrorLogLevel;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(Tools, "AllLogLevel", {
  6210. get: function () {
  6211. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Tools._AddLogEntry = function (entry) {
  6217. Tools._LogCache = entry + Tools._LogCache;
  6218. if (Tools.OnNewCacheEntry) {
  6219. Tools.OnNewCacheEntry(entry);
  6220. }
  6221. };
  6222. Tools._FormatMessage = function (message) {
  6223. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6224. var date = new Date();
  6225. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6226. };
  6227. Tools._LogDisabled = function (message) {
  6228. // nothing to do
  6229. };
  6230. Tools._LogEnabled = function (message) {
  6231. var formattedMessage = Tools._FormatMessage(message);
  6232. console.log("BJS - " + formattedMessage);
  6233. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6234. Tools._AddLogEntry(entry);
  6235. };
  6236. Tools._WarnDisabled = function (message) {
  6237. // nothing to do
  6238. };
  6239. Tools._WarnEnabled = function (message) {
  6240. var formattedMessage = Tools._FormatMessage(message);
  6241. console.warn("BJS - " + formattedMessage);
  6242. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6243. Tools._AddLogEntry(entry);
  6244. };
  6245. Tools._ErrorDisabled = function (message) {
  6246. // nothing to do
  6247. };
  6248. Tools._ErrorEnabled = function (message) {
  6249. Tools.errorsCount++;
  6250. var formattedMessage = Tools._FormatMessage(message);
  6251. console.error("BJS - " + formattedMessage);
  6252. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6253. Tools._AddLogEntry(entry);
  6254. };
  6255. Object.defineProperty(Tools, "LogCache", {
  6256. get: function () {
  6257. return Tools._LogCache;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Tools.ClearLogCache = function () {
  6263. Tools._LogCache = "";
  6264. Tools.errorsCount = 0;
  6265. };
  6266. Object.defineProperty(Tools, "LogLevels", {
  6267. set: function (level) {
  6268. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6269. Tools.Log = Tools._LogEnabled;
  6270. }
  6271. else {
  6272. Tools.Log = Tools._LogDisabled;
  6273. }
  6274. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6275. Tools.Warn = Tools._WarnEnabled;
  6276. }
  6277. else {
  6278. Tools.Warn = Tools._WarnDisabled;
  6279. }
  6280. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6281. Tools.Error = Tools._ErrorEnabled;
  6282. }
  6283. else {
  6284. Tools.Error = Tools._ErrorDisabled;
  6285. }
  6286. },
  6287. enumerable: true,
  6288. configurable: true
  6289. });
  6290. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6291. get: function () {
  6292. return Tools._PerformanceNoneLogLevel;
  6293. },
  6294. enumerable: true,
  6295. configurable: true
  6296. });
  6297. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6298. get: function () {
  6299. return Tools._PerformanceUserMarkLogLevel;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6305. get: function () {
  6306. return Tools._PerformanceConsoleLogLevel;
  6307. },
  6308. enumerable: true,
  6309. configurable: true
  6310. });
  6311. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6312. set: function (level) {
  6313. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6314. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6315. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6316. return;
  6317. }
  6318. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6319. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6320. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6321. return;
  6322. }
  6323. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6324. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6325. },
  6326. enumerable: true,
  6327. configurable: true
  6328. });
  6329. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6332. };
  6333. Tools._StartUserMark = function (counterName, condition) {
  6334. if (condition === void 0) { condition = true; }
  6335. if (!condition || !Tools._performance.mark) {
  6336. return;
  6337. }
  6338. Tools._performance.mark(counterName + "-Begin");
  6339. };
  6340. Tools._EndUserMark = function (counterName, condition) {
  6341. if (condition === void 0) { condition = true; }
  6342. if (!condition || !Tools._performance.mark) {
  6343. return;
  6344. }
  6345. Tools._performance.mark(counterName + "-End");
  6346. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6347. };
  6348. Tools._StartPerformanceConsole = function (counterName, condition) {
  6349. if (condition === void 0) { condition = true; }
  6350. if (!condition) {
  6351. return;
  6352. }
  6353. Tools._StartUserMark(counterName, condition);
  6354. if (console.time) {
  6355. console.time(counterName);
  6356. }
  6357. };
  6358. Tools._EndPerformanceConsole = function (counterName, condition) {
  6359. if (condition === void 0) { condition = true; }
  6360. if (!condition) {
  6361. return;
  6362. }
  6363. Tools._EndUserMark(counterName, condition);
  6364. if (console.time) {
  6365. console.timeEnd(counterName);
  6366. }
  6367. };
  6368. Object.defineProperty(Tools, "Now", {
  6369. get: function () {
  6370. if (window.performance && window.performance.now) {
  6371. return window.performance.now();
  6372. }
  6373. return new Date().getTime();
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. /**
  6379. * This method will return the name of the class used to create the instance of the given object.
  6380. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6381. * @param object the object to get the class name from
  6382. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6383. */
  6384. Tools.GetClassName = function (object, isType) {
  6385. if (isType === void 0) { isType = false; }
  6386. var name = null;
  6387. if (!isType && object.getClassName) {
  6388. name = object.getClassName();
  6389. }
  6390. else {
  6391. if (object instanceof Object) {
  6392. var classObj = isType ? object : Object.getPrototypeOf(object);
  6393. name = classObj.constructor["__bjsclassName__"];
  6394. }
  6395. if (!name) {
  6396. name = typeof object;
  6397. }
  6398. }
  6399. return name;
  6400. };
  6401. Tools.first = function (array, predicate) {
  6402. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6403. var el = array_1[_i];
  6404. if (predicate(el)) {
  6405. return el;
  6406. }
  6407. }
  6408. };
  6409. /**
  6410. * This method will return the name of the full name of the class, including its owning module (if any).
  6411. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6412. * @param object the object to get the class name from
  6413. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6414. */
  6415. Tools.getFullClassName = function (object, isType) {
  6416. if (isType === void 0) { isType = false; }
  6417. var className = null;
  6418. var moduleName = null;
  6419. if (!isType && object.getClassName) {
  6420. className = object.getClassName();
  6421. }
  6422. else {
  6423. if (object instanceof Object) {
  6424. var classObj = isType ? object : Object.getPrototypeOf(object);
  6425. className = classObj.constructor["__bjsclassName__"];
  6426. moduleName = classObj.constructor["__bjsmoduleName__"];
  6427. }
  6428. if (!className) {
  6429. className = typeof object;
  6430. }
  6431. }
  6432. if (!className) {
  6433. return null;
  6434. }
  6435. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6436. };
  6437. /**
  6438. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6439. * @param array
  6440. */
  6441. Tools.arrayOrStringFeeder = function (array) {
  6442. return function (index) {
  6443. if (index >= array.length) {
  6444. return null;
  6445. }
  6446. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6447. if (val && val.getHashCode) {
  6448. val = val.getHashCode();
  6449. }
  6450. if (typeof val === "string") {
  6451. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6452. }
  6453. return val;
  6454. };
  6455. };
  6456. /**
  6457. * Compute the hashCode of a stream of number
  6458. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6459. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6460. * @return the hash code computed
  6461. */
  6462. Tools.hashCodeFromStream = function (feeder) {
  6463. // Based from here: http://stackoverflow.com/a/7616484/802124
  6464. var hash = 0;
  6465. var index = 0;
  6466. var chr = feeder(index++);
  6467. while (chr != null) {
  6468. hash = ((hash << 5) - hash) + chr;
  6469. hash |= 0; // Convert to 32bit integer
  6470. chr = feeder(index++);
  6471. }
  6472. return hash;
  6473. };
  6474. Tools.BaseUrl = "";
  6475. Tools.CorsBehavior = "anonymous";
  6476. Tools.UseFallbackTexture = true;
  6477. // Used in case of a texture loading problem
  6478. Tools.fallbackTexture = "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";
  6479. Tools.PreprocessUrl = function (url) {
  6480. return url;
  6481. };
  6482. // Logs
  6483. Tools._NoneLogLevel = 0;
  6484. Tools._MessageLogLevel = 1;
  6485. Tools._WarningLogLevel = 2;
  6486. Tools._ErrorLogLevel = 4;
  6487. Tools._LogCache = "";
  6488. Tools.errorsCount = 0;
  6489. Tools.Log = Tools._LogEnabled;
  6490. Tools.Warn = Tools._WarnEnabled;
  6491. Tools.Error = Tools._ErrorEnabled;
  6492. // Performances
  6493. Tools._PerformanceNoneLogLevel = 0;
  6494. Tools._PerformanceUserMarkLogLevel = 1;
  6495. Tools._PerformanceConsoleLogLevel = 2;
  6496. Tools._performance = window.performance;
  6497. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6498. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6499. return Tools;
  6500. }());
  6501. BABYLON.Tools = Tools;
  6502. /**
  6503. * This class is used to track a performance counter which is number based.
  6504. * The user has access to many properties which give statistics of different nature
  6505. *
  6506. * The implementer can track two kinds of Performance Counter: time and count
  6507. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6508. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6509. */
  6510. var PerfCounter = (function () {
  6511. function PerfCounter() {
  6512. this._startMonitoringTime = 0;
  6513. this._min = 0;
  6514. this._max = 0;
  6515. this._average = 0;
  6516. this._lastSecAverage = 0;
  6517. this._current = 0;
  6518. this._totalValueCount = 0;
  6519. this._totalAccumulated = 0;
  6520. this._lastSecAccumulated = 0;
  6521. this._lastSecTime = 0;
  6522. this._lastSecValueCount = 0;
  6523. }
  6524. Object.defineProperty(PerfCounter.prototype, "min", {
  6525. /**
  6526. * Returns the smallest value ever
  6527. */
  6528. get: function () {
  6529. return this._min;
  6530. },
  6531. enumerable: true,
  6532. configurable: true
  6533. });
  6534. Object.defineProperty(PerfCounter.prototype, "max", {
  6535. /**
  6536. * Returns the biggest value ever
  6537. */
  6538. get: function () {
  6539. return this._max;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(PerfCounter.prototype, "average", {
  6545. /**
  6546. * Returns the average value since the performance counter is running
  6547. */
  6548. get: function () {
  6549. return this._average;
  6550. },
  6551. enumerable: true,
  6552. configurable: true
  6553. });
  6554. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6555. /**
  6556. * Returns the average value of the last second the counter was monitored
  6557. */
  6558. get: function () {
  6559. return this._lastSecAverage;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. Object.defineProperty(PerfCounter.prototype, "current", {
  6565. /**
  6566. * Returns the current value
  6567. */
  6568. get: function () {
  6569. return this._current;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Object.defineProperty(PerfCounter.prototype, "total", {
  6575. get: function () {
  6576. return this._totalAccumulated;
  6577. },
  6578. enumerable: true,
  6579. configurable: true
  6580. });
  6581. /**
  6582. * Call this method to start monitoring a new frame.
  6583. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6584. */
  6585. PerfCounter.prototype.fetchNewFrame = function () {
  6586. this._totalValueCount++;
  6587. this._current = 0;
  6588. this._lastSecValueCount++;
  6589. };
  6590. /**
  6591. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6592. * @param newCount the count value to add to the monitored count
  6593. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6594. */
  6595. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6596. if (!PerfCounter.Enabled) {
  6597. return;
  6598. }
  6599. this._current += newCount;
  6600. if (fetchResult) {
  6601. this._fetchResult();
  6602. }
  6603. };
  6604. /**
  6605. * Start monitoring this performance counter
  6606. */
  6607. PerfCounter.prototype.beginMonitoring = function () {
  6608. if (!PerfCounter.Enabled) {
  6609. return;
  6610. }
  6611. this._startMonitoringTime = Tools.Now;
  6612. };
  6613. /**
  6614. * Compute the time lapsed since the previous beginMonitoring() call.
  6615. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6616. */
  6617. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6618. if (newFrame === void 0) { newFrame = true; }
  6619. if (!PerfCounter.Enabled) {
  6620. return;
  6621. }
  6622. if (newFrame) {
  6623. this.fetchNewFrame();
  6624. }
  6625. var currentTime = Tools.Now;
  6626. this._current = currentTime - this._startMonitoringTime;
  6627. if (newFrame) {
  6628. this._fetchResult();
  6629. }
  6630. };
  6631. PerfCounter.prototype._fetchResult = function () {
  6632. this._totalAccumulated += this._current;
  6633. this._lastSecAccumulated += this._current;
  6634. // Min/Max update
  6635. this._min = Math.min(this._min, this._current);
  6636. this._max = Math.max(this._max, this._current);
  6637. this._average = this._totalAccumulated / this._totalValueCount;
  6638. // Reset last sec?
  6639. var now = Tools.Now;
  6640. if ((now - this._lastSecTime) > 1000) {
  6641. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6642. this._lastSecTime = now;
  6643. this._lastSecAccumulated = 0;
  6644. this._lastSecValueCount = 0;
  6645. }
  6646. };
  6647. PerfCounter.Enabled = true;
  6648. return PerfCounter;
  6649. }());
  6650. BABYLON.PerfCounter = PerfCounter;
  6651. /**
  6652. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6653. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6654. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6655. * @param name The name of the class, case should be preserved
  6656. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6657. */
  6658. function className(name, module) {
  6659. return function (target) {
  6660. target["__bjsclassName__"] = name;
  6661. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6662. };
  6663. }
  6664. BABYLON.className = className;
  6665. /**
  6666. * An implementation of a loop for asynchronous functions.
  6667. */
  6668. var AsyncLoop = (function () {
  6669. /**
  6670. * Constroctor.
  6671. * @param iterations the number of iterations.
  6672. * @param _fn the function to run each iteration
  6673. * @param _successCallback the callback that will be called upon succesful execution
  6674. * @param offset starting offset.
  6675. */
  6676. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6677. if (offset === void 0) { offset = 0; }
  6678. this.iterations = iterations;
  6679. this._fn = _fn;
  6680. this._successCallback = _successCallback;
  6681. this.index = offset - 1;
  6682. this._done = false;
  6683. }
  6684. /**
  6685. * Execute the next iteration. Must be called after the last iteration was finished.
  6686. */
  6687. AsyncLoop.prototype.executeNext = function () {
  6688. if (!this._done) {
  6689. if (this.index + 1 < this.iterations) {
  6690. ++this.index;
  6691. this._fn(this);
  6692. }
  6693. else {
  6694. this.breakLoop();
  6695. }
  6696. }
  6697. };
  6698. /**
  6699. * Break the loop and run the success callback.
  6700. */
  6701. AsyncLoop.prototype.breakLoop = function () {
  6702. this._done = true;
  6703. this._successCallback();
  6704. };
  6705. /**
  6706. * Helper function
  6707. */
  6708. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6709. if (offset === void 0) { offset = 0; }
  6710. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6711. loop.executeNext();
  6712. return loop;
  6713. };
  6714. /**
  6715. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6716. * @param iterations total number of iterations
  6717. * @param syncedIterations number of synchronous iterations in each async iteration.
  6718. * @param fn the function to call each iteration.
  6719. * @param callback a success call back that will be called when iterating stops.
  6720. * @param breakFunction a break condition (optional)
  6721. * @param timeout timeout settings for the setTimeout function. default - 0.
  6722. * @constructor
  6723. */
  6724. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6725. if (timeout === void 0) { timeout = 0; }
  6726. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6727. if (breakFunction && breakFunction())
  6728. loop.breakLoop();
  6729. else {
  6730. setTimeout(function () {
  6731. for (var i = 0; i < syncedIterations; ++i) {
  6732. var iteration = (loop.index * syncedIterations) + i;
  6733. if (iteration >= iterations)
  6734. break;
  6735. fn(iteration);
  6736. if (breakFunction && breakFunction()) {
  6737. loop.breakLoop();
  6738. break;
  6739. }
  6740. }
  6741. loop.executeNext();
  6742. }, timeout);
  6743. }
  6744. }, callback);
  6745. };
  6746. return AsyncLoop;
  6747. }());
  6748. BABYLON.AsyncLoop = AsyncLoop;
  6749. })(BABYLON || (BABYLON = {}));
  6750. //# sourceMappingURL=babylon.tools.js.map
  6751. var BABYLON;
  6752. (function (BABYLON) {
  6753. var Internals;
  6754. (function (Internals) {
  6755. var _AlphaState = (function () {
  6756. /**
  6757. * Initializes the state.
  6758. */
  6759. function _AlphaState() {
  6760. this._isAlphaBlendDirty = false;
  6761. this._isBlendFunctionParametersDirty = false;
  6762. this._isBlendEquationParametersDirty = false;
  6763. this._isBlendConstantsDirty = false;
  6764. this._alphaBlend = false;
  6765. this._blendFunctionParameters = new Array(4);
  6766. this._blendEquationParameters = new Array(2);
  6767. this._blendConstants = new Array(4);
  6768. this.reset();
  6769. }
  6770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6771. get: function () {
  6772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6773. },
  6774. enumerable: true,
  6775. configurable: true
  6776. });
  6777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6778. get: function () {
  6779. return this._alphaBlend;
  6780. },
  6781. set: function (value) {
  6782. if (this._alphaBlend === value) {
  6783. return;
  6784. }
  6785. this._alphaBlend = value;
  6786. this._isAlphaBlendDirty = true;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6792. if (this._blendConstants[0] === r &&
  6793. this._blendConstants[1] === g &&
  6794. this._blendConstants[2] === b &&
  6795. this._blendConstants[3] === a) {
  6796. return;
  6797. }
  6798. this._blendConstants[0] = r;
  6799. this._blendConstants[1] = g;
  6800. this._blendConstants[2] = b;
  6801. this._blendConstants[3] = a;
  6802. this._isBlendConstantsDirty = true;
  6803. };
  6804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6805. if (this._blendFunctionParameters[0] === value0 &&
  6806. this._blendFunctionParameters[1] === value1 &&
  6807. this._blendFunctionParameters[2] === value2 &&
  6808. this._blendFunctionParameters[3] === value3) {
  6809. return;
  6810. }
  6811. this._blendFunctionParameters[0] = value0;
  6812. this._blendFunctionParameters[1] = value1;
  6813. this._blendFunctionParameters[2] = value2;
  6814. this._blendFunctionParameters[3] = value3;
  6815. this._isBlendFunctionParametersDirty = true;
  6816. };
  6817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6818. if (this._blendEquationParameters[0] === rgb &&
  6819. this._blendEquationParameters[1] === alpha) {
  6820. return;
  6821. }
  6822. this._blendEquationParameters[0] = rgb;
  6823. this._blendEquationParameters[1] = alpha;
  6824. this._isBlendEquationParametersDirty = true;
  6825. };
  6826. _AlphaState.prototype.reset = function () {
  6827. this._alphaBlend = false;
  6828. this._blendFunctionParameters[0] = null;
  6829. this._blendFunctionParameters[1] = null;
  6830. this._blendFunctionParameters[2] = null;
  6831. this._blendFunctionParameters[3] = null;
  6832. this._blendEquationParameters[0] = null;
  6833. this._blendEquationParameters[1] = null;
  6834. this._blendConstants[0] = null;
  6835. this._blendConstants[1] = null;
  6836. this._blendConstants[2] = null;
  6837. this._blendConstants[3] = null;
  6838. this._isAlphaBlendDirty = true;
  6839. this._isBlendFunctionParametersDirty = false;
  6840. this._isBlendEquationParametersDirty = false;
  6841. this._isBlendConstantsDirty = false;
  6842. };
  6843. _AlphaState.prototype.apply = function (gl) {
  6844. if (!this.isDirty) {
  6845. return;
  6846. }
  6847. // Alpha blend
  6848. if (this._isAlphaBlendDirty) {
  6849. if (this._alphaBlend) {
  6850. gl.enable(gl.BLEND);
  6851. }
  6852. else {
  6853. gl.disable(gl.BLEND);
  6854. }
  6855. this._isAlphaBlendDirty = false;
  6856. }
  6857. // Alpha function
  6858. if (this._isBlendFunctionParametersDirty) {
  6859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6860. this._isBlendFunctionParametersDirty = false;
  6861. }
  6862. // Alpha equation
  6863. if (this._isBlendEquationParametersDirty) {
  6864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6865. this._isBlendEquationParametersDirty = false;
  6866. }
  6867. // Constants
  6868. if (this._isBlendConstantsDirty) {
  6869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6870. this._isBlendConstantsDirty = false;
  6871. }
  6872. };
  6873. return _AlphaState;
  6874. }());
  6875. Internals._AlphaState = _AlphaState;
  6876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. var Internals;
  6882. (function (Internals) {
  6883. var _DepthCullingState = (function () {
  6884. /**
  6885. * Initializes the state.
  6886. */
  6887. function _DepthCullingState() {
  6888. this._isDepthTestDirty = false;
  6889. this._isDepthMaskDirty = false;
  6890. this._isDepthFuncDirty = false;
  6891. this._isCullFaceDirty = false;
  6892. this._isCullDirty = false;
  6893. this._isZOffsetDirty = false;
  6894. this.reset();
  6895. }
  6896. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6897. get: function () {
  6898. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6899. },
  6900. enumerable: true,
  6901. configurable: true
  6902. });
  6903. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6904. get: function () {
  6905. return this._zOffset;
  6906. },
  6907. set: function (value) {
  6908. if (this._zOffset === value) {
  6909. return;
  6910. }
  6911. this._zOffset = value;
  6912. this._isZOffsetDirty = true;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6918. get: function () {
  6919. return this._cullFace;
  6920. },
  6921. set: function (value) {
  6922. if (this._cullFace === value) {
  6923. return;
  6924. }
  6925. this._cullFace = value;
  6926. this._isCullFaceDirty = true;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6932. get: function () {
  6933. return this._cull;
  6934. },
  6935. set: function (value) {
  6936. if (this._cull === value) {
  6937. return;
  6938. }
  6939. this._cull = value;
  6940. this._isCullDirty = true;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6946. get: function () {
  6947. return this._depthFunc;
  6948. },
  6949. set: function (value) {
  6950. if (this._depthFunc === value) {
  6951. return;
  6952. }
  6953. this._depthFunc = value;
  6954. this._isDepthFuncDirty = true;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6960. get: function () {
  6961. return this._depthMask;
  6962. },
  6963. set: function (value) {
  6964. if (this._depthMask === value) {
  6965. return;
  6966. }
  6967. this._depthMask = value;
  6968. this._isDepthMaskDirty = true;
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6974. get: function () {
  6975. return this._depthTest;
  6976. },
  6977. set: function (value) {
  6978. if (this._depthTest === value) {
  6979. return;
  6980. }
  6981. this._depthTest = value;
  6982. this._isDepthTestDirty = true;
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. _DepthCullingState.prototype.reset = function () {
  6988. this._depthMask = true;
  6989. this._depthTest = true;
  6990. this._depthFunc = null;
  6991. this._cullFace = null;
  6992. this._cull = null;
  6993. this._zOffset = 0;
  6994. this._isDepthTestDirty = true;
  6995. this._isDepthMaskDirty = true;
  6996. this._isDepthFuncDirty = false;
  6997. this._isCullFaceDirty = false;
  6998. this._isCullDirty = false;
  6999. this._isZOffsetDirty = false;
  7000. };
  7001. _DepthCullingState.prototype.apply = function (gl) {
  7002. if (!this.isDirty) {
  7003. return;
  7004. }
  7005. // Cull
  7006. if (this._isCullDirty) {
  7007. if (this.cull) {
  7008. gl.enable(gl.CULL_FACE);
  7009. }
  7010. else {
  7011. gl.disable(gl.CULL_FACE);
  7012. }
  7013. this._isCullDirty = false;
  7014. }
  7015. // Cull face
  7016. if (this._isCullFaceDirty) {
  7017. gl.cullFace(this.cullFace);
  7018. this._isCullFaceDirty = false;
  7019. }
  7020. // Depth mask
  7021. if (this._isDepthMaskDirty) {
  7022. gl.depthMask(this.depthMask);
  7023. this._isDepthMaskDirty = false;
  7024. }
  7025. // Depth test
  7026. if (this._isDepthTestDirty) {
  7027. if (this.depthTest) {
  7028. gl.enable(gl.DEPTH_TEST);
  7029. }
  7030. else {
  7031. gl.disable(gl.DEPTH_TEST);
  7032. }
  7033. this._isDepthTestDirty = false;
  7034. }
  7035. // Depth func
  7036. if (this._isDepthFuncDirty) {
  7037. gl.depthFunc(this.depthFunc);
  7038. this._isDepthFuncDirty = false;
  7039. }
  7040. // zOffset
  7041. if (this._isZOffsetDirty) {
  7042. if (this.zOffset) {
  7043. gl.enable(gl.POLYGON_OFFSET_FILL);
  7044. gl.polygonOffset(this.zOffset, 0);
  7045. }
  7046. else {
  7047. gl.disable(gl.POLYGON_OFFSET_FILL);
  7048. }
  7049. this._isZOffsetDirty = false;
  7050. }
  7051. };
  7052. return _DepthCullingState;
  7053. }());
  7054. Internals._DepthCullingState = _DepthCullingState;
  7055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7056. })(BABYLON || (BABYLON = {}));
  7057. //# sourceMappingURL=babylon.depthCullingState.js.map
  7058. var BABYLON;
  7059. (function (BABYLON) {
  7060. var Internals;
  7061. (function (Internals) {
  7062. var _StencilState = (function () {
  7063. function _StencilState() {
  7064. this._isStencilTestDirty = false;
  7065. this._isStencilMaskDirty = false;
  7066. this._isStencilFuncDirty = false;
  7067. this._isStencilOpDirty = false;
  7068. this.reset();
  7069. }
  7070. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7071. get: function () {
  7072. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7078. get: function () {
  7079. return this._stencilFunc;
  7080. },
  7081. set: function (value) {
  7082. if (this._stencilFunc === value) {
  7083. return;
  7084. }
  7085. this._stencilFunc = value;
  7086. this._isStencilFuncDirty = true;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7092. get: function () {
  7093. return this._stencilFuncRef;
  7094. },
  7095. set: function (value) {
  7096. if (this._stencilFuncRef === value) {
  7097. return;
  7098. }
  7099. this._stencilFuncRef = value;
  7100. this._isStencilFuncDirty = true;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7106. get: function () {
  7107. return this._stencilFuncMask;
  7108. },
  7109. set: function (value) {
  7110. if (this._stencilFuncMask === value) {
  7111. return;
  7112. }
  7113. this._stencilFuncMask = value;
  7114. this._isStencilFuncDirty = true;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7120. get: function () {
  7121. return this._stencilOpStencilFail;
  7122. },
  7123. set: function (value) {
  7124. if (this._stencilOpStencilFail === value) {
  7125. return;
  7126. }
  7127. this._stencilOpStencilFail = value;
  7128. this._isStencilOpDirty = true;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7134. get: function () {
  7135. return this._stencilOpDepthFail;
  7136. },
  7137. set: function (value) {
  7138. if (this._stencilOpDepthFail === value) {
  7139. return;
  7140. }
  7141. this._stencilOpDepthFail = value;
  7142. this._isStencilOpDirty = true;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7148. get: function () {
  7149. return this._stencilOpStencilDepthPass;
  7150. },
  7151. set: function (value) {
  7152. if (this._stencilOpStencilDepthPass === value) {
  7153. return;
  7154. }
  7155. this._stencilOpStencilDepthPass = value;
  7156. this._isStencilOpDirty = true;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7162. get: function () {
  7163. return this._stencilMask;
  7164. },
  7165. set: function (value) {
  7166. if (this._stencilMask === value) {
  7167. return;
  7168. }
  7169. this._stencilMask = value;
  7170. this._isStencilMaskDirty = true;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7176. get: function () {
  7177. return this._stencilTest;
  7178. },
  7179. set: function (value) {
  7180. if (this._stencilTest === value) {
  7181. return;
  7182. }
  7183. this._stencilTest = value;
  7184. this._isStencilTestDirty = true;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. _StencilState.prototype.reset = function () {
  7190. this._stencilTest = false;
  7191. this._stencilMask = 0xFF;
  7192. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7193. this._stencilFuncRef = 1;
  7194. this._stencilFuncMask = 0xFF;
  7195. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7196. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7197. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7198. this._isStencilTestDirty = true;
  7199. this._isStencilMaskDirty = true;
  7200. this._isStencilFuncDirty = true;
  7201. this._isStencilOpDirty = true;
  7202. };
  7203. _StencilState.prototype.apply = function (gl) {
  7204. if (!this.isDirty) {
  7205. return;
  7206. }
  7207. // Stencil test
  7208. if (this._isStencilTestDirty) {
  7209. if (this.stencilTest) {
  7210. gl.enable(gl.STENCIL_TEST);
  7211. }
  7212. else {
  7213. gl.disable(gl.STENCIL_TEST);
  7214. }
  7215. this._isStencilTestDirty = false;
  7216. }
  7217. // Stencil mask
  7218. if (this._isStencilMaskDirty) {
  7219. gl.stencilMask(this.stencilMask);
  7220. this._isStencilMaskDirty = false;
  7221. }
  7222. // Stencil func
  7223. if (this._isStencilFuncDirty) {
  7224. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7225. this._isStencilFuncDirty = false;
  7226. }
  7227. // Stencil op
  7228. if (this._isStencilOpDirty) {
  7229. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7230. this._isStencilOpDirty = false;
  7231. }
  7232. };
  7233. return _StencilState;
  7234. }());
  7235. Internals._StencilState = _StencilState;
  7236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7237. })(BABYLON || (BABYLON = {}));
  7238. //# sourceMappingURL=babylon.stencilState.js.map
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7242. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7243. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7244. gl.compileShader(shader);
  7245. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7246. throw new Error(gl.getShaderInfoLog(shader));
  7247. }
  7248. return shader;
  7249. };
  7250. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7251. var magFilter = gl.NEAREST;
  7252. var minFilter = gl.NEAREST;
  7253. switch (samplingMode) {
  7254. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7255. magFilter = gl.LINEAR;
  7256. if (generateMipMaps) {
  7257. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7258. }
  7259. else {
  7260. minFilter = gl.LINEAR;
  7261. }
  7262. break;
  7263. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7264. magFilter = gl.LINEAR;
  7265. if (generateMipMaps) {
  7266. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7267. }
  7268. else {
  7269. minFilter = gl.LINEAR;
  7270. }
  7271. break;
  7272. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7273. magFilter = gl.NEAREST;
  7274. if (generateMipMaps) {
  7275. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7276. }
  7277. else {
  7278. minFilter = gl.NEAREST;
  7279. }
  7280. break;
  7281. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7282. magFilter = gl.NEAREST;
  7283. if (generateMipMaps) {
  7284. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7285. }
  7286. else {
  7287. minFilter = gl.NEAREST;
  7288. }
  7289. break;
  7290. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7291. magFilter = gl.NEAREST;
  7292. if (generateMipMaps) {
  7293. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7294. }
  7295. else {
  7296. minFilter = gl.LINEAR;
  7297. }
  7298. break;
  7299. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7300. magFilter = gl.NEAREST;
  7301. if (generateMipMaps) {
  7302. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7303. }
  7304. else {
  7305. minFilter = gl.LINEAR;
  7306. }
  7307. break;
  7308. case BABYLON.Texture.NEAREST_LINEAR:
  7309. magFilter = gl.NEAREST;
  7310. minFilter = gl.LINEAR;
  7311. break;
  7312. case BABYLON.Texture.NEAREST_NEAREST:
  7313. magFilter = gl.NEAREST;
  7314. minFilter = gl.NEAREST;
  7315. break;
  7316. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7317. magFilter = gl.LINEAR;
  7318. if (generateMipMaps) {
  7319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7320. }
  7321. else {
  7322. minFilter = gl.NEAREST;
  7323. }
  7324. break;
  7325. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7326. magFilter = gl.LINEAR;
  7327. if (generateMipMaps) {
  7328. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7329. }
  7330. else {
  7331. minFilter = gl.NEAREST;
  7332. }
  7333. break;
  7334. case BABYLON.Texture.LINEAR_LINEAR:
  7335. magFilter = gl.LINEAR;
  7336. minFilter = gl.LINEAR;
  7337. break;
  7338. case BABYLON.Texture.LINEAR_NEAREST:
  7339. magFilter = gl.LINEAR;
  7340. minFilter = gl.NEAREST;
  7341. break;
  7342. }
  7343. return {
  7344. min: minFilter,
  7345. mag: magFilter
  7346. };
  7347. };
  7348. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7349. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7350. var img;
  7351. var onload = function () {
  7352. loadedImages[index] = img;
  7353. loadedImages._internalCount++;
  7354. if (scene) {
  7355. scene._removePendingData(img);
  7356. }
  7357. if (loadedImages._internalCount === 6) {
  7358. onfinish(loadedImages);
  7359. }
  7360. };
  7361. var onerror = function () {
  7362. if (scene) {
  7363. scene._removePendingData(img);
  7364. }
  7365. if (onErrorCallBack) {
  7366. onErrorCallBack();
  7367. }
  7368. };
  7369. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7370. if (scene) {
  7371. scene._addPendingData(img);
  7372. }
  7373. };
  7374. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7375. if (onError === void 0) { onError = null; }
  7376. var loadedImages = [];
  7377. loadedImages._internalCount = 0;
  7378. for (var index = 0; index < 6; index++) {
  7379. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7380. }
  7381. };
  7382. var BufferPointer = (function () {
  7383. function BufferPointer() {
  7384. }
  7385. return BufferPointer;
  7386. }());
  7387. var InstancingAttributeInfo = (function () {
  7388. function InstancingAttributeInfo() {
  7389. }
  7390. return InstancingAttributeInfo;
  7391. }());
  7392. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7393. /**
  7394. * Define options used to create a render target texture
  7395. */
  7396. var RenderTargetCreationOptions = (function () {
  7397. function RenderTargetCreationOptions() {
  7398. }
  7399. return RenderTargetCreationOptions;
  7400. }());
  7401. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7402. /**
  7403. * Regroup several parameters relative to the browser in use
  7404. */
  7405. var EngineCapabilities = (function () {
  7406. function EngineCapabilities() {
  7407. }
  7408. return EngineCapabilities;
  7409. }());
  7410. BABYLON.EngineCapabilities = EngineCapabilities;
  7411. /**
  7412. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7413. */
  7414. var Engine = (function () {
  7415. /**
  7416. * @constructor
  7417. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7418. * @param {boolean} [antialias] - enable antialias
  7419. * @param options - further options to be sent to the getContext function
  7420. */
  7421. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7422. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7423. var _this = this;
  7424. // Public members
  7425. this.forcePOTTextures = false;
  7426. this.isFullscreen = false;
  7427. this.isPointerLock = false;
  7428. this.cullBackFaces = true;
  7429. this.renderEvenInBackground = true;
  7430. this.preventCacheWipeBetweenFrames = false;
  7431. // To enable/disable IDB support and avoid XHR on .manifest
  7432. this.enableOfflineSupport = false;
  7433. this.scenes = new Array();
  7434. this.postProcesses = new Array();
  7435. // Observables
  7436. /**
  7437. * Observable event triggered each time the rendering canvas is resized
  7438. */
  7439. this.onResizeObservable = new BABYLON.Observable();
  7440. /**
  7441. * Observable event triggered each time the canvas lost focus
  7442. */
  7443. this.onCanvasBlurObservable = new BABYLON.Observable();
  7444. // Uniform buffers list
  7445. this._uniformBuffers = new Array();
  7446. this._windowIsBackground = false;
  7447. this._webGLVersion = 1.0;
  7448. this._badOS = false;
  7449. this._badDesktopOS = false;
  7450. this._drawCalls = new BABYLON.PerfCounter();
  7451. this._renderingQueueLaunched = false;
  7452. this._activeRenderLoops = [];
  7453. // Deterministic lockstepMaxSteps
  7454. this._deterministicLockstep = false;
  7455. this._lockstepMaxSteps = 4;
  7456. this._contextWasLost = false;
  7457. this._doNotHandleContextLost = false;
  7458. // FPS
  7459. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7460. this._fps = 60;
  7461. this._deltaTime = 0;
  7462. /**
  7463. * Turn this value on if you want to pause FPS computation when in background
  7464. */
  7465. this.disablePerformanceMonitorInBackground = false;
  7466. // States
  7467. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7468. this._stencilState = new BABYLON.Internals._StencilState();
  7469. this._alphaState = new BABYLON.Internals._AlphaState();
  7470. this._alphaMode = Engine.ALPHA_DISABLE;
  7471. // Cache
  7472. this._internalTexturesCache = new Array();
  7473. this._maxTextureChannels = 16;
  7474. this._activeTexturesCache = {};
  7475. this._compiledEffects = {};
  7476. this._vertexAttribArraysEnabled = [];
  7477. this._uintIndicesCurrentlySet = false;
  7478. this._currentBoundBuffer = new Array();
  7479. this._currentBufferPointers = new Array();
  7480. this._currentInstanceLocations = new Array();
  7481. this._currentInstanceBuffers = new Array();
  7482. this._vaoRecordInProgress = false;
  7483. this._mustWipeVertexAttributes = false;
  7484. // Hardware supported Compressed Textures
  7485. this._texturesSupported = new Array();
  7486. this._onVRFullScreenTriggered = function () {
  7487. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7488. //get the old size before we change
  7489. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7490. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7491. //get the width and height, change the render size
  7492. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7493. var width, height;
  7494. _this.setHardwareScalingLevel(1);
  7495. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7496. }
  7497. else {
  7498. //When the specs are implemented, need to uncomment this.
  7499. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7500. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7501. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7502. _this._vrDisplayEnabled = undefined;
  7503. }
  7504. };
  7505. var canvas;
  7506. Engine.Instances.push(this);
  7507. options = options || {};
  7508. if (canvasOrContext.getContext) {
  7509. canvas = canvasOrContext;
  7510. this._renderingCanvas = canvas;
  7511. if (antialias != null) {
  7512. options.antialias = antialias;
  7513. }
  7514. if (options.deterministicLockstep === undefined) {
  7515. options.deterministicLockstep = false;
  7516. }
  7517. if (options.lockstepMaxSteps === undefined) {
  7518. options.lockstepMaxSteps = 4;
  7519. }
  7520. if (options.preserveDrawingBuffer === undefined) {
  7521. options.preserveDrawingBuffer = false;
  7522. }
  7523. if (options.audioEngine === undefined) {
  7524. options.audioEngine = true;
  7525. }
  7526. if (options.stencil === undefined) {
  7527. options.stencil = true;
  7528. }
  7529. this._deterministicLockstep = options.deterministicLockstep;
  7530. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7531. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7532. // GL
  7533. if (!options.disableWebGL2Support) {
  7534. try {
  7535. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7536. if (this._gl) {
  7537. this._webGLVersion = 2.0;
  7538. }
  7539. }
  7540. catch (e) {
  7541. // Do nothing
  7542. }
  7543. }
  7544. if (!this._gl) {
  7545. if (!canvas) {
  7546. throw new Error("The provided canvas is null or undefined.");
  7547. }
  7548. try {
  7549. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7550. }
  7551. catch (e) {
  7552. throw new Error("WebGL not supported");
  7553. }
  7554. }
  7555. if (!this._gl) {
  7556. throw new Error("WebGL not supported");
  7557. }
  7558. this._onBlur = function () {
  7559. if (_this.disablePerformanceMonitorInBackground) {
  7560. _this._performanceMonitor.disable();
  7561. }
  7562. _this._windowIsBackground = true;
  7563. };
  7564. this._onFocus = function () {
  7565. if (_this.disablePerformanceMonitorInBackground) {
  7566. _this._performanceMonitor.enable();
  7567. }
  7568. _this._windowIsBackground = false;
  7569. };
  7570. this._onCanvasBlur = function () {
  7571. _this.onCanvasBlurObservable.notifyObservers(_this);
  7572. };
  7573. window.addEventListener("blur", this._onBlur);
  7574. window.addEventListener("focus", this._onFocus);
  7575. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7576. }
  7577. else {
  7578. this._gl = canvasOrContext;
  7579. this._renderingCanvas = this._gl.canvas;
  7580. if (this._gl.renderbufferStorageMultisample) {
  7581. this._webGLVersion = 2.0;
  7582. }
  7583. options.stencil = this._gl.getContextAttributes().stencil;
  7584. }
  7585. // Context lost
  7586. if (!this._doNotHandleContextLost) {
  7587. this._onContextLost = function (evt) {
  7588. evt.preventDefault();
  7589. _this._contextWasLost = true;
  7590. BABYLON.Tools.Warn("WebGL context lost.");
  7591. };
  7592. this._onContextRestored = function (evt) {
  7593. // Rebuild gl context
  7594. _this._initGLContext();
  7595. // Rebuild effects
  7596. _this._rebuildEffects();
  7597. // Rebuild textures
  7598. _this._rebuildInternalTextures();
  7599. // Rebuild buffers
  7600. _this._rebuildBuffers();
  7601. // Cache
  7602. _this.wipeCaches(true);
  7603. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7604. _this._contextWasLost = false;
  7605. };
  7606. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7607. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7608. }
  7609. // Viewport
  7610. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7611. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7612. this.resize();
  7613. this._isStencilEnable = options.stencil;
  7614. this._initGLContext();
  7615. if (canvas) {
  7616. // Fullscreen
  7617. this._onFullscreenChange = function () {
  7618. if (document.fullscreen !== undefined) {
  7619. _this.isFullscreen = document.fullscreen;
  7620. }
  7621. else if (document.mozFullScreen !== undefined) {
  7622. _this.isFullscreen = document.mozFullScreen;
  7623. }
  7624. else if (document.webkitIsFullScreen !== undefined) {
  7625. _this.isFullscreen = document.webkitIsFullScreen;
  7626. }
  7627. else if (document.msIsFullScreen !== undefined) {
  7628. _this.isFullscreen = document.msIsFullScreen;
  7629. }
  7630. // Pointer lock
  7631. if (_this.isFullscreen && _this._pointerLockRequested) {
  7632. canvas.requestPointerLock = canvas.requestPointerLock ||
  7633. canvas.msRequestPointerLock ||
  7634. canvas.mozRequestPointerLock ||
  7635. canvas.webkitRequestPointerLock;
  7636. if (canvas.requestPointerLock) {
  7637. canvas.requestPointerLock();
  7638. }
  7639. }
  7640. };
  7641. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7642. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7643. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7644. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7645. // Pointer lock
  7646. this._onPointerLockChange = function () {
  7647. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7648. document.webkitPointerLockElement === canvas ||
  7649. document.msPointerLockElement === canvas ||
  7650. document.pointerLockElement === canvas);
  7651. };
  7652. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7653. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7654. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7655. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7656. this._onVRDisplayPointerRestricted = function () {
  7657. canvas.requestPointerLock();
  7658. };
  7659. this._onVRDisplayPointerUnrestricted = function () {
  7660. document.exitPointerLock();
  7661. };
  7662. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7663. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7664. }
  7665. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7666. Engine.audioEngine = new BABYLON.AudioEngine();
  7667. }
  7668. // Prepare buffer pointers
  7669. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7670. this._currentBufferPointers[i] = new BufferPointer();
  7671. }
  7672. // Load WebVR Devices
  7673. if (options.autoEnableWebVR) {
  7674. this.initWebVR();
  7675. }
  7676. // Detect if we are running on a faulty buggy OS.
  7677. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7678. // Detect if we are running on a faulty buggy desktop OS.
  7679. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7680. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7681. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7682. }
  7683. Object.defineProperty(Engine, "LastCreatedEngine", {
  7684. get: function () {
  7685. if (Engine.Instances.length === 0) {
  7686. return null;
  7687. }
  7688. return Engine.Instances[Engine.Instances.length - 1];
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Engine, "LastCreatedScene", {
  7694. get: function () {
  7695. var lastCreatedEngine = Engine.LastCreatedEngine;
  7696. if (!lastCreatedEngine) {
  7697. return null;
  7698. }
  7699. if (lastCreatedEngine.scenes.length === 0) {
  7700. return null;
  7701. }
  7702. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. /**
  7708. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7709. */
  7710. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7711. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7712. var engine = Engine.Instances[engineIndex];
  7713. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7714. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7715. }
  7716. }
  7717. };
  7718. Object.defineProperty(Engine, "NEVER", {
  7719. get: function () {
  7720. return Engine._NEVER;
  7721. },
  7722. enumerable: true,
  7723. configurable: true
  7724. });
  7725. Object.defineProperty(Engine, "ALWAYS", {
  7726. get: function () {
  7727. return Engine._ALWAYS;
  7728. },
  7729. enumerable: true,
  7730. configurable: true
  7731. });
  7732. Object.defineProperty(Engine, "LESS", {
  7733. get: function () {
  7734. return Engine._LESS;
  7735. },
  7736. enumerable: true,
  7737. configurable: true
  7738. });
  7739. Object.defineProperty(Engine, "EQUAL", {
  7740. get: function () {
  7741. return Engine._EQUAL;
  7742. },
  7743. enumerable: true,
  7744. configurable: true
  7745. });
  7746. Object.defineProperty(Engine, "LEQUAL", {
  7747. get: function () {
  7748. return Engine._LEQUAL;
  7749. },
  7750. enumerable: true,
  7751. configurable: true
  7752. });
  7753. Object.defineProperty(Engine, "GREATER", {
  7754. get: function () {
  7755. return Engine._GREATER;
  7756. },
  7757. enumerable: true,
  7758. configurable: true
  7759. });
  7760. Object.defineProperty(Engine, "GEQUAL", {
  7761. get: function () {
  7762. return Engine._GEQUAL;
  7763. },
  7764. enumerable: true,
  7765. configurable: true
  7766. });
  7767. Object.defineProperty(Engine, "NOTEQUAL", {
  7768. get: function () {
  7769. return Engine._NOTEQUAL;
  7770. },
  7771. enumerable: true,
  7772. configurable: true
  7773. });
  7774. Object.defineProperty(Engine, "KEEP", {
  7775. get: function () {
  7776. return Engine._KEEP;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(Engine, "REPLACE", {
  7782. get: function () {
  7783. return Engine._REPLACE;
  7784. },
  7785. enumerable: true,
  7786. configurable: true
  7787. });
  7788. Object.defineProperty(Engine, "INCR", {
  7789. get: function () {
  7790. return Engine._INCR;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine, "DECR", {
  7796. get: function () {
  7797. return Engine._DECR;
  7798. },
  7799. enumerable: true,
  7800. configurable: true
  7801. });
  7802. Object.defineProperty(Engine, "INVERT", {
  7803. get: function () {
  7804. return Engine._INVERT;
  7805. },
  7806. enumerable: true,
  7807. configurable: true
  7808. });
  7809. Object.defineProperty(Engine, "INCR_WRAP", {
  7810. get: function () {
  7811. return Engine._INCR_WRAP;
  7812. },
  7813. enumerable: true,
  7814. configurable: true
  7815. });
  7816. Object.defineProperty(Engine, "DECR_WRAP", {
  7817. get: function () {
  7818. return Engine._DECR_WRAP;
  7819. },
  7820. enumerable: true,
  7821. configurable: true
  7822. });
  7823. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7824. get: function () {
  7825. return Engine._ALPHA_DISABLE;
  7826. },
  7827. enumerable: true,
  7828. configurable: true
  7829. });
  7830. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7831. get: function () {
  7832. return Engine._ALPHA_ONEONE;
  7833. },
  7834. enumerable: true,
  7835. configurable: true
  7836. });
  7837. Object.defineProperty(Engine, "ALPHA_ADD", {
  7838. get: function () {
  7839. return Engine._ALPHA_ADD;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7845. get: function () {
  7846. return Engine._ALPHA_COMBINE;
  7847. },
  7848. enumerable: true,
  7849. configurable: true
  7850. });
  7851. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7852. get: function () {
  7853. return Engine._ALPHA_SUBTRACT;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7859. get: function () {
  7860. return Engine._ALPHA_MULTIPLY;
  7861. },
  7862. enumerable: true,
  7863. configurable: true
  7864. });
  7865. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7866. get: function () {
  7867. return Engine._ALPHA_MAXIMIZED;
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7873. get: function () {
  7874. return Engine._ALPHA_PREMULTIPLIED;
  7875. },
  7876. enumerable: true,
  7877. configurable: true
  7878. });
  7879. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7880. get: function () {
  7881. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7882. },
  7883. enumerable: true,
  7884. configurable: true
  7885. });
  7886. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7887. get: function () {
  7888. return Engine._ALPHA_INTERPOLATE;
  7889. },
  7890. enumerable: true,
  7891. configurable: true
  7892. });
  7893. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7894. get: function () {
  7895. return Engine._ALPHA_SCREENMODE;
  7896. },
  7897. enumerable: true,
  7898. configurable: true
  7899. });
  7900. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7901. get: function () {
  7902. return Engine._DELAYLOADSTATE_NONE;
  7903. },
  7904. enumerable: true,
  7905. configurable: true
  7906. });
  7907. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7908. get: function () {
  7909. return Engine._DELAYLOADSTATE_LOADED;
  7910. },
  7911. enumerable: true,
  7912. configurable: true
  7913. });
  7914. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7915. get: function () {
  7916. return Engine._DELAYLOADSTATE_LOADING;
  7917. },
  7918. enumerable: true,
  7919. configurable: true
  7920. });
  7921. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7922. get: function () {
  7923. return Engine._DELAYLOADSTATE_NOTLOADED;
  7924. },
  7925. enumerable: true,
  7926. configurable: true
  7927. });
  7928. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7929. get: function () {
  7930. return Engine._TEXTUREFORMAT_ALPHA;
  7931. },
  7932. enumerable: true,
  7933. configurable: true
  7934. });
  7935. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7936. get: function () {
  7937. return Engine._TEXTUREFORMAT_LUMINANCE;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7943. get: function () {
  7944. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7945. },
  7946. enumerable: true,
  7947. configurable: true
  7948. });
  7949. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7950. get: function () {
  7951. return Engine._TEXTUREFORMAT_RGB;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7957. get: function () {
  7958. return Engine._TEXTUREFORMAT_RGBA;
  7959. },
  7960. enumerable: true,
  7961. configurable: true
  7962. });
  7963. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7964. get: function () {
  7965. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7971. get: function () {
  7972. return Engine._TEXTURETYPE_FLOAT;
  7973. },
  7974. enumerable: true,
  7975. configurable: true
  7976. });
  7977. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7978. get: function () {
  7979. return Engine._TEXTURETYPE_HALF_FLOAT;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7985. get: function () {
  7986. return Engine._SCALEMODE_FLOOR;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7992. get: function () {
  7993. return Engine._SCALEMODE_NEAREST;
  7994. },
  7995. enumerable: true,
  7996. configurable: true
  7997. });
  7998. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7999. get: function () {
  8000. return Engine._SCALEMODE_CEILING;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Engine, "Version", {
  8006. get: function () {
  8007. return "3.1-alpha";
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8013. get: function () {
  8014. return this._webGLVersion < 2 || this.forcePOTTextures;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Object.defineProperty(Engine.prototype, "badOS", {
  8020. get: function () {
  8021. return this._badOS;
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8027. get: function () {
  8028. return this._badDesktopOS;
  8029. },
  8030. enumerable: true,
  8031. configurable: true
  8032. });
  8033. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8034. get: function () {
  8035. return this._performanceMonitor;
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8041. get: function () {
  8042. return this._texturesSupported;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8048. get: function () {
  8049. return this._textureFormatInUse;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8055. // Empty texture
  8056. get: function () {
  8057. if (!this._emptyTexture) {
  8058. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8059. }
  8060. return this._emptyTexture;
  8061. },
  8062. enumerable: true,
  8063. configurable: true
  8064. });
  8065. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8066. get: function () {
  8067. if (!this._emptyCubeTexture) {
  8068. var faceData = new Uint8Array(4);
  8069. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8070. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8071. }
  8072. return this._emptyCubeTexture;
  8073. },
  8074. enumerable: true,
  8075. configurable: true
  8076. });
  8077. Engine.prototype._rebuildInternalTextures = function () {
  8078. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8079. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8080. var internalTexture = currentState_1[_i];
  8081. internalTexture._rebuild();
  8082. }
  8083. };
  8084. Engine.prototype._rebuildEffects = function () {
  8085. for (var key in this._compiledEffects) {
  8086. var effect = this._compiledEffects[key];
  8087. effect._prepareEffect();
  8088. }
  8089. BABYLON.Effect.ResetCache();
  8090. };
  8091. Engine.prototype._rebuildBuffers = function () {
  8092. // Index / Vertex
  8093. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8094. var scene = _a[_i];
  8095. scene.resetCachedMaterial();
  8096. scene._rebuildGeometries();
  8097. scene._rebuildTextures();
  8098. }
  8099. // Uniforms
  8100. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8101. var uniformBuffer = _c[_b];
  8102. uniformBuffer._rebuild();
  8103. }
  8104. };
  8105. Engine.prototype._initGLContext = function () {
  8106. // Caps
  8107. this._caps = new EngineCapabilities();
  8108. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8109. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8110. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8111. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8112. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8113. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8114. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8115. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8116. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8117. // Infos
  8118. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8119. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8120. if (rendererInfo != null) {
  8121. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8122. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8123. }
  8124. if (!this._glVendor) {
  8125. this._glVendor = "Unknown vendor";
  8126. }
  8127. if (!this._glRenderer) {
  8128. this._glRenderer = "Unknown renderer";
  8129. }
  8130. // Constants
  8131. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8132. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8133. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8134. this._gl.DEPTH24_STENCIL8 = 35056;
  8135. // Extensions
  8136. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8137. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8138. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8139. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8140. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8141. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8142. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8143. 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');
  8144. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8145. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8146. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8147. this._caps.highPrecisionShaderSupported = true;
  8148. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8149. // Checks if some of the format renders first to allow the use of webgl inspector.
  8150. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8151. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8152. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8153. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8154. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8155. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8156. if (this._webGLVersion > 1) {
  8157. this._gl.HALF_FLOAT_OES = 0x140B;
  8158. }
  8159. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8160. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8161. // Vertex array object
  8162. if (this._webGLVersion > 1) {
  8163. this._caps.vertexArrayObject = true;
  8164. }
  8165. else {
  8166. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8167. if (vertexArrayObjectExtension != null) {
  8168. this._caps.vertexArrayObject = true;
  8169. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8170. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8171. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8172. }
  8173. else {
  8174. this._caps.vertexArrayObject = false;
  8175. }
  8176. }
  8177. // Instances count
  8178. if (this._webGLVersion > 1) {
  8179. this._caps.instancedArrays = true;
  8180. }
  8181. else {
  8182. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8183. if (instanceExtension != null) {
  8184. this._caps.instancedArrays = true;
  8185. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8186. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8187. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8188. }
  8189. else {
  8190. this._caps.instancedArrays = false;
  8191. }
  8192. }
  8193. // Intelligently add supported compressed formats in order to check for.
  8194. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8195. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8196. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8197. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8198. if (this._caps.astc)
  8199. this.texturesSupported.push('-astc.ktx');
  8200. if (this._caps.s3tc)
  8201. this.texturesSupported.push('-dxt.ktx');
  8202. if (this._caps.pvrtc)
  8203. this.texturesSupported.push('-pvrtc.ktx');
  8204. if (this._caps.etc2)
  8205. this.texturesSupported.push('-etc2.ktx');
  8206. if (this._caps.etc1)
  8207. this.texturesSupported.push('-etc1.ktx');
  8208. if (this._gl.getShaderPrecisionFormat) {
  8209. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8210. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8211. }
  8212. // Depth buffer
  8213. this.setDepthBuffer(true);
  8214. this.setDepthFunctionToLessOrEqual();
  8215. this.setDepthWrite(true);
  8216. };
  8217. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8218. get: function () {
  8219. return this._webGLVersion;
  8220. },
  8221. enumerable: true,
  8222. configurable: true
  8223. });
  8224. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8225. /**
  8226. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8227. */
  8228. get: function () {
  8229. return this._isStencilEnable;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Engine.prototype._prepareWorkingCanvas = function () {
  8235. if (this._workingCanvas) {
  8236. return;
  8237. }
  8238. this._workingCanvas = document.createElement("canvas");
  8239. this._workingContext = this._workingCanvas.getContext("2d");
  8240. };
  8241. Engine.prototype.resetTextureCache = function () {
  8242. for (var key in this._activeTexturesCache) {
  8243. this._activeTexturesCache[key] = null;
  8244. }
  8245. };
  8246. Engine.prototype.isDeterministicLockStep = function () {
  8247. return this._deterministicLockstep;
  8248. };
  8249. Engine.prototype.getLockstepMaxSteps = function () {
  8250. return this._lockstepMaxSteps;
  8251. };
  8252. Engine.prototype.getGlInfo = function () {
  8253. return {
  8254. vendor: this._glVendor,
  8255. renderer: this._glRenderer,
  8256. version: this._glVersion
  8257. };
  8258. };
  8259. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8260. if (useScreen === void 0) { useScreen = false; }
  8261. var viewport = camera.viewport;
  8262. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8263. };
  8264. Engine.prototype.getRenderWidth = function (useScreen) {
  8265. if (useScreen === void 0) { useScreen = false; }
  8266. if (!useScreen && this._currentRenderTarget) {
  8267. return this._currentRenderTarget.width;
  8268. }
  8269. return this._gl.drawingBufferWidth;
  8270. };
  8271. Engine.prototype.getRenderHeight = function (useScreen) {
  8272. if (useScreen === void 0) { useScreen = false; }
  8273. if (!useScreen && this._currentRenderTarget) {
  8274. return this._currentRenderTarget.height;
  8275. }
  8276. return this._gl.drawingBufferHeight;
  8277. };
  8278. Engine.prototype.getRenderingCanvas = function () {
  8279. return this._renderingCanvas;
  8280. };
  8281. Engine.prototype.getRenderingCanvasClientRect = function () {
  8282. return this._renderingCanvas.getBoundingClientRect();
  8283. };
  8284. Engine.prototype.setHardwareScalingLevel = function (level) {
  8285. this._hardwareScalingLevel = level;
  8286. this.resize();
  8287. };
  8288. Engine.prototype.getHardwareScalingLevel = function () {
  8289. return this._hardwareScalingLevel;
  8290. };
  8291. Engine.prototype.getLoadedTexturesCache = function () {
  8292. return this._internalTexturesCache;
  8293. };
  8294. Engine.prototype.getCaps = function () {
  8295. return this._caps;
  8296. };
  8297. Object.defineProperty(Engine.prototype, "drawCalls", {
  8298. /** The number of draw calls submitted last frame */
  8299. get: function () {
  8300. return this._drawCalls.current;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8306. get: function () {
  8307. return this._drawCalls;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Engine.prototype.getDepthFunction = function () {
  8313. return this._depthCullingState.depthFunc;
  8314. };
  8315. Engine.prototype.setDepthFunction = function (depthFunc) {
  8316. this._depthCullingState.depthFunc = depthFunc;
  8317. };
  8318. Engine.prototype.setDepthFunctionToGreater = function () {
  8319. this._depthCullingState.depthFunc = this._gl.GREATER;
  8320. };
  8321. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8322. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8323. };
  8324. Engine.prototype.setDepthFunctionToLess = function () {
  8325. this._depthCullingState.depthFunc = this._gl.LESS;
  8326. };
  8327. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8328. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8329. };
  8330. Engine.prototype.getStencilBuffer = function () {
  8331. return this._stencilState.stencilTest;
  8332. };
  8333. Engine.prototype.setStencilBuffer = function (enable) {
  8334. this._stencilState.stencilTest = enable;
  8335. };
  8336. Engine.prototype.getStencilMask = function () {
  8337. return this._stencilState.stencilMask;
  8338. };
  8339. Engine.prototype.setStencilMask = function (mask) {
  8340. this._stencilState.stencilMask = mask;
  8341. };
  8342. Engine.prototype.getStencilFunction = function () {
  8343. return this._stencilState.stencilFunc;
  8344. };
  8345. Engine.prototype.getStencilFunctionReference = function () {
  8346. return this._stencilState.stencilFuncRef;
  8347. };
  8348. Engine.prototype.getStencilFunctionMask = function () {
  8349. return this._stencilState.stencilFuncMask;
  8350. };
  8351. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8352. this._stencilState.stencilFunc = stencilFunc;
  8353. };
  8354. Engine.prototype.setStencilFunctionReference = function (reference) {
  8355. this._stencilState.stencilFuncRef = reference;
  8356. };
  8357. Engine.prototype.setStencilFunctionMask = function (mask) {
  8358. this._stencilState.stencilFuncMask = mask;
  8359. };
  8360. Engine.prototype.getStencilOperationFail = function () {
  8361. return this._stencilState.stencilOpStencilFail;
  8362. };
  8363. Engine.prototype.getStencilOperationDepthFail = function () {
  8364. return this._stencilState.stencilOpDepthFail;
  8365. };
  8366. Engine.prototype.getStencilOperationPass = function () {
  8367. return this._stencilState.stencilOpStencilDepthPass;
  8368. };
  8369. Engine.prototype.setStencilOperationFail = function (operation) {
  8370. this._stencilState.stencilOpStencilFail = operation;
  8371. };
  8372. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8373. this._stencilState.stencilOpDepthFail = operation;
  8374. };
  8375. Engine.prototype.setStencilOperationPass = function (operation) {
  8376. this._stencilState.stencilOpStencilDepthPass = operation;
  8377. };
  8378. Engine.prototype.setDitheringState = function (value) {
  8379. if (value) {
  8380. this._gl.enable(this._gl.DITHER);
  8381. }
  8382. else {
  8383. this._gl.disable(this._gl.DITHER);
  8384. }
  8385. };
  8386. /**
  8387. * stop executing a render loop function and remove it from the execution array
  8388. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8389. */
  8390. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8391. if (!renderFunction) {
  8392. this._activeRenderLoops = [];
  8393. return;
  8394. }
  8395. var index = this._activeRenderLoops.indexOf(renderFunction);
  8396. if (index >= 0) {
  8397. this._activeRenderLoops.splice(index, 1);
  8398. }
  8399. };
  8400. Engine.prototype._renderLoop = function () {
  8401. if (!this._contextWasLost) {
  8402. var shouldRender = true;
  8403. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8404. shouldRender = false;
  8405. }
  8406. if (shouldRender) {
  8407. // Start new frame
  8408. this.beginFrame();
  8409. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8410. var renderFunction = this._activeRenderLoops[index];
  8411. renderFunction();
  8412. }
  8413. // Present
  8414. this.endFrame();
  8415. }
  8416. }
  8417. if (this._activeRenderLoops.length > 0) {
  8418. // Register new frame
  8419. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8420. }
  8421. else {
  8422. this._renderingQueueLaunched = false;
  8423. }
  8424. };
  8425. /**
  8426. * Register and execute a render loop. The engine can have more than one render function.
  8427. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8428. * @example
  8429. * engine.runRenderLoop(function () {
  8430. * scene.render()
  8431. * })
  8432. */
  8433. Engine.prototype.runRenderLoop = function (renderFunction) {
  8434. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8435. return;
  8436. }
  8437. this._activeRenderLoops.push(renderFunction);
  8438. if (!this._renderingQueueLaunched) {
  8439. this._renderingQueueLaunched = true;
  8440. this._bindedRenderFunction = this._renderLoop.bind(this);
  8441. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8442. }
  8443. };
  8444. /**
  8445. * Toggle full screen mode.
  8446. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8447. * @param {any} options - an options object to be sent to the requestFullscreen function
  8448. */
  8449. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8450. if (this.isFullscreen) {
  8451. BABYLON.Tools.ExitFullscreen();
  8452. }
  8453. else {
  8454. this._pointerLockRequested = requestPointerLock;
  8455. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8456. }
  8457. };
  8458. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8459. if (stencil === void 0) { stencil = false; }
  8460. this.applyStates();
  8461. var mode = 0;
  8462. if (backBuffer && color) {
  8463. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8464. mode |= this._gl.COLOR_BUFFER_BIT;
  8465. }
  8466. if (depth) {
  8467. this._gl.clearDepth(1.0);
  8468. mode |= this._gl.DEPTH_BUFFER_BIT;
  8469. }
  8470. if (stencil) {
  8471. this._gl.clearStencil(0);
  8472. mode |= this._gl.STENCIL_BUFFER_BIT;
  8473. }
  8474. this._gl.clear(mode);
  8475. };
  8476. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8477. var gl = this._gl;
  8478. // Save state
  8479. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8480. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8481. // Change state
  8482. gl.enable(gl.SCISSOR_TEST);
  8483. gl.scissor(x, y, width, height);
  8484. // Clear
  8485. this.clear(clearColor, true, true, true);
  8486. // Restore state
  8487. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8488. if (curScissor === true) {
  8489. gl.enable(gl.SCISSOR_TEST);
  8490. }
  8491. else {
  8492. gl.disable(gl.SCISSOR_TEST);
  8493. }
  8494. };
  8495. /**
  8496. * Set the WebGL's viewport
  8497. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8498. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8499. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8500. */
  8501. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8502. var width = requiredWidth || this.getRenderWidth();
  8503. var height = requiredHeight || this.getRenderHeight();
  8504. var x = viewport.x || 0;
  8505. var y = viewport.y || 0;
  8506. this._cachedViewport = viewport;
  8507. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8508. };
  8509. /**
  8510. * Directly set the WebGL Viewport
  8511. * The x, y, width & height are directly passed to the WebGL call
  8512. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  8513. */
  8514. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8515. var currentViewport = this._cachedViewport;
  8516. this._cachedViewport = null;
  8517. this._gl.viewport(x, y, width, height);
  8518. return currentViewport;
  8519. };
  8520. Engine.prototype.beginFrame = function () {
  8521. this._measureFps();
  8522. };
  8523. Engine.prototype.endFrame = function () {
  8524. //force a flush in case we are using a bad OS.
  8525. if (this._badOS) {
  8526. this.flushFramebuffer();
  8527. }
  8528. //submit frame to the vr device, if enabled
  8529. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8530. this._vrDisplayEnabled.submitFrame();
  8531. }
  8532. };
  8533. /**
  8534. * resize the view according to the canvas' size.
  8535. * @example
  8536. * window.addEventListener("resize", function () {
  8537. * engine.resize();
  8538. * });
  8539. */
  8540. Engine.prototype.resize = function () {
  8541. // We're not resizing the size of the canvas while in VR mode & presenting
  8542. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8543. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8544. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8545. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8546. }
  8547. };
  8548. /**
  8549. * force a specific size of the canvas
  8550. * @param {number} width - the new canvas' width
  8551. * @param {number} height - the new canvas' height
  8552. */
  8553. Engine.prototype.setSize = function (width, height) {
  8554. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8555. return;
  8556. }
  8557. this._renderingCanvas.width = width;
  8558. this._renderingCanvas.height = height;
  8559. for (var index = 0; index < this.scenes.length; index++) {
  8560. var scene = this.scenes[index];
  8561. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8562. var cam = scene.cameras[camIndex];
  8563. cam._currentRenderId = 0;
  8564. }
  8565. }
  8566. if (this.onResizeObservable.hasObservers) {
  8567. this.onResizeObservable.notifyObservers(this);
  8568. }
  8569. };
  8570. //WebVR functions
  8571. Engine.prototype.isVRDevicePresent = function (callback) {
  8572. this.getVRDevice(null, function (device) {
  8573. callback(device !== null);
  8574. });
  8575. };
  8576. Engine.prototype.getVRDevice = function (name, callback) {
  8577. if (!this.vrDisplaysPromise) {
  8578. callback(null);
  8579. return;
  8580. }
  8581. this.vrDisplaysPromise.then(function (devices) {
  8582. if (devices.length > 0) {
  8583. if (name) {
  8584. var found = devices.some(function (device) {
  8585. if (device.displayName === name) {
  8586. callback(device);
  8587. return true;
  8588. }
  8589. else {
  8590. return false;
  8591. }
  8592. });
  8593. if (!found) {
  8594. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8595. callback(devices[0]);
  8596. }
  8597. }
  8598. else {
  8599. //choose the first one
  8600. callback(devices[0]);
  8601. }
  8602. }
  8603. else {
  8604. BABYLON.Tools.Error("No WebVR devices found!");
  8605. callback(null);
  8606. }
  8607. });
  8608. };
  8609. Engine.prototype.initWebVR = function () {
  8610. if (!this.vrDisplaysPromise) {
  8611. this._getVRDisplays();
  8612. }
  8613. };
  8614. Engine.prototype.enableVR = function (vrDevice) {
  8615. this._vrDisplayEnabled = vrDevice;
  8616. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8617. };
  8618. Engine.prototype.disableVR = function () {
  8619. if (this._vrDisplayEnabled) {
  8620. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8621. }
  8622. };
  8623. Engine.prototype._getVRDisplays = function () {
  8624. var _this = this;
  8625. var getWebVRDevices = function (devices) {
  8626. _this._vrDisplays = devices.filter(function (device) {
  8627. return device instanceof VRDisplay;
  8628. });
  8629. return _this._vrDisplays;
  8630. };
  8631. if (navigator.getVRDisplays) {
  8632. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8633. }
  8634. };
  8635. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8636. if (this._currentRenderTarget) {
  8637. this.unBindFramebuffer(this._currentRenderTarget);
  8638. }
  8639. this._currentRenderTarget = texture;
  8640. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8641. var gl = this._gl;
  8642. if (texture.isCube) {
  8643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8644. }
  8645. if (this._cachedViewport && !forceFullscreenViewport) {
  8646. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8647. }
  8648. else {
  8649. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8650. }
  8651. this.wipeCaches();
  8652. };
  8653. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8654. if (this._currentFramebuffer !== framebuffer) {
  8655. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8656. this._currentFramebuffer = framebuffer;
  8657. }
  8658. };
  8659. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8660. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8661. this._currentRenderTarget = null;
  8662. // If MSAA, we need to bitblt back to main texture
  8663. var gl = this._gl;
  8664. if (texture._MSAAFramebuffer) {
  8665. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8666. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8667. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8668. }
  8669. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8670. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8671. gl.generateMipmap(gl.TEXTURE_2D);
  8672. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8673. }
  8674. if (onBeforeUnbind) {
  8675. if (texture._MSAAFramebuffer) {
  8676. // Bind the correct framebuffer
  8677. this.bindUnboundFramebuffer(texture._framebuffer);
  8678. }
  8679. onBeforeUnbind();
  8680. }
  8681. this.bindUnboundFramebuffer(null);
  8682. };
  8683. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8684. if (texture.generateMipMaps) {
  8685. var gl = this._gl;
  8686. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8687. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8688. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8689. }
  8690. };
  8691. Engine.prototype.flushFramebuffer = function () {
  8692. this._gl.flush();
  8693. };
  8694. Engine.prototype.restoreDefaultFramebuffer = function () {
  8695. if (this._currentRenderTarget) {
  8696. this.unBindFramebuffer(this._currentRenderTarget);
  8697. }
  8698. else {
  8699. this.bindUnboundFramebuffer(null);
  8700. }
  8701. if (this._cachedViewport) {
  8702. this.setViewport(this._cachedViewport);
  8703. }
  8704. this.wipeCaches();
  8705. };
  8706. // UBOs
  8707. Engine.prototype.createUniformBuffer = function (elements) {
  8708. var ubo = this._gl.createBuffer();
  8709. this.bindUniformBuffer(ubo);
  8710. if (elements instanceof Float32Array) {
  8711. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8712. }
  8713. else {
  8714. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8715. }
  8716. this.bindUniformBuffer(null);
  8717. ubo.references = 1;
  8718. return ubo;
  8719. };
  8720. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8721. var ubo = this._gl.createBuffer();
  8722. this.bindUniformBuffer(ubo);
  8723. if (elements instanceof Float32Array) {
  8724. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8725. }
  8726. else {
  8727. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8728. }
  8729. this.bindUniformBuffer(null);
  8730. ubo.references = 1;
  8731. return ubo;
  8732. };
  8733. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8734. this.bindUniformBuffer(uniformBuffer);
  8735. if (offset === undefined) {
  8736. offset = 0;
  8737. }
  8738. if (count === undefined) {
  8739. if (elements instanceof Float32Array) {
  8740. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8741. }
  8742. else {
  8743. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8744. }
  8745. }
  8746. else {
  8747. if (elements instanceof Float32Array) {
  8748. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8749. }
  8750. else {
  8751. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8752. }
  8753. }
  8754. this.bindUniformBuffer(null);
  8755. };
  8756. // VBOs
  8757. Engine.prototype._resetVertexBufferBinding = function () {
  8758. this.bindArrayBuffer(null);
  8759. this._cachedVertexBuffers = null;
  8760. };
  8761. Engine.prototype.createVertexBuffer = function (vertices) {
  8762. var vbo = this._gl.createBuffer();
  8763. this.bindArrayBuffer(vbo);
  8764. if (vertices instanceof Float32Array) {
  8765. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8766. }
  8767. else {
  8768. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8769. }
  8770. this._resetVertexBufferBinding();
  8771. vbo.references = 1;
  8772. return vbo;
  8773. };
  8774. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8775. var vbo = this._gl.createBuffer();
  8776. this.bindArrayBuffer(vbo);
  8777. if (vertices instanceof Float32Array) {
  8778. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8779. }
  8780. else {
  8781. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8782. }
  8783. this._resetVertexBufferBinding();
  8784. vbo.references = 1;
  8785. return vbo;
  8786. };
  8787. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8788. this.bindArrayBuffer(vertexBuffer);
  8789. if (offset === undefined) {
  8790. offset = 0;
  8791. }
  8792. if (count === undefined) {
  8793. if (vertices instanceof Float32Array) {
  8794. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8795. }
  8796. else {
  8797. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8798. }
  8799. }
  8800. else {
  8801. if (vertices instanceof Float32Array) {
  8802. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8803. }
  8804. else {
  8805. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8806. }
  8807. }
  8808. this._resetVertexBufferBinding();
  8809. };
  8810. Engine.prototype._resetIndexBufferBinding = function () {
  8811. this.bindIndexBuffer(null);
  8812. this._cachedIndexBuffer = null;
  8813. };
  8814. Engine.prototype.createIndexBuffer = function (indices) {
  8815. var vbo = this._gl.createBuffer();
  8816. this.bindIndexBuffer(vbo);
  8817. // Check for 32 bits indices
  8818. var arrayBuffer;
  8819. var need32Bits = false;
  8820. if (indices instanceof Uint16Array) {
  8821. arrayBuffer = indices;
  8822. }
  8823. else {
  8824. //check 32 bit support
  8825. if (this._caps.uintIndices) {
  8826. if (indices instanceof Uint32Array) {
  8827. arrayBuffer = indices;
  8828. need32Bits = true;
  8829. }
  8830. else {
  8831. //number[] or Int32Array, check if 32 bit is necessary
  8832. for (var index = 0; index < indices.length; index++) {
  8833. if (indices[index] > 65535) {
  8834. need32Bits = true;
  8835. break;
  8836. }
  8837. }
  8838. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8839. }
  8840. }
  8841. else {
  8842. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8843. arrayBuffer = new Uint16Array(indices);
  8844. }
  8845. }
  8846. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8847. this._resetIndexBufferBinding();
  8848. vbo.references = 1;
  8849. vbo.is32Bits = need32Bits;
  8850. return vbo;
  8851. };
  8852. Engine.prototype.bindArrayBuffer = function (buffer) {
  8853. if (!this._vaoRecordInProgress) {
  8854. this._unbindVertexArrayObject();
  8855. }
  8856. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8857. };
  8858. Engine.prototype.bindUniformBuffer = function (buffer) {
  8859. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8860. };
  8861. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8862. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8863. };
  8864. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8865. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8866. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8867. };
  8868. ;
  8869. Engine.prototype.bindIndexBuffer = function (buffer) {
  8870. if (!this._vaoRecordInProgress) {
  8871. this._unbindVertexArrayObject();
  8872. }
  8873. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8874. };
  8875. Engine.prototype.bindBuffer = function (buffer, target) {
  8876. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8877. this._gl.bindBuffer(target, buffer);
  8878. this._currentBoundBuffer[target] = buffer;
  8879. }
  8880. };
  8881. Engine.prototype.updateArrayBuffer = function (data) {
  8882. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8883. };
  8884. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8885. var pointer = this._currentBufferPointers[indx];
  8886. var changed = false;
  8887. if (!pointer.active) {
  8888. changed = true;
  8889. pointer.active = true;
  8890. pointer.index = indx;
  8891. pointer.size = size;
  8892. pointer.type = type;
  8893. pointer.normalized = normalized;
  8894. pointer.stride = stride;
  8895. pointer.offset = offset;
  8896. pointer.buffer = buffer;
  8897. }
  8898. else {
  8899. if (pointer.buffer !== buffer) {
  8900. pointer.buffer = buffer;
  8901. changed = true;
  8902. }
  8903. if (pointer.size !== size) {
  8904. pointer.size = size;
  8905. changed = true;
  8906. }
  8907. if (pointer.type !== type) {
  8908. pointer.type = type;
  8909. changed = true;
  8910. }
  8911. if (pointer.normalized !== normalized) {
  8912. pointer.normalized = normalized;
  8913. changed = true;
  8914. }
  8915. if (pointer.stride !== stride) {
  8916. pointer.stride = stride;
  8917. changed = true;
  8918. }
  8919. if (pointer.offset !== offset) {
  8920. pointer.offset = offset;
  8921. changed = true;
  8922. }
  8923. }
  8924. if (changed || this._vaoRecordInProgress) {
  8925. this.bindArrayBuffer(buffer);
  8926. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8927. }
  8928. };
  8929. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8930. if (indexBuffer == null) {
  8931. return;
  8932. }
  8933. if (this._cachedIndexBuffer !== indexBuffer) {
  8934. this._cachedIndexBuffer = indexBuffer;
  8935. this.bindIndexBuffer(indexBuffer);
  8936. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8937. }
  8938. };
  8939. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8940. var attributes = effect.getAttributesNames();
  8941. if (!this._vaoRecordInProgress) {
  8942. this._unbindVertexArrayObject();
  8943. }
  8944. this.unbindAllAttributes();
  8945. for (var index = 0; index < attributes.length; index++) {
  8946. var order = effect.getAttributeLocation(index);
  8947. if (order >= 0) {
  8948. var vertexBuffer = vertexBuffers[attributes[index]];
  8949. if (!vertexBuffer) {
  8950. continue;
  8951. }
  8952. this._gl.enableVertexAttribArray(order);
  8953. if (!this._vaoRecordInProgress) {
  8954. this._vertexAttribArraysEnabled[order] = true;
  8955. }
  8956. var buffer = vertexBuffer.getBuffer();
  8957. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8958. if (vertexBuffer.getIsInstanced()) {
  8959. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8960. if (!this._vaoRecordInProgress) {
  8961. this._currentInstanceLocations.push(order);
  8962. this._currentInstanceBuffers.push(buffer);
  8963. }
  8964. }
  8965. }
  8966. }
  8967. };
  8968. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8969. var vao = this._gl.createVertexArray();
  8970. this._vaoRecordInProgress = true;
  8971. this._gl.bindVertexArray(vao);
  8972. this._mustWipeVertexAttributes = true;
  8973. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8974. this.bindIndexBuffer(indexBuffer);
  8975. this._vaoRecordInProgress = false;
  8976. this._gl.bindVertexArray(null);
  8977. return vao;
  8978. };
  8979. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8980. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8981. this._cachedVertexArrayObject = vertexArrayObject;
  8982. this._gl.bindVertexArray(vertexArrayObject);
  8983. this._cachedVertexBuffers = null;
  8984. this._cachedIndexBuffer = null;
  8985. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8986. this._mustWipeVertexAttributes = true;
  8987. }
  8988. };
  8989. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8990. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8991. this._cachedVertexBuffers = vertexBuffer;
  8992. this._cachedEffectForVertexBuffers = effect;
  8993. var attributesCount = effect.getAttributesCount();
  8994. this._unbindVertexArrayObject();
  8995. this.unbindAllAttributes();
  8996. var offset = 0;
  8997. for (var index = 0; index < attributesCount; index++) {
  8998. if (index < vertexDeclaration.length) {
  8999. var order = effect.getAttributeLocation(index);
  9000. if (order >= 0) {
  9001. this._gl.enableVertexAttribArray(order);
  9002. this._vertexAttribArraysEnabled[order] = true;
  9003. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9004. }
  9005. offset += vertexDeclaration[index] * 4;
  9006. }
  9007. }
  9008. }
  9009. this._bindIndexBufferWithCache(indexBuffer);
  9010. };
  9011. Engine.prototype._unbindVertexArrayObject = function () {
  9012. if (!this._cachedVertexArrayObject) {
  9013. return;
  9014. }
  9015. this._cachedVertexArrayObject = null;
  9016. this._gl.bindVertexArray(null);
  9017. };
  9018. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9019. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9020. this._cachedVertexBuffers = vertexBuffers;
  9021. this._cachedEffectForVertexBuffers = effect;
  9022. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9023. }
  9024. this._bindIndexBufferWithCache(indexBuffer);
  9025. };
  9026. Engine.prototype.unbindInstanceAttributes = function () {
  9027. var boundBuffer;
  9028. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9029. var instancesBuffer = this._currentInstanceBuffers[i];
  9030. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9031. boundBuffer = instancesBuffer;
  9032. this.bindArrayBuffer(instancesBuffer);
  9033. }
  9034. var offsetLocation = this._currentInstanceLocations[i];
  9035. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9036. }
  9037. this._currentInstanceBuffers.length = 0;
  9038. this._currentInstanceLocations.length = 0;
  9039. };
  9040. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9041. this._gl.deleteVertexArray(vao);
  9042. };
  9043. Engine.prototype._releaseBuffer = function (buffer) {
  9044. buffer.references--;
  9045. if (buffer.references === 0) {
  9046. this._gl.deleteBuffer(buffer);
  9047. return true;
  9048. }
  9049. return false;
  9050. };
  9051. Engine.prototype.createInstancesBuffer = function (capacity) {
  9052. var buffer = this._gl.createBuffer();
  9053. buffer.capacity = capacity;
  9054. this.bindArrayBuffer(buffer);
  9055. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9056. return buffer;
  9057. };
  9058. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9059. this._gl.deleteBuffer(buffer);
  9060. };
  9061. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9062. this.bindArrayBuffer(instancesBuffer);
  9063. if (data) {
  9064. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9065. }
  9066. if (offsetLocations[0].index !== undefined) {
  9067. var stride = 0;
  9068. for (var i = 0; i < offsetLocations.length; i++) {
  9069. var ai = offsetLocations[i];
  9070. stride += ai.attributeSize * 4;
  9071. }
  9072. for (var i = 0; i < offsetLocations.length; i++) {
  9073. var ai = offsetLocations[i];
  9074. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9075. this._gl.enableVertexAttribArray(ai.index);
  9076. this._vertexAttribArraysEnabled[ai.index] = true;
  9077. }
  9078. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9079. this._gl.vertexAttribDivisor(ai.index, 1);
  9080. this._currentInstanceLocations.push(ai.index);
  9081. this._currentInstanceBuffers.push(instancesBuffer);
  9082. }
  9083. }
  9084. else {
  9085. for (var index = 0; index < 4; index++) {
  9086. var offsetLocation = offsetLocations[index];
  9087. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9088. this._gl.enableVertexAttribArray(offsetLocation);
  9089. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9090. }
  9091. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9092. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9093. this._currentInstanceLocations.push(offsetLocation);
  9094. this._currentInstanceBuffers.push(instancesBuffer);
  9095. }
  9096. }
  9097. };
  9098. Engine.prototype.applyStates = function () {
  9099. this._depthCullingState.apply(this._gl);
  9100. this._stencilState.apply(this._gl);
  9101. this._alphaState.apply(this._gl);
  9102. };
  9103. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9104. // Apply states
  9105. this.applyStates();
  9106. this._drawCalls.addCount(1, false);
  9107. // Render
  9108. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9109. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9110. if (instancesCount) {
  9111. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9112. return;
  9113. }
  9114. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9115. };
  9116. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9117. // Apply states
  9118. this.applyStates();
  9119. this._drawCalls.addCount(1, false);
  9120. if (instancesCount) {
  9121. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9122. return;
  9123. }
  9124. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9125. };
  9126. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9127. // Apply states
  9128. this.applyStates();
  9129. this._drawCalls.addCount(1, false);
  9130. if (instancesCount) {
  9131. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9132. return;
  9133. }
  9134. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9135. };
  9136. // Shaders
  9137. Engine.prototype._releaseEffect = function (effect) {
  9138. if (this._compiledEffects[effect._key]) {
  9139. delete this._compiledEffects[effect._key];
  9140. if (effect.getProgram()) {
  9141. this._gl.deleteProgram(effect.getProgram());
  9142. }
  9143. }
  9144. };
  9145. /**
  9146. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9147. * @param samplers An array of string used to represent textures
  9148. */
  9149. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9150. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9151. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9152. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9153. if (this._compiledEffects[name]) {
  9154. var compiledEffect = this._compiledEffects[name];
  9155. if (onCompiled && compiledEffect.isReady()) {
  9156. onCompiled(compiledEffect);
  9157. }
  9158. return compiledEffect;
  9159. }
  9160. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9161. effect._key = name;
  9162. this._compiledEffects[name] = effect;
  9163. return effect;
  9164. };
  9165. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9166. if (uniformsNames === void 0) { uniformsNames = []; }
  9167. if (samplers === void 0) { samplers = []; }
  9168. if (defines === void 0) { defines = ""; }
  9169. return this.createEffect({
  9170. vertex: "particles",
  9171. fragmentElement: fragmentName
  9172. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9173. };
  9174. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9175. context = context || this._gl;
  9176. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9177. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9178. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9179. var shaderProgram = context.createProgram();
  9180. context.attachShader(shaderProgram, vertexShader);
  9181. context.attachShader(shaderProgram, fragmentShader);
  9182. context.linkProgram(shaderProgram);
  9183. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9184. if (!linked) {
  9185. context.validateProgram(shaderProgram);
  9186. var error = context.getProgramInfoLog(shaderProgram);
  9187. if (error) {
  9188. throw new Error(error);
  9189. }
  9190. }
  9191. context.deleteShader(vertexShader);
  9192. context.deleteShader(fragmentShader);
  9193. return shaderProgram;
  9194. };
  9195. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9196. var results = [];
  9197. for (var index = 0; index < uniformsNames.length; index++) {
  9198. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9199. }
  9200. return results;
  9201. };
  9202. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9203. var results = [];
  9204. for (var index = 0; index < attributesNames.length; index++) {
  9205. try {
  9206. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9207. }
  9208. catch (e) {
  9209. results.push(-1);
  9210. }
  9211. }
  9212. return results;
  9213. };
  9214. Engine.prototype.enableEffect = function (effect) {
  9215. // Use program
  9216. this.setProgram(effect.getProgram());
  9217. this._currentEffect = effect;
  9218. if (effect.onBind) {
  9219. effect.onBind(effect);
  9220. }
  9221. effect.onBindObservable.notifyObservers(effect);
  9222. };
  9223. Engine.prototype.setIntArray = function (uniform, array) {
  9224. if (!uniform)
  9225. return;
  9226. this._gl.uniform1iv(uniform, array);
  9227. };
  9228. Engine.prototype.setIntArray2 = function (uniform, array) {
  9229. if (!uniform || array.length % 2 !== 0)
  9230. return;
  9231. this._gl.uniform2iv(uniform, array);
  9232. };
  9233. Engine.prototype.setIntArray3 = function (uniform, array) {
  9234. if (!uniform || array.length % 3 !== 0)
  9235. return;
  9236. this._gl.uniform3iv(uniform, array);
  9237. };
  9238. Engine.prototype.setIntArray4 = function (uniform, array) {
  9239. if (!uniform || array.length % 4 !== 0)
  9240. return;
  9241. this._gl.uniform4iv(uniform, array);
  9242. };
  9243. Engine.prototype.setFloatArray = function (uniform, array) {
  9244. if (!uniform)
  9245. return;
  9246. this._gl.uniform1fv(uniform, array);
  9247. };
  9248. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9249. if (!uniform || array.length % 2 !== 0)
  9250. return;
  9251. this._gl.uniform2fv(uniform, array);
  9252. };
  9253. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9254. if (!uniform || array.length % 3 !== 0)
  9255. return;
  9256. this._gl.uniform3fv(uniform, array);
  9257. };
  9258. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9259. if (!uniform || array.length % 4 !== 0)
  9260. return;
  9261. this._gl.uniform4fv(uniform, array);
  9262. };
  9263. Engine.prototype.setArray = function (uniform, array) {
  9264. if (!uniform)
  9265. return;
  9266. this._gl.uniform1fv(uniform, array);
  9267. };
  9268. Engine.prototype.setArray2 = function (uniform, array) {
  9269. if (!uniform || array.length % 2 !== 0)
  9270. return;
  9271. this._gl.uniform2fv(uniform, array);
  9272. };
  9273. Engine.prototype.setArray3 = function (uniform, array) {
  9274. if (!uniform || array.length % 3 !== 0)
  9275. return;
  9276. this._gl.uniform3fv(uniform, array);
  9277. };
  9278. Engine.prototype.setArray4 = function (uniform, array) {
  9279. if (!uniform || array.length % 4 !== 0)
  9280. return;
  9281. this._gl.uniform4fv(uniform, array);
  9282. };
  9283. Engine.prototype.setMatrices = function (uniform, matrices) {
  9284. if (!uniform)
  9285. return;
  9286. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9287. };
  9288. Engine.prototype.setMatrix = function (uniform, matrix) {
  9289. if (!uniform)
  9290. return;
  9291. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9292. };
  9293. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9294. if (!uniform)
  9295. return;
  9296. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9297. };
  9298. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9299. if (!uniform)
  9300. return;
  9301. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9302. };
  9303. Engine.prototype.setFloat = function (uniform, value) {
  9304. if (!uniform)
  9305. return;
  9306. this._gl.uniform1f(uniform, value);
  9307. };
  9308. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9309. if (!uniform)
  9310. return;
  9311. this._gl.uniform2f(uniform, x, y);
  9312. };
  9313. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9314. if (!uniform)
  9315. return;
  9316. this._gl.uniform3f(uniform, x, y, z);
  9317. };
  9318. Engine.prototype.setBool = function (uniform, bool) {
  9319. if (!uniform)
  9320. return;
  9321. this._gl.uniform1i(uniform, bool);
  9322. };
  9323. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9324. if (!uniform)
  9325. return;
  9326. this._gl.uniform4f(uniform, x, y, z, w);
  9327. };
  9328. Engine.prototype.setColor3 = function (uniform, color3) {
  9329. if (!uniform)
  9330. return;
  9331. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9332. };
  9333. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9334. if (!uniform)
  9335. return;
  9336. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9337. };
  9338. // States
  9339. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9340. if (zOffset === void 0) { zOffset = 0; }
  9341. if (reverseSide === void 0) { reverseSide = false; }
  9342. // Culling
  9343. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9344. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9345. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9346. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9347. if (culling) {
  9348. this._depthCullingState.cullFace = cullFace;
  9349. this._depthCullingState.cull = true;
  9350. }
  9351. else {
  9352. this._depthCullingState.cull = false;
  9353. }
  9354. }
  9355. // Z offset
  9356. this.setZOffset(zOffset);
  9357. };
  9358. Engine.prototype.setZOffset = function (value) {
  9359. this._depthCullingState.zOffset = value;
  9360. };
  9361. Engine.prototype.getZOffset = function () {
  9362. return this._depthCullingState.zOffset;
  9363. };
  9364. Engine.prototype.setDepthBuffer = function (enable) {
  9365. this._depthCullingState.depthTest = enable;
  9366. };
  9367. Engine.prototype.getDepthWrite = function () {
  9368. return this._depthCullingState.depthMask;
  9369. };
  9370. Engine.prototype.setDepthWrite = function (enable) {
  9371. this._depthCullingState.depthMask = enable;
  9372. };
  9373. Engine.prototype.setColorWrite = function (enable) {
  9374. this._gl.colorMask(enable, enable, enable, enable);
  9375. };
  9376. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9377. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9378. };
  9379. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9380. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9381. if (this._alphaMode === mode) {
  9382. return;
  9383. }
  9384. switch (mode) {
  9385. case Engine.ALPHA_DISABLE:
  9386. this._alphaState.alphaBlend = false;
  9387. break;
  9388. case Engine.ALPHA_PREMULTIPLIED:
  9389. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9390. this._alphaState.alphaBlend = true;
  9391. break;
  9392. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9393. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9394. this._alphaState.alphaBlend = true;
  9395. break;
  9396. case Engine.ALPHA_COMBINE:
  9397. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9398. this._alphaState.alphaBlend = true;
  9399. break;
  9400. case Engine.ALPHA_ONEONE:
  9401. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9402. this._alphaState.alphaBlend = true;
  9403. break;
  9404. case Engine.ALPHA_ADD:
  9405. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9406. this._alphaState.alphaBlend = true;
  9407. break;
  9408. case Engine.ALPHA_SUBTRACT:
  9409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9410. this._alphaState.alphaBlend = true;
  9411. break;
  9412. case Engine.ALPHA_MULTIPLY:
  9413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9414. this._alphaState.alphaBlend = true;
  9415. break;
  9416. case Engine.ALPHA_MAXIMIZED:
  9417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9418. this._alphaState.alphaBlend = true;
  9419. break;
  9420. case Engine.ALPHA_INTERPOLATE:
  9421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9422. this._alphaState.alphaBlend = true;
  9423. break;
  9424. case Engine.ALPHA_SCREENMODE:
  9425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9426. this._alphaState.alphaBlend = true;
  9427. break;
  9428. }
  9429. if (!noDepthWriteChange) {
  9430. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9431. }
  9432. this._alphaMode = mode;
  9433. };
  9434. Engine.prototype.getAlphaMode = function () {
  9435. return this._alphaMode;
  9436. };
  9437. Engine.prototype.setAlphaTesting = function (enable) {
  9438. this._alphaTest = enable;
  9439. };
  9440. Engine.prototype.getAlphaTesting = function () {
  9441. return !!this._alphaTest;
  9442. };
  9443. // Textures
  9444. Engine.prototype.wipeCaches = function (bruteForce) {
  9445. if (this.preventCacheWipeBetweenFrames) {
  9446. return;
  9447. }
  9448. this.resetTextureCache();
  9449. this._currentEffect = null;
  9450. // 6/8/2017: deltakosh: Should not be required anymore.
  9451. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9452. if (bruteForce) {
  9453. this._currentProgram = null;
  9454. this._stencilState.reset();
  9455. this._depthCullingState.reset();
  9456. this.setDepthFunctionToLessOrEqual();
  9457. this._alphaState.reset();
  9458. }
  9459. this._cachedVertexBuffers = null;
  9460. this._cachedIndexBuffer = null;
  9461. this._cachedEffectForVertexBuffers = null;
  9462. this._unbindVertexArrayObject();
  9463. this.bindIndexBuffer(null);
  9464. this.bindArrayBuffer(null);
  9465. };
  9466. /**
  9467. * Set the compressed texture format to use, based on the formats you have, and the formats
  9468. * supported by the hardware / browser.
  9469. *
  9470. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9471. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9472. * to API arguments needed to compressed textures. This puts the burden on the container
  9473. * generator to house the arcane code for determining these for current & future formats.
  9474. *
  9475. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9476. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9477. *
  9478. * Note: The result of this call is not taken into account when a texture is base64.
  9479. *
  9480. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9481. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9482. *
  9483. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9484. * @returns The extension selected.
  9485. */
  9486. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9487. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9488. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9489. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9490. return this._textureFormatInUse = this._texturesSupported[i];
  9491. }
  9492. }
  9493. }
  9494. // actively set format to nothing, to allow this to be called more than once
  9495. // and possibly fail the 2nd time
  9496. return this._textureFormatInUse = null;
  9497. };
  9498. Engine.prototype._createTexture = function () {
  9499. return this._gl.createTexture();
  9500. };
  9501. /**
  9502. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9503. * @param {string} urlArg- This contains one of the following:
  9504. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9505. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9506. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9507. *
  9508. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9509. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9510. * @param {Scene} scene- Needed for loading to the correct scene.
  9511. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9512. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9513. * @param {callback} onError- Optional callback to be called upon failure.
  9514. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9515. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9516. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9517. *
  9518. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9519. */
  9520. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9521. var _this = this;
  9522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9523. if (onLoad === void 0) { onLoad = null; }
  9524. if (onError === void 0) { onError = null; }
  9525. if (buffer === void 0) { buffer = null; }
  9526. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9527. var fromData = url.substr(0, 5) === "data:";
  9528. var fromBlob = url.substr(0, 5) === "blob:";
  9529. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9530. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9531. // establish the file extension, if possible
  9532. var lastDot = url.lastIndexOf('.');
  9533. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9534. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9535. var isTGA = (extension === ".tga");
  9536. // determine if a ktx file should be substituted
  9537. var isKTX = false;
  9538. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9539. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9540. isKTX = true;
  9541. }
  9542. if (scene) {
  9543. scene._addPendingData(texture);
  9544. }
  9545. texture.url = url;
  9546. texture.generateMipMaps = !noMipmap;
  9547. texture.samplingMode = samplingMode;
  9548. texture.invertY = invertY;
  9549. if (!this._doNotHandleContextLost) {
  9550. // Keep a link to the buffer only if we plan to handle context lost
  9551. texture._buffer = buffer;
  9552. }
  9553. if (onLoad) {
  9554. texture.onLoadedObservable.add(onLoad);
  9555. }
  9556. if (!fallBack)
  9557. this._internalTexturesCache.push(texture);
  9558. var onerror = function () {
  9559. if (scene) {
  9560. scene._removePendingData(texture);
  9561. }
  9562. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9563. if (isKTX) {
  9564. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9565. }
  9566. else if (onError) {
  9567. onError();
  9568. }
  9569. };
  9570. var callback;
  9571. // processing for non-image formats
  9572. if (isKTX || isTGA || isDDS) {
  9573. if (isKTX) {
  9574. callback = function (data) {
  9575. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9576. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9577. ktx.uploadLevels(_this._gl, !noMipmap);
  9578. return false;
  9579. }, samplingMode);
  9580. };
  9581. }
  9582. else if (isTGA) {
  9583. callback = function (arrayBuffer) {
  9584. var data = new Uint8Array(arrayBuffer);
  9585. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9586. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9587. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9588. return false;
  9589. }, samplingMode);
  9590. };
  9591. }
  9592. else if (isDDS) {
  9593. callback = function (data) {
  9594. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9595. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9596. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9597. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9598. return false;
  9599. }, samplingMode);
  9600. };
  9601. }
  9602. if (!buffer) {
  9603. BABYLON.Tools.LoadFile(url, function (data) {
  9604. callback(data);
  9605. }, null, scene ? scene.database : null, true, onerror);
  9606. }
  9607. else {
  9608. callback(buffer);
  9609. }
  9610. // image format processing
  9611. }
  9612. else {
  9613. var onload = function (img) {
  9614. if (fromBlob && !_this._doNotHandleContextLost) {
  9615. // We need to store the image if we need to rebuild the texture
  9616. // in case of a webgl context lost
  9617. texture._buffer = img;
  9618. }
  9619. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9620. var gl = _this._gl;
  9621. var isPot = (img.width === potWidth && img.height === potHeight);
  9622. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9623. if (isPot) {
  9624. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9625. return false;
  9626. }
  9627. // Using shaders to rescale because canvas.drawImage is lossy
  9628. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9629. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9630. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9632. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9633. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9635. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9636. _this._releaseTexture(source);
  9637. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9638. continuationCallback();
  9639. });
  9640. return true;
  9641. }, samplingMode);
  9642. };
  9643. if (!fromData || isBase64)
  9644. if (buffer instanceof HTMLImageElement) {
  9645. onload(buffer);
  9646. }
  9647. else {
  9648. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9649. }
  9650. else if (buffer instanceof Array || typeof buffer === "string")
  9651. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9652. else
  9653. onload(buffer);
  9654. }
  9655. return texture;
  9656. };
  9657. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9658. var _this = this;
  9659. var rtt = this.createRenderTargetTexture({
  9660. width: destination.width,
  9661. height: destination.height,
  9662. }, {
  9663. generateMipMaps: false,
  9664. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9665. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9666. generateDepthBuffer: false,
  9667. generateStencilBuffer: false
  9668. });
  9669. if (!this._rescalePostProcess) {
  9670. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9671. }
  9672. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9673. _this._rescalePostProcess.onApply = function (effect) {
  9674. effect._bindTexture("textureSampler", source);
  9675. };
  9676. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9677. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9678. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9679. _this.unBindFramebuffer(rtt);
  9680. _this._releaseTexture(rtt);
  9681. if (onComplete) {
  9682. onComplete();
  9683. }
  9684. });
  9685. };
  9686. Engine.prototype._getInternalFormat = function (format) {
  9687. var internalFormat = this._gl.RGBA;
  9688. switch (format) {
  9689. case Engine.TEXTUREFORMAT_ALPHA:
  9690. internalFormat = this._gl.ALPHA;
  9691. break;
  9692. case Engine.TEXTUREFORMAT_LUMINANCE:
  9693. internalFormat = this._gl.LUMINANCE;
  9694. break;
  9695. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9696. internalFormat = this._gl.LUMINANCE_ALPHA;
  9697. break;
  9698. case Engine.TEXTUREFORMAT_RGB:
  9699. internalFormat = this._gl.RGB;
  9700. break;
  9701. case Engine.TEXTUREFORMAT_RGBA:
  9702. internalFormat = this._gl.RGBA;
  9703. break;
  9704. }
  9705. return internalFormat;
  9706. };
  9707. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9708. if (compression === void 0) { compression = null; }
  9709. var internalFormat = this._getInternalFormat(format);
  9710. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9711. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9712. if (!this._doNotHandleContextLost) {
  9713. texture._bufferView = data;
  9714. texture.format = format;
  9715. texture.invertY = invertY;
  9716. texture._compression = compression;
  9717. }
  9718. if (texture.width % 4 !== 0) {
  9719. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9720. }
  9721. if (compression) {
  9722. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9723. }
  9724. else {
  9725. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9726. }
  9727. if (texture.generateMipMaps) {
  9728. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9729. }
  9730. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9731. this.resetTextureCache();
  9732. texture.isReady = true;
  9733. };
  9734. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9735. if (compression === void 0) { compression = null; }
  9736. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9737. texture.baseWidth = width;
  9738. texture.baseHeight = height;
  9739. texture.width = width;
  9740. texture.height = height;
  9741. texture.format = format;
  9742. texture.generateMipMaps = generateMipMaps;
  9743. texture.samplingMode = samplingMode;
  9744. texture.invertY = invertY;
  9745. texture._compression = compression;
  9746. if (!this._doNotHandleContextLost) {
  9747. texture._bufferView = data;
  9748. }
  9749. this.updateRawTexture(texture, data, format, invertY, compression);
  9750. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9751. // Filters
  9752. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9753. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9754. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9755. if (generateMipMaps) {
  9756. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9757. }
  9758. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9759. this._internalTexturesCache.push(texture);
  9760. return texture;
  9761. };
  9762. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9763. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9764. texture.baseWidth = width;
  9765. texture.baseHeight = height;
  9766. if (generateMipMaps) {
  9767. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9768. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9769. }
  9770. this.resetTextureCache();
  9771. texture.width = width;
  9772. texture.height = height;
  9773. texture.isReady = false;
  9774. texture.generateMipMaps = generateMipMaps;
  9775. texture.samplingMode = samplingMode;
  9776. this.updateTextureSamplingMode(samplingMode, texture);
  9777. this._internalTexturesCache.push(texture);
  9778. return texture;
  9779. };
  9780. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9781. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9782. if (texture.isCube) {
  9783. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9784. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9785. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9786. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9787. }
  9788. else {
  9789. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9792. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9793. }
  9794. texture.samplingMode = samplingMode;
  9795. };
  9796. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9797. if (premulAlpha === void 0) { premulAlpha = false; }
  9798. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9799. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9800. if (premulAlpha) {
  9801. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9802. }
  9803. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9804. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9805. if (texture.generateMipMaps) {
  9806. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9807. }
  9808. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9809. if (premulAlpha) {
  9810. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9811. }
  9812. this.resetTextureCache();
  9813. texture.isReady = true;
  9814. };
  9815. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9816. if (texture._isDisabled) {
  9817. return;
  9818. }
  9819. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9820. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9821. try {
  9822. // Testing video texture support
  9823. if (this._videoTextureSupported === undefined) {
  9824. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9825. if (this._gl.getError() !== 0) {
  9826. this._videoTextureSupported = false;
  9827. }
  9828. else {
  9829. this._videoTextureSupported = true;
  9830. }
  9831. }
  9832. // Copy video through the current working canvas if video texture is not supported
  9833. if (!this._videoTextureSupported) {
  9834. if (!texture._workingCanvas) {
  9835. texture._workingCanvas = document.createElement("canvas");
  9836. texture._workingContext = texture._workingCanvas.getContext("2d");
  9837. texture._workingCanvas.width = texture.width;
  9838. texture._workingCanvas.height = texture.height;
  9839. }
  9840. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  9841. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9842. }
  9843. else {
  9844. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9845. }
  9846. if (texture.generateMipMaps) {
  9847. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9848. }
  9849. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9850. this.resetTextureCache();
  9851. texture.isReady = true;
  9852. }
  9853. catch (ex) {
  9854. // Something unexpected
  9855. // Let's disable the texture
  9856. texture._isDisabled = true;
  9857. }
  9858. };
  9859. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9860. var fullOptions = new RenderTargetCreationOptions();
  9861. if (options !== undefined && typeof options === "object") {
  9862. fullOptions.generateMipMaps = options.generateMipMaps;
  9863. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9864. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  9865. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  9866. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  9867. }
  9868. else {
  9869. fullOptions.generateMipMaps = options;
  9870. fullOptions.generateDepthBuffer = true;
  9871. fullOptions.generateStencilBuffer = false;
  9872. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9873. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9874. }
  9875. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9876. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9877. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9878. }
  9879. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9880. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9881. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9882. }
  9883. var gl = this._gl;
  9884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  9885. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9886. var width = size.width || size;
  9887. var height = size.height || size;
  9888. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  9889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9890. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9891. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9892. }
  9893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9897. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  9898. // Create the framebuffer
  9899. var framebuffer = gl.createFramebuffer();
  9900. this.bindUnboundFramebuffer(framebuffer);
  9901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9902. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  9903. if (fullOptions.generateMipMaps) {
  9904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9905. }
  9906. // Unbind
  9907. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9909. this.bindUnboundFramebuffer(null);
  9910. texture._framebuffer = framebuffer;
  9911. texture.baseWidth = width;
  9912. texture.baseHeight = height;
  9913. texture.width = width;
  9914. texture.height = height;
  9915. texture.isReady = true;
  9916. texture.samples = 1;
  9917. texture.generateMipMaps = fullOptions.generateMipMaps;
  9918. texture.samplingMode = fullOptions.samplingMode;
  9919. texture.type = fullOptions.type;
  9920. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  9921. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  9922. this.resetTextureCache();
  9923. this._internalTexturesCache.push(texture);
  9924. return texture;
  9925. };
  9926. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9927. var generateMipMaps = false;
  9928. var generateDepthBuffer = true;
  9929. var generateStencilBuffer = false;
  9930. var generateDepthTexture = false;
  9931. var textureCount = 1;
  9932. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9933. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9934. var types = [], samplingModes = [];
  9935. if (options !== undefined) {
  9936. generateMipMaps = options.generateMipMaps;
  9937. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9938. generateStencilBuffer = options.generateStencilBuffer;
  9939. generateDepthTexture = options.generateDepthTexture;
  9940. textureCount = options.textureCount || 1;
  9941. if (options.types) {
  9942. types = options.types;
  9943. }
  9944. if (options.samplingModes) {
  9945. samplingModes = options.samplingModes;
  9946. }
  9947. }
  9948. var gl = this._gl;
  9949. // Create the framebuffer
  9950. var framebuffer = gl.createFramebuffer();
  9951. this.bindUnboundFramebuffer(framebuffer);
  9952. var width = size.width || size;
  9953. var height = size.height || size;
  9954. var textures = [];
  9955. var attachments = [];
  9956. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9957. for (var i = 0; i < textureCount; i++) {
  9958. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9959. var type = types[i] || defaultType;
  9960. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9961. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9962. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9963. }
  9964. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9965. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9966. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9967. }
  9968. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9969. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9970. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9971. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9972. }
  9973. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  9974. var attachment = gl["COLOR_ATTACHMENT" + i];
  9975. textures.push(texture);
  9976. attachments.push(attachment);
  9977. gl.activeTexture(gl["TEXTURE" + i]);
  9978. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  9979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9983. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9984. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9985. if (generateMipMaps) {
  9986. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9987. }
  9988. // Unbind
  9989. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9990. texture._framebuffer = framebuffer;
  9991. texture._depthStencilBuffer = depthStencilBuffer;
  9992. texture.baseWidth = width;
  9993. texture.baseHeight = height;
  9994. texture.width = width;
  9995. texture.height = height;
  9996. texture.isReady = true;
  9997. texture.samples = 1;
  9998. texture.generateMipMaps = generateMipMaps;
  9999. texture.samplingMode = samplingMode;
  10000. texture.type = type;
  10001. texture._generateDepthBuffer = generateDepthBuffer;
  10002. texture._generateStencilBuffer = generateStencilBuffer;
  10003. this._internalTexturesCache.push(texture);
  10004. }
  10005. if (generateDepthTexture) {
  10006. // Depth texture
  10007. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10008. gl.activeTexture(gl.TEXTURE0);
  10009. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10014. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10016. depthTexture._framebuffer = framebuffer;
  10017. depthTexture.baseWidth = width;
  10018. depthTexture.baseHeight = height;
  10019. depthTexture.width = width;
  10020. depthTexture.height = height;
  10021. depthTexture.isReady = true;
  10022. depthTexture.samples = 1;
  10023. depthTexture.generateMipMaps = generateMipMaps;
  10024. depthTexture.samplingMode = gl.NEAREST;
  10025. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10026. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10027. textures.push(depthTexture);
  10028. this._internalTexturesCache.push(depthTexture);
  10029. }
  10030. gl.drawBuffers(attachments);
  10031. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10032. this.bindUnboundFramebuffer(null);
  10033. this.resetTextureCache();
  10034. return textures;
  10035. };
  10036. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10037. if (samples === void 0) { samples = 1; }
  10038. var depthStencilBuffer = null;
  10039. var gl = this._gl;
  10040. // Create the depth/stencil buffer
  10041. if (generateStencilBuffer) {
  10042. depthStencilBuffer = gl.createRenderbuffer();
  10043. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10044. if (samples > 1) {
  10045. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10046. }
  10047. else {
  10048. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10049. }
  10050. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10051. }
  10052. else if (generateDepthBuffer) {
  10053. depthStencilBuffer = gl.createRenderbuffer();
  10054. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10055. if (samples > 1) {
  10056. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10057. }
  10058. else {
  10059. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10060. }
  10061. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10062. }
  10063. return depthStencilBuffer;
  10064. };
  10065. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10066. if (this.webGLVersion < 2) {
  10067. return 1;
  10068. }
  10069. if (texture.samples === samples) {
  10070. return samples;
  10071. }
  10072. var gl = this._gl;
  10073. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10074. // Dispose previous render buffers
  10075. if (texture._depthStencilBuffer) {
  10076. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10077. }
  10078. if (texture._MSAAFramebuffer) {
  10079. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10080. }
  10081. if (texture._MSAARenderBuffer) {
  10082. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10083. }
  10084. if (samples > 1) {
  10085. texture._MSAAFramebuffer = gl.createFramebuffer();
  10086. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10087. var colorRenderbuffer = gl.createRenderbuffer();
  10088. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10089. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10090. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10091. texture._MSAARenderBuffer = colorRenderbuffer;
  10092. }
  10093. else {
  10094. this.bindUnboundFramebuffer(texture._framebuffer);
  10095. }
  10096. texture.samples = samples;
  10097. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10098. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10099. this.bindUnboundFramebuffer(null);
  10100. return samples;
  10101. };
  10102. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10103. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10104. };
  10105. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10106. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10107. };
  10108. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10109. var gl = this._gl;
  10110. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10111. var generateMipMaps = true;
  10112. var generateDepthBuffer = true;
  10113. var generateStencilBuffer = false;
  10114. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10115. if (options !== undefined) {
  10116. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10117. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10118. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10119. if (options.samplingMode !== undefined) {
  10120. samplingMode = options.samplingMode;
  10121. }
  10122. }
  10123. texture.isCube = true;
  10124. texture.generateMipMaps = generateMipMaps;
  10125. texture.samples = 1;
  10126. texture.samplingMode = samplingMode;
  10127. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10128. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10129. for (var face = 0; face < 6; face++) {
  10130. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10131. }
  10132. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10134. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10135. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10136. // Create the framebuffer
  10137. var framebuffer = gl.createFramebuffer();
  10138. this.bindUnboundFramebuffer(framebuffer);
  10139. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10140. // Mipmaps
  10141. if (texture.generateMipMaps) {
  10142. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10143. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10144. }
  10145. // Unbind
  10146. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10147. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10148. this.bindUnboundFramebuffer(null);
  10149. texture._framebuffer = framebuffer;
  10150. texture.width = size;
  10151. texture.height = size;
  10152. texture.isReady = true;
  10153. this.resetTextureCache();
  10154. this._internalTexturesCache.push(texture);
  10155. return texture;
  10156. };
  10157. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10158. var _this = this;
  10159. if (onError === void 0) { onError = null; }
  10160. if (forcedExtension === void 0) { forcedExtension = null; }
  10161. var callback = function (loadData) {
  10162. if (!loadData) {
  10163. if (onLoad) {
  10164. onLoad(null);
  10165. }
  10166. return;
  10167. }
  10168. var texture = loadData.texture;
  10169. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10170. texture._lodGenerationScale = scale;
  10171. texture._lodGenerationOffset = offset;
  10172. if (_this._caps.textureLOD) {
  10173. // Do not add extra process if texture lod is supported.
  10174. if (onLoad) {
  10175. onLoad(texture);
  10176. }
  10177. return;
  10178. }
  10179. var mipSlices = 3;
  10180. var gl = _this._gl;
  10181. var width = loadData.width;
  10182. if (!width) {
  10183. return;
  10184. }
  10185. var textures = [];
  10186. for (var i = 0; i < mipSlices; i++) {
  10187. //compute LOD from even spacing in smoothness (matching shader calculation)
  10188. var smoothness = i / (mipSlices - 1);
  10189. var roughness = 1 - smoothness;
  10190. var minLODIndex = offset; // roughness = 0
  10191. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10192. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10193. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10194. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10195. glTextureFromLod.isCube = true;
  10196. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10198. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10199. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10200. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10201. if (loadData.isDDS) {
  10202. var info = loadData.info;
  10203. var data = loadData.data;
  10204. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10205. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10206. }
  10207. else {
  10208. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10209. }
  10210. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10211. // Wrap in a base texture for easy binding.
  10212. var lodTexture = new BABYLON.BaseTexture(scene);
  10213. lodTexture.isCube = true;
  10214. lodTexture._texture = glTextureFromLod;
  10215. glTextureFromLod.isReady = true;
  10216. textures.push(lodTexture);
  10217. }
  10218. texture._lodTextureHigh = textures[2];
  10219. texture._lodTextureMid = textures[1];
  10220. texture._lodTextureLow = textures[0];
  10221. if (onLoad) {
  10222. onLoad(texture);
  10223. }
  10224. };
  10225. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10226. };
  10227. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10228. var _this = this;
  10229. if (onLoad === void 0) { onLoad = null; }
  10230. if (onError === void 0) { onError = null; }
  10231. if (forcedExtension === void 0) { forcedExtension = null; }
  10232. var gl = this._gl;
  10233. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10234. texture.isCube = true;
  10235. texture.url = rootUrl;
  10236. texture.generateMipMaps = !noMipmap;
  10237. if (!this._doNotHandleContextLost) {
  10238. texture._extension = forcedExtension;
  10239. texture._files = files;
  10240. }
  10241. var isKTX = false;
  10242. var isDDS = false;
  10243. var lastDot = rootUrl.lastIndexOf('.');
  10244. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10245. if (this._textureFormatInUse) {
  10246. extension = this._textureFormatInUse;
  10247. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10248. isKTX = true;
  10249. }
  10250. else {
  10251. isDDS = (extension === ".dds");
  10252. }
  10253. if (isKTX) {
  10254. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10255. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10256. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10257. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10258. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10259. ktx.uploadLevels(_this._gl, !noMipmap);
  10260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10264. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10265. _this.resetTextureCache();
  10266. texture.width = ktx.pixelWidth;
  10267. texture.height = ktx.pixelHeight;
  10268. texture.isReady = true;
  10269. }, null, null, true, onError);
  10270. }
  10271. else if (isDDS) {
  10272. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10273. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10274. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10275. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10276. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10277. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10278. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10279. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10280. }
  10281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10285. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10286. _this.resetTextureCache();
  10287. texture.width = info.width;
  10288. texture.height = info.height;
  10289. texture.isReady = true;
  10290. texture.type = info.textureType;
  10291. if (onLoad) {
  10292. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10293. }
  10294. }, null, null, true, onError);
  10295. }
  10296. else {
  10297. cascadeLoad(rootUrl, scene, function (imgs) {
  10298. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10299. var height = width;
  10300. _this._prepareWorkingCanvas();
  10301. _this._workingCanvas.width = width;
  10302. _this._workingCanvas.height = height;
  10303. var faces = [
  10304. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10305. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10306. ];
  10307. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10308. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10309. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10310. for (var index = 0; index < faces.length; index++) {
  10311. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10312. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10313. }
  10314. if (!noMipmap) {
  10315. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10316. }
  10317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10321. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10322. _this.resetTextureCache();
  10323. texture.width = width;
  10324. texture.height = height;
  10325. texture.isReady = true;
  10326. texture.format = format;
  10327. texture.onLoadedObservable.notifyObservers(texture);
  10328. texture.onLoadedObservable.clear();
  10329. if (onLoad) {
  10330. onLoad();
  10331. }
  10332. }, files, onError);
  10333. }
  10334. this._internalTexturesCache.push(texture);
  10335. return texture;
  10336. };
  10337. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10338. if (compression === void 0) { compression = null; }
  10339. if (level === void 0) { level = 0; }
  10340. var gl = this._gl;
  10341. var textureType = this._getWebGLTextureType(type);
  10342. var internalFormat = this._getInternalFormat(format);
  10343. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10344. var needConversion = false;
  10345. if (internalFormat === gl.RGB) {
  10346. internalFormat = gl.RGBA;
  10347. needConversion = true;
  10348. }
  10349. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10350. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10351. if (texture.width % 4 !== 0) {
  10352. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10353. }
  10354. // Data are known to be in +X +Y +Z -X -Y -Z
  10355. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10356. var faceData = data[faceIndex];
  10357. if (compression) {
  10358. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10359. }
  10360. else {
  10361. if (needConversion) {
  10362. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10363. }
  10364. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10365. }
  10366. }
  10367. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10368. if (isPot && texture.generateMipMaps && level === 0) {
  10369. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10370. }
  10371. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10372. this.resetTextureCache();
  10373. texture.isReady = true;
  10374. };
  10375. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10376. if (compression === void 0) { compression = null; }
  10377. var gl = this._gl;
  10378. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10379. texture.isCube = true;
  10380. texture.generateMipMaps = generateMipMaps;
  10381. texture.format = format;
  10382. texture.type = type;
  10383. if (!this._doNotHandleContextLost) {
  10384. texture._bufferViewArray = data;
  10385. }
  10386. var textureType = this._getWebGLTextureType(type);
  10387. var internalFormat = this._getInternalFormat(format);
  10388. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10389. var needConversion = false;
  10390. if (internalFormat === gl.RGB) {
  10391. internalFormat = gl.RGBA;
  10392. needConversion = true;
  10393. }
  10394. var width = size;
  10395. var height = width;
  10396. texture.width = width;
  10397. texture.height = height;
  10398. // Double check on POT to generate Mips.
  10399. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10400. if (!isPot) {
  10401. generateMipMaps = false;
  10402. }
  10403. // Upload data if needed. The texture won't be ready until then.
  10404. if (data) {
  10405. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10406. }
  10407. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10408. // Filters
  10409. if (data && generateMipMaps) {
  10410. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10411. }
  10412. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10415. }
  10416. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10419. }
  10420. else {
  10421. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10424. }
  10425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10427. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10428. return texture;
  10429. };
  10430. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10431. var _this = this;
  10432. if (onLoad === void 0) { onLoad = null; }
  10433. if (onError === void 0) { onError = null; }
  10434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10435. if (invertY === void 0) { invertY = false; }
  10436. var gl = this._gl;
  10437. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10438. scene._addPendingData(texture);
  10439. texture.url = url;
  10440. this._internalTexturesCache.push(texture);
  10441. var onerror = function () {
  10442. scene._removePendingData(texture);
  10443. if (onError) {
  10444. onError();
  10445. }
  10446. };
  10447. var internalCallback = function (data) {
  10448. var width = texture.width;
  10449. var height = texture.height;
  10450. var faceDataArrays = callback(data);
  10451. if (mipmmapGenerator) {
  10452. var textureType = _this._getWebGLTextureType(type);
  10453. var internalFormat = _this._getInternalFormat(format);
  10454. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10455. var needConversion = false;
  10456. if (internalFormat === gl.RGB) {
  10457. internalFormat = gl.RGBA;
  10458. needConversion = true;
  10459. }
  10460. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10461. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10462. var mipData = mipmmapGenerator(faceDataArrays);
  10463. for (var level = 0; level < mipData.length; level++) {
  10464. var mipSize = width >> level;
  10465. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10466. var mipFaceData = mipData[level][faceIndex];
  10467. if (needConversion) {
  10468. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10469. }
  10470. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10471. }
  10472. }
  10473. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10474. }
  10475. else {
  10476. texture.generateMipMaps = !noMipmap;
  10477. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10478. }
  10479. texture.isReady = true;
  10480. _this.resetTextureCache();
  10481. scene._removePendingData(texture);
  10482. if (onLoad) {
  10483. onLoad();
  10484. }
  10485. };
  10486. BABYLON.Tools.LoadFile(url, function (data) {
  10487. internalCallback(data);
  10488. }, onerror, scene.database, true);
  10489. return texture;
  10490. };
  10491. ;
  10492. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10493. var gl = this._gl;
  10494. if (!gl) {
  10495. return;
  10496. }
  10497. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10500. if (!noMipmap && !isCompressed) {
  10501. gl.generateMipmap(gl.TEXTURE_2D);
  10502. }
  10503. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10504. this.resetTextureCache();
  10505. if (scene) {
  10506. scene._removePendingData(texture);
  10507. }
  10508. texture.onLoadedObservable.notifyObservers(texture);
  10509. texture.onLoadedObservable.clear();
  10510. };
  10511. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10512. var _this = this;
  10513. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10514. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10515. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10516. var gl = this._gl;
  10517. if (!gl) {
  10518. return;
  10519. }
  10520. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10521. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10522. texture.baseWidth = width;
  10523. texture.baseHeight = height;
  10524. texture.width = potWidth;
  10525. texture.height = potHeight;
  10526. texture.isReady = true;
  10527. if (processFunction(potWidth, potHeight, function () {
  10528. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10529. })) {
  10530. // Returning as texture needs extra async steps
  10531. return;
  10532. }
  10533. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10534. };
  10535. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10536. // Create new RGBA data container.
  10537. var rgbaData;
  10538. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10539. rgbaData = new Float32Array(width * height * 4);
  10540. }
  10541. else {
  10542. rgbaData = new Uint32Array(width * height * 4);
  10543. }
  10544. // Convert each pixel.
  10545. for (var x = 0; x < width; x++) {
  10546. for (var y = 0; y < height; y++) {
  10547. var index = (y * width + x) * 3;
  10548. var newIndex = (y * width + x) * 4;
  10549. // Map Old Value to new value.
  10550. rgbaData[newIndex + 0] = rgbData[index + 0];
  10551. rgbaData[newIndex + 1] = rgbData[index + 1];
  10552. rgbaData[newIndex + 2] = rgbData[index + 2];
  10553. // Add fully opaque alpha channel.
  10554. rgbaData[newIndex + 3] = 1;
  10555. }
  10556. }
  10557. return rgbaData;
  10558. };
  10559. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10560. var gl = this._gl;
  10561. if (texture._framebuffer) {
  10562. gl.deleteFramebuffer(texture._framebuffer);
  10563. texture._framebuffer = null;
  10564. }
  10565. if (texture._depthStencilBuffer) {
  10566. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10567. texture._depthStencilBuffer = null;
  10568. }
  10569. if (texture._MSAAFramebuffer) {
  10570. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10571. texture._MSAAFramebuffer = null;
  10572. }
  10573. if (texture._MSAARenderBuffer) {
  10574. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10575. texture._MSAARenderBuffer = null;
  10576. }
  10577. };
  10578. Engine.prototype._releaseTexture = function (texture) {
  10579. var gl = this._gl;
  10580. this._releaseFramebufferObjects(texture);
  10581. gl.deleteTexture(texture._webGLTexture);
  10582. // Unbind channels
  10583. this.unbindAllTextures();
  10584. var index = this._internalTexturesCache.indexOf(texture);
  10585. if (index !== -1) {
  10586. this._internalTexturesCache.splice(index, 1);
  10587. }
  10588. // Integrated fixed lod samplers.
  10589. if (texture._lodTextureHigh) {
  10590. texture._lodTextureHigh.dispose();
  10591. }
  10592. if (texture._lodTextureMid) {
  10593. texture._lodTextureMid.dispose();
  10594. }
  10595. if (texture._lodTextureLow) {
  10596. texture._lodTextureLow.dispose();
  10597. }
  10598. };
  10599. Engine.prototype.setProgram = function (program) {
  10600. if (this._currentProgram !== program) {
  10601. this._gl.useProgram(program);
  10602. this._currentProgram = program;
  10603. }
  10604. };
  10605. Engine.prototype.bindSamplers = function (effect) {
  10606. this.setProgram(effect.getProgram());
  10607. var samplers = effect.getSamplers();
  10608. for (var index = 0; index < samplers.length; index++) {
  10609. var uniform = effect.getUniform(samplers[index]);
  10610. this._gl.uniform1i(uniform, index);
  10611. }
  10612. this._currentEffect = null;
  10613. };
  10614. Engine.prototype.activateTexture = function (texture) {
  10615. if (this._activeTexture !== texture) {
  10616. this._gl.activeTexture(texture);
  10617. this._activeTexture = texture;
  10618. }
  10619. };
  10620. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10621. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10622. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10623. this._activeTexturesCache[this._activeTexture] = texture;
  10624. }
  10625. };
  10626. Engine.prototype._bindTexture = function (channel, texture) {
  10627. if (channel < 0) {
  10628. return;
  10629. }
  10630. this.activateTexture(this._gl.TEXTURE0 + channel);
  10631. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10632. };
  10633. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10634. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10635. };
  10636. Engine.prototype.unbindAllTextures = function () {
  10637. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10638. this.activateTexture(this._gl["TEXTURE" + channel]);
  10639. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10640. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10641. }
  10642. };
  10643. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10644. if (channel < 0) {
  10645. return;
  10646. }
  10647. this._gl.uniform1i(uniform, channel);
  10648. this._setTexture(channel, texture);
  10649. };
  10650. Engine.prototype._setTexture = function (channel, texture) {
  10651. // Not ready?
  10652. if (!texture) {
  10653. if (this._activeTexturesCache[channel] != null) {
  10654. this.activateTexture(this._gl["TEXTURE" + channel]);
  10655. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10656. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10657. }
  10658. return;
  10659. }
  10660. // Video
  10661. var alreadyActivated = false;
  10662. if (texture.video) {
  10663. this.activateTexture(this._gl["TEXTURE" + channel]);
  10664. alreadyActivated = true;
  10665. texture.update();
  10666. }
  10667. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10668. texture.delayLoad();
  10669. return;
  10670. }
  10671. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10672. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10673. if (this._activeTexturesCache[channel] === internalTexture) {
  10674. return;
  10675. }
  10676. if (!alreadyActivated) {
  10677. this.activateTexture(this._gl["TEXTURE" + channel]);
  10678. }
  10679. if (internalTexture.isCube) {
  10680. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10681. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10682. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10683. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10684. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10685. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10686. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10687. }
  10688. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10689. }
  10690. else {
  10691. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10692. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10693. internalTexture._cachedWrapU = texture.wrapU;
  10694. switch (texture.wrapU) {
  10695. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10696. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10697. break;
  10698. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10699. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10700. break;
  10701. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10702. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10703. break;
  10704. }
  10705. }
  10706. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10707. internalTexture._cachedWrapV = texture.wrapV;
  10708. switch (texture.wrapV) {
  10709. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10710. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10711. break;
  10712. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10713. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10714. break;
  10715. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10716. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10717. break;
  10718. }
  10719. }
  10720. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10721. }
  10722. };
  10723. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10724. if (channel < 0) {
  10725. return;
  10726. }
  10727. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10728. this._textureUnits = new Int32Array(textures.length);
  10729. }
  10730. for (var i = 0; i < textures.length; i++) {
  10731. this._textureUnits[i] = channel + i;
  10732. }
  10733. this._gl.uniform1iv(uniform, this._textureUnits);
  10734. for (var index = 0; index < textures.length; index++) {
  10735. this._setTexture(channel + index, textures[index]);
  10736. }
  10737. };
  10738. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10739. var internalTexture = texture.getInternalTexture();
  10740. if (!internalTexture) {
  10741. return;
  10742. }
  10743. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10744. var value = texture.anisotropicFilteringLevel;
  10745. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10746. value = 1;
  10747. }
  10748. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10749. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10750. internalTexture._cachedAnisotropicFilteringLevel = value;
  10751. }
  10752. };
  10753. Engine.prototype.readPixels = function (x, y, width, height) {
  10754. var data = new Uint8Array(height * width * 4);
  10755. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10756. return data;
  10757. };
  10758. /**
  10759. * Add an externaly attached data from its key.
  10760. * This method call will fail and return false, if such key already exists.
  10761. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10762. * @param key the unique key that identifies the data
  10763. * @param data the data object to associate to the key for this Engine instance
  10764. * @return true if no such key were already present and the data was added successfully, false otherwise
  10765. */
  10766. Engine.prototype.addExternalData = function (key, data) {
  10767. if (!this._externalData) {
  10768. this._externalData = new BABYLON.StringDictionary();
  10769. }
  10770. return this._externalData.add(key, data);
  10771. };
  10772. /**
  10773. * Get an externaly attached data from its key
  10774. * @param key the unique key that identifies the data
  10775. * @return the associated data, if present (can be null), or undefined if not present
  10776. */
  10777. Engine.prototype.getExternalData = function (key) {
  10778. if (!this._externalData) {
  10779. this._externalData = new BABYLON.StringDictionary();
  10780. }
  10781. return this._externalData.get(key);
  10782. };
  10783. /**
  10784. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10785. * @param key the unique key that identifies the data
  10786. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10787. * @return the associated data, can be null if the factory returned null.
  10788. */
  10789. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10790. if (!this._externalData) {
  10791. this._externalData = new BABYLON.StringDictionary();
  10792. }
  10793. return this._externalData.getOrAddWithFactory(key, factory);
  10794. };
  10795. /**
  10796. * Remove an externaly attached data from the Engine instance
  10797. * @param key the unique key that identifies the data
  10798. * @return true if the data was successfully removed, false if it doesn't exist
  10799. */
  10800. Engine.prototype.removeExternalData = function (key) {
  10801. if (!this._externalData) {
  10802. this._externalData = new BABYLON.StringDictionary();
  10803. }
  10804. return this._externalData.remove(key);
  10805. };
  10806. Engine.prototype.unbindAllAttributes = function () {
  10807. if (this._mustWipeVertexAttributes) {
  10808. this._mustWipeVertexAttributes = false;
  10809. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10810. this._gl.disableVertexAttribArray(i);
  10811. this._vertexAttribArraysEnabled[i] = false;
  10812. this._currentBufferPointers[i].active = false;
  10813. }
  10814. return;
  10815. }
  10816. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10817. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10818. continue;
  10819. }
  10820. this._gl.disableVertexAttribArray(i);
  10821. this._vertexAttribArraysEnabled[i] = false;
  10822. this._currentBufferPointers[i].active = false;
  10823. }
  10824. };
  10825. Engine.prototype.releaseEffects = function () {
  10826. for (var name in this._compiledEffects) {
  10827. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10828. }
  10829. this._compiledEffects = {};
  10830. };
  10831. // Dispose
  10832. Engine.prototype.dispose = function () {
  10833. this.hideLoadingUI();
  10834. this.stopRenderLoop();
  10835. // Release postProcesses
  10836. while (this.postProcesses.length) {
  10837. this.postProcesses[0].dispose();
  10838. }
  10839. // Empty texture
  10840. if (this._emptyTexture) {
  10841. this._releaseTexture(this._emptyTexture);
  10842. this._emptyTexture = null;
  10843. }
  10844. if (this._emptyCubeTexture) {
  10845. this._releaseTexture(this._emptyCubeTexture);
  10846. this._emptyCubeTexture = null;
  10847. }
  10848. // Rescale PP
  10849. if (this._rescalePostProcess) {
  10850. this._rescalePostProcess.dispose();
  10851. }
  10852. // Release scenes
  10853. while (this.scenes.length) {
  10854. this.scenes[0].dispose();
  10855. }
  10856. // Release audio engine
  10857. if (Engine.audioEngine) {
  10858. Engine.audioEngine.dispose();
  10859. }
  10860. // Release effects
  10861. this.releaseEffects();
  10862. // Unbind
  10863. this.unbindAllAttributes();
  10864. if (this._dummyFramebuffer) {
  10865. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10866. }
  10867. this._gl = null;
  10868. //WebVR
  10869. this.disableVR();
  10870. // Events
  10871. window.removeEventListener("blur", this._onBlur);
  10872. window.removeEventListener("focus", this._onFocus);
  10873. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  10874. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  10875. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10876. if (!this._doNotHandleContextLost) {
  10877. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  10878. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  10879. }
  10880. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10881. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10882. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10883. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10884. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10885. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10886. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10887. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10888. // Remove from Instances
  10889. var index = Engine.Instances.indexOf(this);
  10890. if (index >= 0) {
  10891. Engine.Instances.splice(index, 1);
  10892. }
  10893. this._workingCanvas = null;
  10894. this._workingContext = null;
  10895. this._currentBufferPointers = null;
  10896. this._renderingCanvas = null;
  10897. this._currentProgram = null;
  10898. this.onResizeObservable.clear();
  10899. this.onCanvasBlurObservable.clear();
  10900. BABYLON.Effect.ResetCache();
  10901. };
  10902. // Loading screen
  10903. Engine.prototype.displayLoadingUI = function () {
  10904. var loadingScreen = this.loadingScreen;
  10905. if (loadingScreen) {
  10906. loadingScreen.displayLoadingUI();
  10907. }
  10908. };
  10909. Engine.prototype.hideLoadingUI = function () {
  10910. var loadingScreen = this.loadingScreen;
  10911. if (loadingScreen) {
  10912. loadingScreen.hideLoadingUI();
  10913. }
  10914. };
  10915. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10916. get: function () {
  10917. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10918. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10919. return this._loadingScreen;
  10920. },
  10921. set: function (loadingScreen) {
  10922. this._loadingScreen = loadingScreen;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10928. set: function (text) {
  10929. this.loadingScreen.loadingUIText = text;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10935. set: function (color) {
  10936. this.loadingScreen.loadingUIBackgroundColor = color;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Engine.prototype.attachContextLostEvent = function (callback) {
  10942. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10943. };
  10944. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10945. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10946. };
  10947. Engine.prototype.getVertexShaderSource = function (program) {
  10948. var shaders = this._gl.getAttachedShaders(program);
  10949. return this._gl.getShaderSource(shaders[0]);
  10950. };
  10951. Engine.prototype.getFragmentShaderSource = function (program) {
  10952. var shaders = this._gl.getAttachedShaders(program);
  10953. return this._gl.getShaderSource(shaders[1]);
  10954. };
  10955. Engine.prototype.getError = function () {
  10956. return this._gl.getError();
  10957. };
  10958. // FPS
  10959. Engine.prototype.getFps = function () {
  10960. return this._fps;
  10961. };
  10962. Engine.prototype.getDeltaTime = function () {
  10963. return this._deltaTime;
  10964. };
  10965. Engine.prototype._measureFps = function () {
  10966. this._performanceMonitor.sampleFrame();
  10967. this._fps = this._performanceMonitor.averageFPS;
  10968. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10969. };
  10970. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10971. if (faceIndex === void 0) { faceIndex = -1; }
  10972. var gl = this._gl;
  10973. if (!this._dummyFramebuffer) {
  10974. this._dummyFramebuffer = gl.createFramebuffer();
  10975. }
  10976. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10977. if (faceIndex > -1) {
  10978. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10979. }
  10980. else {
  10981. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10982. }
  10983. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10984. var buffer;
  10985. switch (readType) {
  10986. case gl.UNSIGNED_BYTE:
  10987. buffer = new Uint8Array(4 * width * height);
  10988. readType = gl.UNSIGNED_BYTE;
  10989. break;
  10990. default:
  10991. buffer = new Float32Array(4 * width * height);
  10992. readType = gl.FLOAT;
  10993. break;
  10994. }
  10995. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10996. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  10997. return buffer;
  10998. };
  10999. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11000. if (this._webGLVersion > 1) {
  11001. return this._caps.colorBufferFloat;
  11002. }
  11003. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11004. };
  11005. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11006. if (this._webGLVersion > 1) {
  11007. return this._caps.colorBufferFloat;
  11008. }
  11009. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11010. };
  11011. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11012. Engine.prototype._canRenderToFramebuffer = function (type) {
  11013. var gl = this._gl;
  11014. //clear existing errors
  11015. while (gl.getError() !== gl.NO_ERROR) { }
  11016. var successful = true;
  11017. var texture = gl.createTexture();
  11018. gl.bindTexture(gl.TEXTURE_2D, texture);
  11019. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11022. var fb = gl.createFramebuffer();
  11023. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11025. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11026. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11027. successful = successful && (gl.getError() === gl.NO_ERROR);
  11028. //try render by clearing frame buffer's color buffer
  11029. if (successful) {
  11030. gl.clear(gl.COLOR_BUFFER_BIT);
  11031. successful = successful && (gl.getError() === gl.NO_ERROR);
  11032. }
  11033. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11034. if (successful) {
  11035. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11036. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11037. var readFormat = gl.RGBA;
  11038. var readType = gl.UNSIGNED_BYTE;
  11039. var buffer = new Uint8Array(4);
  11040. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11041. successful = successful && (gl.getError() === gl.NO_ERROR);
  11042. }
  11043. //clean up
  11044. gl.deleteTexture(texture);
  11045. gl.deleteFramebuffer(fb);
  11046. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11047. //clear accumulated errors
  11048. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11049. return successful;
  11050. };
  11051. Engine.prototype._getWebGLTextureType = function (type) {
  11052. if (type === Engine.TEXTURETYPE_FLOAT) {
  11053. return this._gl.FLOAT;
  11054. }
  11055. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11056. // Add Half Float Constant.
  11057. return this._gl.HALF_FLOAT_OES;
  11058. }
  11059. return this._gl.UNSIGNED_BYTE;
  11060. };
  11061. ;
  11062. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11063. if (this._webGLVersion === 1) {
  11064. return this._gl.RGBA;
  11065. }
  11066. if (type === Engine.TEXTURETYPE_FLOAT) {
  11067. return this._gl.RGBA32F;
  11068. }
  11069. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11070. return this._gl.RGBA16F;
  11071. }
  11072. return this._gl.RGBA;
  11073. };
  11074. ;
  11075. Engine.prototype.createQuery = function () {
  11076. return this._gl.createQuery();
  11077. };
  11078. Engine.prototype.deleteQuery = function (query) {
  11079. this._gl.deleteQuery(query);
  11080. return this;
  11081. };
  11082. Engine.prototype.isQueryResultAvailable = function (query) {
  11083. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11084. };
  11085. Engine.prototype.getQueryResult = function (query) {
  11086. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11087. };
  11088. Engine.prototype.beginQuery = function (algorithmType, query) {
  11089. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11090. this._gl.beginQuery(glAlgorithm, query);
  11091. };
  11092. Engine.prototype.endQuery = function (algorithmType) {
  11093. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11094. this._gl.endQuery(glAlgorithm);
  11095. return this;
  11096. };
  11097. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11098. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11099. };
  11100. // Statics
  11101. Engine.isSupported = function () {
  11102. try {
  11103. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11104. if (navigator.isCocoonJS) {
  11105. return true;
  11106. }
  11107. var tempcanvas = document.createElement("canvas");
  11108. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11109. return gl != null && !!window.WebGLRenderingContext;
  11110. }
  11111. catch (e) {
  11112. return false;
  11113. }
  11114. };
  11115. Engine.Instances = new Array();
  11116. // Const statics
  11117. Engine._ALPHA_DISABLE = 0;
  11118. Engine._ALPHA_ADD = 1;
  11119. Engine._ALPHA_COMBINE = 2;
  11120. Engine._ALPHA_SUBTRACT = 3;
  11121. Engine._ALPHA_MULTIPLY = 4;
  11122. Engine._ALPHA_MAXIMIZED = 5;
  11123. Engine._ALPHA_ONEONE = 6;
  11124. Engine._ALPHA_PREMULTIPLIED = 7;
  11125. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11126. Engine._ALPHA_INTERPOLATE = 9;
  11127. Engine._ALPHA_SCREENMODE = 10;
  11128. Engine._DELAYLOADSTATE_NONE = 0;
  11129. Engine._DELAYLOADSTATE_LOADED = 1;
  11130. Engine._DELAYLOADSTATE_LOADING = 2;
  11131. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11132. Engine._TEXTUREFORMAT_ALPHA = 0;
  11133. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11134. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11135. Engine._TEXTUREFORMAT_RGB = 4;
  11136. Engine._TEXTUREFORMAT_RGBA = 5;
  11137. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11138. Engine._TEXTURETYPE_FLOAT = 1;
  11139. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11140. // Depht or Stencil test Constants.
  11141. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11142. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  11143. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  11144. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  11145. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  11146. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  11147. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  11148. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  11149. // Stencil Actions Constants.
  11150. Engine._KEEP = 0x1E00;
  11151. Engine._REPLACE = 0x1E01;
  11152. Engine._INCR = 0x1E02;
  11153. Engine._DECR = 0x1E03;
  11154. Engine._INVERT = 0x150A;
  11155. Engine._INCR_WRAP = 0x8507;
  11156. Engine._DECR_WRAP = 0x8508;
  11157. // Texture rescaling mode
  11158. Engine._SCALEMODE_FLOOR = 1;
  11159. Engine._SCALEMODE_NEAREST = 2;
  11160. Engine._SCALEMODE_CEILING = 3;
  11161. // Updatable statics so stick with vars here
  11162. Engine.CollisionsEpsilon = 0.001;
  11163. Engine.CodeRepository = "src/";
  11164. Engine.ShadersRepository = "src/Shaders/";
  11165. return Engine;
  11166. }());
  11167. BABYLON.Engine = Engine;
  11168. })(BABYLON || (BABYLON = {}));
  11169. //# sourceMappingURL=babylon.engine.js.map
  11170. /// <reference path="Tools\babylon.decorators.ts" />
  11171. var BABYLON;
  11172. (function (BABYLON) {
  11173. /**
  11174. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11175. */
  11176. var Node = (function () {
  11177. /**
  11178. * @constructor
  11179. * @param {string} name - the name and id to be given to this node
  11180. * @param {BABYLON.Scene} the scene this node will be added to
  11181. */
  11182. function Node(name, scene) {
  11183. this.state = "";
  11184. this.metadata = null;
  11185. this.doNotSerialize = false;
  11186. this.animations = new Array();
  11187. this._ranges = {};
  11188. this._childrenFlag = -1;
  11189. this._isEnabled = true;
  11190. this._isReady = true;
  11191. this._currentRenderId = -1;
  11192. this._parentRenderId = -1;
  11193. /**
  11194. * An event triggered when the mesh is disposed.
  11195. * @type {BABYLON.Observable}
  11196. */
  11197. this.onDisposeObservable = new BABYLON.Observable();
  11198. // Behaviors
  11199. this._behaviors = new Array();
  11200. this.name = name;
  11201. this.id = name;
  11202. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11203. this._initCache();
  11204. }
  11205. Object.defineProperty(Node.prototype, "parent", {
  11206. get: function () {
  11207. return this._parentNode;
  11208. },
  11209. set: function (parent) {
  11210. if (this._parentNode === parent) {
  11211. return;
  11212. }
  11213. if (this._parentNode) {
  11214. var index = this._parentNode._children.indexOf(this);
  11215. if (index !== -1) {
  11216. this._parentNode._children.splice(index, 1);
  11217. }
  11218. }
  11219. this._parentNode = parent;
  11220. if (this._parentNode) {
  11221. if (!this._parentNode._children) {
  11222. this._parentNode._children = new Array();
  11223. }
  11224. this._parentNode._children.push(this);
  11225. }
  11226. },
  11227. enumerable: true,
  11228. configurable: true
  11229. });
  11230. Node.prototype.getClassName = function () {
  11231. return "Node";
  11232. };
  11233. Object.defineProperty(Node.prototype, "onDispose", {
  11234. set: function (callback) {
  11235. if (this._onDisposeObserver) {
  11236. this.onDisposeObservable.remove(this._onDisposeObserver);
  11237. }
  11238. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11239. },
  11240. enumerable: true,
  11241. configurable: true
  11242. });
  11243. Node.prototype.getScene = function () {
  11244. return this._scene;
  11245. };
  11246. Node.prototype.getEngine = function () {
  11247. return this._scene.getEngine();
  11248. };
  11249. Node.prototype.addBehavior = function (behavior) {
  11250. var index = this._behaviors.indexOf(behavior);
  11251. if (index !== -1) {
  11252. return;
  11253. }
  11254. behavior.attach(this);
  11255. this._behaviors.push(behavior);
  11256. return this;
  11257. };
  11258. Node.prototype.removeBehavior = function (behavior) {
  11259. var index = this._behaviors.indexOf(behavior);
  11260. if (index === -1) {
  11261. return;
  11262. }
  11263. this._behaviors[index].detach();
  11264. this._behaviors.splice(index, 1);
  11265. return this;
  11266. };
  11267. Object.defineProperty(Node.prototype, "behaviors", {
  11268. get: function () {
  11269. return this._behaviors;
  11270. },
  11271. enumerable: true,
  11272. configurable: true
  11273. });
  11274. Node.prototype.getBehaviorByName = function (name) {
  11275. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11276. var behavior = _a[_i];
  11277. if (behavior.name === name) {
  11278. return behavior;
  11279. }
  11280. }
  11281. return null;
  11282. };
  11283. // override it in derived class
  11284. Node.prototype.getWorldMatrix = function () {
  11285. return BABYLON.Matrix.Identity();
  11286. };
  11287. // override it in derived class if you add new variables to the cache
  11288. // and call the parent class method
  11289. Node.prototype._initCache = function () {
  11290. this._cache = {};
  11291. this._cache.parent = undefined;
  11292. };
  11293. Node.prototype.updateCache = function (force) {
  11294. if (!force && this.isSynchronized())
  11295. return;
  11296. this._cache.parent = this.parent;
  11297. this._updateCache();
  11298. };
  11299. // override it in derived class if you add new variables to the cache
  11300. // and call the parent class method if !ignoreParentClass
  11301. Node.prototype._updateCache = function (ignoreParentClass) {
  11302. };
  11303. // override it in derived class if you add new variables to the cache
  11304. Node.prototype._isSynchronized = function () {
  11305. return true;
  11306. };
  11307. Node.prototype._markSyncedWithParent = function () {
  11308. this._parentRenderId = this.parent._currentRenderId;
  11309. };
  11310. Node.prototype.isSynchronizedWithParent = function () {
  11311. if (!this.parent) {
  11312. return true;
  11313. }
  11314. if (this._parentRenderId !== this.parent._currentRenderId) {
  11315. return false;
  11316. }
  11317. return this.parent.isSynchronized();
  11318. };
  11319. Node.prototype.isSynchronized = function (updateCache) {
  11320. var check = this.hasNewParent();
  11321. check = check || !this.isSynchronizedWithParent();
  11322. check = check || !this._isSynchronized();
  11323. if (updateCache)
  11324. this.updateCache(true);
  11325. return !check;
  11326. };
  11327. Node.prototype.hasNewParent = function (update) {
  11328. if (this._cache.parent === this.parent)
  11329. return false;
  11330. if (update)
  11331. this._cache.parent = this.parent;
  11332. return true;
  11333. };
  11334. /**
  11335. * Is this node ready to be used/rendered
  11336. * @return {boolean} is it ready
  11337. */
  11338. Node.prototype.isReady = function () {
  11339. return this._isReady;
  11340. };
  11341. /**
  11342. * Is this node enabled.
  11343. * If the node has a parent and is enabled, the parent will be inspected as well.
  11344. * @return {boolean} whether this node (and its parent) is enabled.
  11345. * @see setEnabled
  11346. */
  11347. Node.prototype.isEnabled = function () {
  11348. if (!this._isEnabled) {
  11349. return false;
  11350. }
  11351. if (this.parent) {
  11352. return this.parent.isEnabled();
  11353. }
  11354. return true;
  11355. };
  11356. /**
  11357. * Set the enabled state of this node.
  11358. * @param {boolean} value - the new enabled state
  11359. * @see isEnabled
  11360. */
  11361. Node.prototype.setEnabled = function (value) {
  11362. this._isEnabled = value;
  11363. };
  11364. /**
  11365. * Is this node a descendant of the given node.
  11366. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11367. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11368. * @see parent
  11369. */
  11370. Node.prototype.isDescendantOf = function (ancestor) {
  11371. if (this.parent) {
  11372. if (this.parent === ancestor) {
  11373. return true;
  11374. }
  11375. return this.parent.isDescendantOf(ancestor);
  11376. }
  11377. return false;
  11378. };
  11379. /**
  11380. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11381. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11382. * @param {boolean} directDescendantsOnly 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.
  11383. * @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.
  11384. */
  11385. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11386. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11387. if (!this._children) {
  11388. return;
  11389. }
  11390. for (var index = 0; index < this._children.length; index++) {
  11391. var item = this._children[index];
  11392. if (!predicate || predicate(item)) {
  11393. results.push(item);
  11394. }
  11395. if (!directDescendantsOnly) {
  11396. item._getDescendants(results, false, predicate);
  11397. }
  11398. }
  11399. };
  11400. /**
  11401. * Will return all nodes that have this node as ascendant.
  11402. * @param {boolean} directDescendantsOnly 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.
  11403. * @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.
  11404. * @return {BABYLON.Node[]} all children nodes of all types.
  11405. */
  11406. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11407. var results = [];
  11408. this._getDescendants(results, directDescendantsOnly, predicate);
  11409. return results;
  11410. };
  11411. /**
  11412. * Get all child-meshes of this node.
  11413. */
  11414. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11415. var results = [];
  11416. this._getDescendants(results, directDecendantsOnly, function (node) {
  11417. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11418. });
  11419. return results;
  11420. };
  11421. /**
  11422. * Get all direct children of this node.
  11423. */
  11424. Node.prototype.getChildren = function (predicate) {
  11425. return this.getDescendants(true, predicate);
  11426. };
  11427. Node.prototype._setReady = function (state) {
  11428. if (state === this._isReady) {
  11429. return;
  11430. }
  11431. if (!state) {
  11432. this._isReady = false;
  11433. return;
  11434. }
  11435. this._isReady = true;
  11436. if (this.onReady) {
  11437. this.onReady(this);
  11438. }
  11439. };
  11440. Node.prototype.getAnimationByName = function (name) {
  11441. for (var i = 0; i < this.animations.length; i++) {
  11442. var animation = this.animations[i];
  11443. if (animation.name === name) {
  11444. return animation;
  11445. }
  11446. }
  11447. return null;
  11448. };
  11449. Node.prototype.createAnimationRange = function (name, from, to) {
  11450. // check name not already in use
  11451. if (!this._ranges[name]) {
  11452. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11453. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11454. if (this.animations[i]) {
  11455. this.animations[i].createRange(name, from, to);
  11456. }
  11457. }
  11458. }
  11459. };
  11460. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11461. if (deleteFrames === void 0) { deleteFrames = true; }
  11462. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11463. if (this.animations[i]) {
  11464. this.animations[i].deleteRange(name, deleteFrames);
  11465. }
  11466. }
  11467. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11468. };
  11469. Node.prototype.getAnimationRange = function (name) {
  11470. return this._ranges[name];
  11471. };
  11472. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11473. var range = this.getAnimationRange(name);
  11474. if (!range) {
  11475. return null;
  11476. }
  11477. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11478. };
  11479. Node.prototype.serializeAnimationRanges = function () {
  11480. var serializationRanges = [];
  11481. for (var name in this._ranges) {
  11482. var range = {};
  11483. range.name = name;
  11484. range.from = this._ranges[name].from;
  11485. range.to = this._ranges[name].to;
  11486. serializationRanges.push(range);
  11487. }
  11488. return serializationRanges;
  11489. };
  11490. Node.prototype.dispose = function () {
  11491. this.parent = null;
  11492. // Callback
  11493. this.onDisposeObservable.notifyObservers(this);
  11494. this.onDisposeObservable.clear();
  11495. // Behaviors
  11496. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11497. var behavior = _a[_i];
  11498. behavior.detach();
  11499. }
  11500. this._behaviors = [];
  11501. };
  11502. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11503. if (parsedNode.ranges) {
  11504. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11505. var data = parsedNode.ranges[index];
  11506. node.createAnimationRange(data.name, data.from, data.to);
  11507. }
  11508. }
  11509. };
  11510. __decorate([
  11511. BABYLON.serialize()
  11512. ], Node.prototype, "name", void 0);
  11513. __decorate([
  11514. BABYLON.serialize()
  11515. ], Node.prototype, "id", void 0);
  11516. __decorate([
  11517. BABYLON.serialize()
  11518. ], Node.prototype, "uniqueId", void 0);
  11519. __decorate([
  11520. BABYLON.serialize()
  11521. ], Node.prototype, "state", void 0);
  11522. __decorate([
  11523. BABYLON.serialize()
  11524. ], Node.prototype, "metadata", void 0);
  11525. return Node;
  11526. }());
  11527. BABYLON.Node = Node;
  11528. })(BABYLON || (BABYLON = {}));
  11529. //# sourceMappingURL=babylon.node.js.map
  11530. var BABYLON;
  11531. (function (BABYLON) {
  11532. var BoundingSphere = (function () {
  11533. function BoundingSphere(minimum, maximum) {
  11534. this.minimum = minimum;
  11535. this.maximum = maximum;
  11536. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11537. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11538. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11539. this.radius = distance * 0.5;
  11540. this.centerWorld = BABYLON.Vector3.Zero();
  11541. this._update(BABYLON.Matrix.Identity());
  11542. }
  11543. // Methods
  11544. BoundingSphere.prototype._update = function (world) {
  11545. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11546. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11547. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11548. };
  11549. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11550. for (var i = 0; i < 6; i++) {
  11551. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11552. return false;
  11553. }
  11554. return true;
  11555. };
  11556. BoundingSphere.prototype.intersectsPoint = function (point) {
  11557. var x = this.centerWorld.x - point.x;
  11558. var y = this.centerWorld.y - point.y;
  11559. var z = this.centerWorld.z - point.z;
  11560. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11561. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11562. return false;
  11563. return true;
  11564. };
  11565. // Statics
  11566. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11567. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11568. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11569. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11570. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11571. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11572. return false;
  11573. return true;
  11574. };
  11575. return BoundingSphere;
  11576. }());
  11577. BABYLON.BoundingSphere = BoundingSphere;
  11578. })(BABYLON || (BABYLON = {}));
  11579. //# sourceMappingURL=babylon.boundingSphere.js.map
  11580. var BABYLON;
  11581. (function (BABYLON) {
  11582. var BoundingBox = (function () {
  11583. function BoundingBox(minimum, maximum) {
  11584. this.minimum = minimum;
  11585. this.maximum = maximum;
  11586. this.vectors = new Array();
  11587. this.vectorsWorld = new Array();
  11588. // Bounding vectors
  11589. this.vectors.push(this.minimum.clone());
  11590. this.vectors.push(this.maximum.clone());
  11591. this.vectors.push(this.minimum.clone());
  11592. this.vectors[2].x = this.maximum.x;
  11593. this.vectors.push(this.minimum.clone());
  11594. this.vectors[3].y = this.maximum.y;
  11595. this.vectors.push(this.minimum.clone());
  11596. this.vectors[4].z = this.maximum.z;
  11597. this.vectors.push(this.maximum.clone());
  11598. this.vectors[5].z = this.minimum.z;
  11599. this.vectors.push(this.maximum.clone());
  11600. this.vectors[6].x = this.minimum.x;
  11601. this.vectors.push(this.maximum.clone());
  11602. this.vectors[7].y = this.minimum.y;
  11603. // OBB
  11604. this.center = this.maximum.add(this.minimum).scale(0.5);
  11605. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11606. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11607. // World
  11608. for (var index = 0; index < this.vectors.length; index++) {
  11609. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11610. }
  11611. this.minimumWorld = BABYLON.Vector3.Zero();
  11612. this.maximumWorld = BABYLON.Vector3.Zero();
  11613. this.centerWorld = BABYLON.Vector3.Zero();
  11614. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11615. this._update(BABYLON.Matrix.Identity());
  11616. }
  11617. // Methods
  11618. BoundingBox.prototype.getWorldMatrix = function () {
  11619. return this._worldMatrix;
  11620. };
  11621. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11622. this._worldMatrix.copyFrom(matrix);
  11623. return this;
  11624. };
  11625. BoundingBox.prototype._update = function (world) {
  11626. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11627. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11628. for (var index = 0; index < this.vectors.length; index++) {
  11629. var v = this.vectorsWorld[index];
  11630. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11631. if (v.x < this.minimumWorld.x)
  11632. this.minimumWorld.x = v.x;
  11633. if (v.y < this.minimumWorld.y)
  11634. this.minimumWorld.y = v.y;
  11635. if (v.z < this.minimumWorld.z)
  11636. this.minimumWorld.z = v.z;
  11637. if (v.x > this.maximumWorld.x)
  11638. this.maximumWorld.x = v.x;
  11639. if (v.y > this.maximumWorld.y)
  11640. this.maximumWorld.y = v.y;
  11641. if (v.z > this.maximumWorld.z)
  11642. this.maximumWorld.z = v.z;
  11643. }
  11644. // Extend
  11645. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11646. this.extendSizeWorld.scaleInPlace(0.5);
  11647. // OBB
  11648. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11649. this.centerWorld.scaleInPlace(0.5);
  11650. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11651. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11652. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11653. this._worldMatrix = world;
  11654. };
  11655. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11656. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11657. };
  11658. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11659. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11660. };
  11661. BoundingBox.prototype.intersectsPoint = function (point) {
  11662. var delta = -BABYLON.Epsilon;
  11663. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11664. return false;
  11665. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11666. return false;
  11667. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11668. return false;
  11669. return true;
  11670. };
  11671. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11672. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11673. };
  11674. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11675. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11676. return false;
  11677. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11678. return false;
  11679. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11680. return false;
  11681. return true;
  11682. };
  11683. // Statics
  11684. BoundingBox.Intersects = function (box0, box1) {
  11685. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11686. return false;
  11687. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11688. return false;
  11689. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11690. return false;
  11691. return true;
  11692. };
  11693. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11694. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11695. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11696. return (num <= (sphereRadius * sphereRadius));
  11697. };
  11698. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11699. for (var p = 0; p < 6; p++) {
  11700. for (var i = 0; i < 8; i++) {
  11701. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11702. return false;
  11703. }
  11704. }
  11705. }
  11706. return true;
  11707. };
  11708. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11709. for (var p = 0; p < 6; p++) {
  11710. var inCount = 8;
  11711. for (var i = 0; i < 8; i++) {
  11712. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11713. --inCount;
  11714. }
  11715. else {
  11716. break;
  11717. }
  11718. }
  11719. if (inCount === 0)
  11720. return false;
  11721. }
  11722. return true;
  11723. };
  11724. return BoundingBox;
  11725. }());
  11726. BABYLON.BoundingBox = BoundingBox;
  11727. })(BABYLON || (BABYLON = {}));
  11728. //# sourceMappingURL=babylon.boundingBox.js.map
  11729. var BABYLON;
  11730. (function (BABYLON) {
  11731. var computeBoxExtents = function (axis, box) {
  11732. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11733. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11734. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11735. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11736. var r = r0 + r1 + r2;
  11737. return {
  11738. min: p - r,
  11739. max: p + r
  11740. };
  11741. };
  11742. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11743. var axisOverlap = function (axis, box0, box1) {
  11744. var result0 = computeBoxExtents(axis, box0);
  11745. var result1 = computeBoxExtents(axis, box1);
  11746. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11747. };
  11748. var BoundingInfo = (function () {
  11749. function BoundingInfo(minimum, maximum) {
  11750. this.minimum = minimum;
  11751. this.maximum = maximum;
  11752. this._isLocked = false;
  11753. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11754. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11755. }
  11756. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11757. get: function () {
  11758. return this._isLocked;
  11759. },
  11760. set: function (value) {
  11761. this._isLocked = value;
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. // Methods
  11767. BoundingInfo.prototype.update = function (world) {
  11768. if (this._isLocked) {
  11769. return;
  11770. }
  11771. this.boundingBox._update(world);
  11772. this.boundingSphere._update(world);
  11773. };
  11774. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11775. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11776. return false;
  11777. return this.boundingBox.isInFrustum(frustumPlanes);
  11778. };
  11779. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11780. /**
  11781. * Gets the world distance between the min and max points of the bounding box
  11782. */
  11783. get: function () {
  11784. var boundingBox = this.boundingBox;
  11785. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11786. return size.length();
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11792. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11793. };
  11794. BoundingInfo.prototype._checkCollision = function (collider) {
  11795. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11796. };
  11797. BoundingInfo.prototype.intersectsPoint = function (point) {
  11798. if (!this.boundingSphere.centerWorld) {
  11799. return false;
  11800. }
  11801. if (!this.boundingSphere.intersectsPoint(point)) {
  11802. return false;
  11803. }
  11804. if (!this.boundingBox.intersectsPoint(point)) {
  11805. return false;
  11806. }
  11807. return true;
  11808. };
  11809. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11810. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11811. return false;
  11812. }
  11813. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11814. return false;
  11815. }
  11816. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11817. return false;
  11818. }
  11819. if (!precise) {
  11820. return true;
  11821. }
  11822. var box0 = this.boundingBox;
  11823. var box1 = boundingInfo.boundingBox;
  11824. if (!axisOverlap(box0.directions[0], box0, box1))
  11825. return false;
  11826. if (!axisOverlap(box0.directions[1], box0, box1))
  11827. return false;
  11828. if (!axisOverlap(box0.directions[2], box0, box1))
  11829. return false;
  11830. if (!axisOverlap(box1.directions[0], box0, box1))
  11831. return false;
  11832. if (!axisOverlap(box1.directions[1], box0, box1))
  11833. return false;
  11834. if (!axisOverlap(box1.directions[2], box0, box1))
  11835. return false;
  11836. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11837. return false;
  11838. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11839. return false;
  11840. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11841. return false;
  11842. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11843. return false;
  11844. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11845. return false;
  11846. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11847. return false;
  11848. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11849. return false;
  11850. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11851. return false;
  11852. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11853. return false;
  11854. return true;
  11855. };
  11856. return BoundingInfo;
  11857. }());
  11858. BABYLON.BoundingInfo = BoundingInfo;
  11859. })(BABYLON || (BABYLON = {}));
  11860. //# sourceMappingURL=babylon.boundingInfo.js.map
  11861. var BABYLON;
  11862. (function (BABYLON) {
  11863. var AbstractMesh = (function (_super) {
  11864. __extends(AbstractMesh, _super);
  11865. // Constructor
  11866. function AbstractMesh(name, scene) {
  11867. var _this = _super.call(this, name, scene) || this;
  11868. _this._facetNb = 0; // facet number
  11869. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11870. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11871. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11872. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11873. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11874. _this._subDiv = {
  11875. max: 1,
  11876. X: 1,
  11877. Y: 1,
  11878. Z: 1
  11879. };
  11880. // Events
  11881. /**
  11882. * An event triggered when this mesh collides with another one
  11883. * @type {BABYLON.Observable}
  11884. */
  11885. _this.onCollideObservable = new BABYLON.Observable();
  11886. /**
  11887. * An event triggered when the collision's position changes
  11888. * @type {BABYLON.Observable}
  11889. */
  11890. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11891. /**
  11892. * An event triggered after the world matrix is updated
  11893. * @type {BABYLON.Observable}
  11894. */
  11895. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11896. /**
  11897. * An event triggered when material is changed
  11898. * @type {BABYLON.Observable}
  11899. */
  11900. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11901. // Properties
  11902. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11903. _this.position = BABYLON.Vector3.Zero();
  11904. /**
  11905. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  11906. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  11907. * or
  11908. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  11909. * for more info check WebGl documentations
  11910. */
  11911. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  11912. /**
  11913. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  11914. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  11915. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  11916. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  11917. */
  11918. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  11919. /**
  11920. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  11921. * The default value is -1 which means don't break the query and wait till the result.
  11922. */
  11923. _this.occlusionRetryCount = -1;
  11924. _this._occlusionInternalRetryCounter = 0;
  11925. _this._isOccluded = false;
  11926. _this._isOcclusionQueryInProgress = false;
  11927. _this._rotation = BABYLON.Vector3.Zero();
  11928. _this._scaling = BABYLON.Vector3.One();
  11929. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11930. _this.visibility = 1.0;
  11931. _this.alphaIndex = Number.MAX_VALUE;
  11932. _this.infiniteDistance = false;
  11933. _this.isVisible = true;
  11934. _this.isPickable = true;
  11935. _this.showBoundingBox = false;
  11936. _this.showSubMeshesBoundingBox = false;
  11937. _this.isBlocker = false;
  11938. _this.enablePointerMoveEvents = false;
  11939. _this.renderingGroupId = 0;
  11940. _this._receiveShadows = false;
  11941. _this.renderOutline = false;
  11942. _this.outlineColor = BABYLON.Color3.Red();
  11943. _this.outlineWidth = 0.02;
  11944. _this.renderOverlay = false;
  11945. _this.overlayColor = BABYLON.Color3.Red();
  11946. _this.overlayAlpha = 0.5;
  11947. _this._hasVertexAlpha = false;
  11948. _this._useVertexColors = true;
  11949. _this._computeBonesUsingShaders = true;
  11950. _this._numBoneInfluencers = 4;
  11951. _this._applyFog = true;
  11952. _this.scalingDeterminant = 1;
  11953. _this.useOctreeForRenderingSelection = true;
  11954. _this.useOctreeForPicking = true;
  11955. _this.useOctreeForCollisions = true;
  11956. _this._layerMask = 0x0FFFFFFF;
  11957. /**
  11958. * True if the mesh must be rendered in any case.
  11959. */
  11960. _this.alwaysSelectAsActiveMesh = false;
  11961. // Collisions
  11962. _this._checkCollisions = false;
  11963. _this._collisionMask = -1;
  11964. _this._collisionGroup = -1;
  11965. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11966. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11967. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11968. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11969. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11970. // Edges
  11971. _this.edgesWidth = 1;
  11972. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11973. // Cache
  11974. _this._localWorld = BABYLON.Matrix.Zero();
  11975. _this._worldMatrix = BABYLON.Matrix.Zero();
  11976. _this._absolutePosition = BABYLON.Vector3.Zero();
  11977. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11978. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11979. _this._isDirty = false;
  11980. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11981. _this._isDisposed = false;
  11982. _this._renderId = 0;
  11983. _this._intersectionsInProgress = new Array();
  11984. _this._isWorldMatrixFrozen = false;
  11985. _this._unIndexed = false;
  11986. _this._lightSources = new Array();
  11987. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11988. if (collidedMesh === void 0) { collidedMesh = null; }
  11989. //TODO move this to the collision coordinator!
  11990. if (_this.getScene().workerCollisions)
  11991. newPosition.multiplyInPlace(_this._collider.radius);
  11992. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11993. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11994. _this.position.addInPlace(_this._diffPositionForCollisions);
  11995. }
  11996. if (collidedMesh) {
  11997. _this.onCollideObservable.notifyObservers(collidedMesh);
  11998. }
  11999. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12000. };
  12001. _this.getScene().addMesh(_this);
  12002. _this._resyncLightSources();
  12003. return _this;
  12004. }
  12005. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12006. get: function () {
  12007. return AbstractMesh._BILLBOARDMODE_NONE;
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12013. get: function () {
  12014. return AbstractMesh._BILLBOARDMODE_X;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12020. get: function () {
  12021. return AbstractMesh._BILLBOARDMODE_Y;
  12022. },
  12023. enumerable: true,
  12024. configurable: true
  12025. });
  12026. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12027. get: function () {
  12028. return AbstractMesh._BILLBOARDMODE_Z;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12034. get: function () {
  12035. return AbstractMesh._BILLBOARDMODE_ALL;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12041. /**
  12042. * Read-only : the number of facets in the mesh
  12043. */
  12044. get: function () {
  12045. return this._facetNb;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12051. /**
  12052. * The number (integer) of subdivisions per axis in the partioning space
  12053. */
  12054. get: function () {
  12055. return this._partitioningSubdivisions;
  12056. },
  12057. set: function (nb) {
  12058. this._partitioningSubdivisions = nb;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12064. /**
  12065. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12066. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12067. */
  12068. get: function () {
  12069. return this._partitioningBBoxRatio;
  12070. },
  12071. set: function (ratio) {
  12072. this._partitioningBBoxRatio = ratio;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12078. /**
  12079. * Read-only boolean : is the feature facetData enabled ?
  12080. */
  12081. get: function () {
  12082. return this._facetDataEnabled;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12088. set: function (callback) {
  12089. if (this._onCollideObserver) {
  12090. this.onCollideObservable.remove(this._onCollideObserver);
  12091. }
  12092. this._onCollideObserver = this.onCollideObservable.add(callback);
  12093. },
  12094. enumerable: true,
  12095. configurable: true
  12096. });
  12097. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12098. set: function (callback) {
  12099. if (this._onCollisionPositionChangeObserver) {
  12100. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12101. }
  12102. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12108. /**
  12109. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  12110. */
  12111. get: function () {
  12112. return this._isOccluded;
  12113. },
  12114. set: function (value) {
  12115. this._isOccluded = value;
  12116. },
  12117. enumerable: true,
  12118. configurable: true
  12119. });
  12120. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12121. /**
  12122. * Flag to check the progress status of the query
  12123. */
  12124. get: function () {
  12125. return this._isOcclusionQueryInProgress;
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(AbstractMesh.prototype, "material", {
  12131. get: function () {
  12132. return this._material;
  12133. },
  12134. set: function (value) {
  12135. if (this._material === value) {
  12136. return;
  12137. }
  12138. this._material = value;
  12139. if (this.onMaterialChangedObservable.hasObservers) {
  12140. this.onMaterialChangedObservable.notifyObservers(this);
  12141. }
  12142. if (!this.subMeshes) {
  12143. return;
  12144. }
  12145. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12146. var subMesh = _a[_i];
  12147. subMesh.setEffect(null);
  12148. }
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12154. get: function () {
  12155. return this._receiveShadows;
  12156. },
  12157. set: function (value) {
  12158. if (this._receiveShadows === value) {
  12159. return;
  12160. }
  12161. this._receiveShadows = value;
  12162. this._markSubMeshesAsLightDirty();
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12168. get: function () {
  12169. return this._hasVertexAlpha;
  12170. },
  12171. set: function (value) {
  12172. if (this._hasVertexAlpha === value) {
  12173. return;
  12174. }
  12175. this._hasVertexAlpha = value;
  12176. this._markSubMeshesAsAttributesDirty();
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12182. get: function () {
  12183. return this._useVertexColors;
  12184. },
  12185. set: function (value) {
  12186. if (this._useVertexColors === value) {
  12187. return;
  12188. }
  12189. this._useVertexColors = value;
  12190. this._markSubMeshesAsAttributesDirty();
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12196. get: function () {
  12197. return this._computeBonesUsingShaders;
  12198. },
  12199. set: function (value) {
  12200. if (this._computeBonesUsingShaders === value) {
  12201. return;
  12202. }
  12203. this._computeBonesUsingShaders = value;
  12204. this._markSubMeshesAsAttributesDirty();
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12210. get: function () {
  12211. return this._numBoneInfluencers;
  12212. },
  12213. set: function (value) {
  12214. if (this._numBoneInfluencers === value) {
  12215. return;
  12216. }
  12217. this._numBoneInfluencers = value;
  12218. this._markSubMeshesAsAttributesDirty();
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12224. get: function () {
  12225. return this._applyFog;
  12226. },
  12227. set: function (value) {
  12228. if (this._applyFog === value) {
  12229. return;
  12230. }
  12231. this._applyFog = value;
  12232. this._markSubMeshesAsMiscDirty();
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12238. get: function () {
  12239. return this._layerMask;
  12240. },
  12241. set: function (value) {
  12242. if (value === this._layerMask) {
  12243. return;
  12244. }
  12245. this._layerMask = value;
  12246. this._resyncLightSources();
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12252. get: function () {
  12253. return this._collisionMask;
  12254. },
  12255. set: function (mask) {
  12256. this._collisionMask = !isNaN(mask) ? mask : -1;
  12257. },
  12258. enumerable: true,
  12259. configurable: true
  12260. });
  12261. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12262. get: function () {
  12263. return this._collisionGroup;
  12264. },
  12265. set: function (mask) {
  12266. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12267. },
  12268. enumerable: true,
  12269. configurable: true
  12270. });
  12271. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12272. get: function () {
  12273. return null;
  12274. },
  12275. enumerable: true,
  12276. configurable: true
  12277. });
  12278. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12279. get: function () {
  12280. return this._skeleton;
  12281. },
  12282. set: function (value) {
  12283. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12284. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12285. }
  12286. if (value && value.needInitialSkinMatrix) {
  12287. value._registerMeshWithPoseMatrix(this);
  12288. }
  12289. this._skeleton = value;
  12290. if (!this._skeleton) {
  12291. this._bonesTransformMatrices = null;
  12292. }
  12293. this._markSubMeshesAsAttributesDirty();
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. /**
  12299. * Boolean : true if the mesh has been disposed.
  12300. */
  12301. AbstractMesh.prototype.isDisposed = function () {
  12302. return this._isDisposed;
  12303. };
  12304. /**
  12305. * Returns the string "AbstractMesh"
  12306. */
  12307. AbstractMesh.prototype.getClassName = function () {
  12308. return "AbstractMesh";
  12309. };
  12310. /**
  12311. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12312. */
  12313. AbstractMesh.prototype.toString = function (fullDetails) {
  12314. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12315. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12316. if (this._skeleton) {
  12317. ret += ", skeleton: " + this._skeleton.name;
  12318. }
  12319. if (fullDetails) {
  12320. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12321. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12322. }
  12323. return ret;
  12324. };
  12325. AbstractMesh.prototype._rebuild = function () {
  12326. if (this._occlusionQuery) {
  12327. this._occlusionQuery = null;
  12328. }
  12329. if (!this.subMeshes) {
  12330. return;
  12331. }
  12332. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12333. var subMesh = _a[_i];
  12334. subMesh._rebuild();
  12335. }
  12336. };
  12337. AbstractMesh.prototype._resyncLightSources = function () {
  12338. this._lightSources.length = 0;
  12339. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12340. var light = _a[_i];
  12341. if (!light.isEnabled()) {
  12342. continue;
  12343. }
  12344. if (light.canAffectMesh(this)) {
  12345. this._lightSources.push(light);
  12346. }
  12347. }
  12348. this._markSubMeshesAsLightDirty();
  12349. };
  12350. AbstractMesh.prototype._resyncLighSource = function (light) {
  12351. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12352. var index = this._lightSources.indexOf(light);
  12353. if (index === -1) {
  12354. if (!isIn) {
  12355. return;
  12356. }
  12357. this._lightSources.push(light);
  12358. }
  12359. else {
  12360. if (isIn) {
  12361. return;
  12362. }
  12363. this._lightSources.splice(index, 1);
  12364. }
  12365. this._markSubMeshesAsLightDirty();
  12366. };
  12367. AbstractMesh.prototype._removeLightSource = function (light) {
  12368. var index = this._lightSources.indexOf(light);
  12369. if (index === -1) {
  12370. return;
  12371. }
  12372. this._lightSources.splice(index, 1);
  12373. };
  12374. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12375. if (!this.subMeshes) {
  12376. return;
  12377. }
  12378. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12379. var subMesh = _a[_i];
  12380. if (subMesh._materialDefines) {
  12381. func(subMesh._materialDefines);
  12382. }
  12383. }
  12384. };
  12385. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12386. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12387. };
  12388. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12389. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12390. };
  12391. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12392. if (!this.subMeshes) {
  12393. return;
  12394. }
  12395. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12396. var subMesh = _a[_i];
  12397. var material = subMesh.getMaterial();
  12398. if (material) {
  12399. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12400. }
  12401. }
  12402. };
  12403. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12404. /**
  12405. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12406. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12407. * Default : (0.0, 0.0, 0.0)
  12408. */
  12409. get: function () {
  12410. return this._rotation;
  12411. },
  12412. set: function (newRotation) {
  12413. this._rotation = newRotation;
  12414. },
  12415. enumerable: true,
  12416. configurable: true
  12417. });
  12418. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12419. /**
  12420. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12421. * Default : (1.0, 1.0, 1.0)
  12422. */
  12423. get: function () {
  12424. return this._scaling;
  12425. },
  12426. set: function (newScaling) {
  12427. this._scaling = newScaling;
  12428. if (this.physicsImpostor) {
  12429. this.physicsImpostor.forceUpdate();
  12430. }
  12431. },
  12432. enumerable: true,
  12433. configurable: true
  12434. });
  12435. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12436. /**
  12437. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12438. * It's null by default.
  12439. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  12440. */
  12441. get: function () {
  12442. return this._rotationQuaternion;
  12443. },
  12444. set: function (quaternion) {
  12445. this._rotationQuaternion = quaternion;
  12446. //reset the rotation vector.
  12447. if (quaternion && this.rotation.length()) {
  12448. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12449. }
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. // Methods
  12455. /**
  12456. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12457. * Returns the AbstractMesh.
  12458. */
  12459. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12460. this._poseMatrix.copyFrom(matrix);
  12461. return this;
  12462. };
  12463. /**
  12464. * Returns the mesh Pose matrix.
  12465. * Returned object : Matrix
  12466. */
  12467. AbstractMesh.prototype.getPoseMatrix = function () {
  12468. return this._poseMatrix;
  12469. };
  12470. /**
  12471. * Disables the mesh edger rendering mode.
  12472. * Returns the AbstractMesh.
  12473. */
  12474. AbstractMesh.prototype.disableEdgesRendering = function () {
  12475. if (this._edgesRenderer !== undefined) {
  12476. this._edgesRenderer.dispose();
  12477. this._edgesRenderer = undefined;
  12478. }
  12479. return this;
  12480. };
  12481. /**
  12482. * Enables the edge rendering mode on the mesh.
  12483. * This mode makes the mesh edges visible.
  12484. * Returns the AbstractMesh.
  12485. */
  12486. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12487. if (epsilon === void 0) { epsilon = 0.95; }
  12488. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12489. this.disableEdgesRendering();
  12490. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12491. return this;
  12492. };
  12493. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12494. /**
  12495. * Returns true if the mesh is blocked. Used by the class Mesh.
  12496. * Returns the boolean `false` by default.
  12497. */
  12498. get: function () {
  12499. return false;
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. /**
  12505. * Returns the mesh itself by default, used by the class Mesh.
  12506. * Returned type : AbstractMesh
  12507. */
  12508. AbstractMesh.prototype.getLOD = function (camera) {
  12509. return this;
  12510. };
  12511. /**
  12512. * Returns 0 by default, used by the class Mesh.
  12513. * Returns an integer.
  12514. */
  12515. AbstractMesh.prototype.getTotalVertices = function () {
  12516. return 0;
  12517. };
  12518. /**
  12519. * Returns null by default, used by the class Mesh.
  12520. * Returned type : integer array
  12521. */
  12522. AbstractMesh.prototype.getIndices = function () {
  12523. return null;
  12524. };
  12525. /**
  12526. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12527. * Returned type : float array or Float32Array
  12528. */
  12529. AbstractMesh.prototype.getVerticesData = function (kind) {
  12530. return null;
  12531. };
  12532. /**
  12533. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12534. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12535. * The `data` are either a numeric array either a Float32Array.
  12536. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12537. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  12538. * Note that a new underlying VertexBuffer object is created each call.
  12539. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12540. *
  12541. * Possible `kind` values :
  12542. * - BABYLON.VertexBuffer.PositionKind
  12543. * - BABYLON.VertexBuffer.UVKind
  12544. * - BABYLON.VertexBuffer.UV2Kind
  12545. * - BABYLON.VertexBuffer.UV3Kind
  12546. * - BABYLON.VertexBuffer.UV4Kind
  12547. * - BABYLON.VertexBuffer.UV5Kind
  12548. * - BABYLON.VertexBuffer.UV6Kind
  12549. * - BABYLON.VertexBuffer.ColorKind
  12550. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12551. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12552. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12553. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12554. *
  12555. * Returns the Mesh.
  12556. */
  12557. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12558. return null;
  12559. };
  12560. /**
  12561. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12562. * If the mesh has no geometry, it is simply returned as it is.
  12563. * The `data` are either a numeric array either a Float32Array.
  12564. * No new underlying VertexBuffer object is created.
  12565. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12566. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12567. *
  12568. * Possible `kind` values :
  12569. * - BABYLON.VertexBuffer.PositionKind
  12570. * - BABYLON.VertexBuffer.UVKind
  12571. * - BABYLON.VertexBuffer.UV2Kind
  12572. * - BABYLON.VertexBuffer.UV3Kind
  12573. * - BABYLON.VertexBuffer.UV4Kind
  12574. * - BABYLON.VertexBuffer.UV5Kind
  12575. * - BABYLON.VertexBuffer.UV6Kind
  12576. * - BABYLON.VertexBuffer.ColorKind
  12577. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12578. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12579. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12580. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12581. *
  12582. * Returns the Mesh.
  12583. */
  12584. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12585. return null;
  12586. };
  12587. /**
  12588. * Sets the mesh indices.
  12589. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12590. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12591. * This method creates a new index buffer each call.
  12592. * Returns the Mesh.
  12593. */
  12594. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12595. return null;
  12596. };
  12597. /** Returns false by default, used by the class Mesh.
  12598. * Returns a boolean
  12599. */
  12600. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12601. return false;
  12602. };
  12603. /**
  12604. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12605. * Returns a BoundingInfo
  12606. */
  12607. AbstractMesh.prototype.getBoundingInfo = function () {
  12608. if (this._masterMesh) {
  12609. return this._masterMesh.getBoundingInfo();
  12610. }
  12611. if (!this._boundingInfo) {
  12612. this._updateBoundingInfo();
  12613. }
  12614. return this._boundingInfo;
  12615. };
  12616. /**
  12617. * Sets a mesh new object BoundingInfo.
  12618. * Returns the AbstractMesh.
  12619. */
  12620. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12621. this._boundingInfo = boundingInfo;
  12622. return this;
  12623. };
  12624. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12625. get: function () {
  12626. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12627. },
  12628. enumerable: true,
  12629. configurable: true
  12630. });
  12631. AbstractMesh.prototype._preActivate = function () {
  12632. };
  12633. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12634. };
  12635. AbstractMesh.prototype._activate = function (renderId) {
  12636. this._renderId = renderId;
  12637. };
  12638. /**
  12639. * Returns the last update of the World matrix
  12640. * Returns a Matrix.
  12641. */
  12642. AbstractMesh.prototype.getWorldMatrix = function () {
  12643. if (this._masterMesh) {
  12644. return this._masterMesh.getWorldMatrix();
  12645. }
  12646. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12647. this.computeWorldMatrix();
  12648. }
  12649. return this._worldMatrix;
  12650. };
  12651. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12652. /**
  12653. * Returns directly the last state of the mesh World matrix.
  12654. * A Matrix is returned.
  12655. */
  12656. get: function () {
  12657. return this._worldMatrix;
  12658. },
  12659. enumerable: true,
  12660. configurable: true
  12661. });
  12662. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12663. /**
  12664. * Returns the current mesh absolute position.
  12665. * Retuns a Vector3.
  12666. */
  12667. get: function () {
  12668. return this._absolutePosition;
  12669. },
  12670. enumerable: true,
  12671. configurable: true
  12672. });
  12673. /**
  12674. * Prevents the World matrix to be computed any longer.
  12675. * Returns the AbstractMesh.
  12676. */
  12677. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12678. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12679. this.computeWorldMatrix(true);
  12680. this._isWorldMatrixFrozen = true;
  12681. return this;
  12682. };
  12683. /**
  12684. * Allows back the World matrix computation.
  12685. * Returns the AbstractMesh.
  12686. */
  12687. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12688. this._isWorldMatrixFrozen = false;
  12689. this.computeWorldMatrix(true);
  12690. return this;
  12691. };
  12692. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12693. /**
  12694. * True if the World matrix has been frozen.
  12695. * Returns a boolean.
  12696. */
  12697. get: function () {
  12698. return this._isWorldMatrixFrozen;
  12699. },
  12700. enumerable: true,
  12701. configurable: true
  12702. });
  12703. /**
  12704. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12705. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12706. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12707. * The passed axis is also normalized.
  12708. * Returns the AbstractMesh.
  12709. */
  12710. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12711. axis.normalize();
  12712. if (!this.rotationQuaternion) {
  12713. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12714. this.rotation = BABYLON.Vector3.Zero();
  12715. }
  12716. var rotationQuaternion;
  12717. if (!space || space === BABYLON.Space.LOCAL) {
  12718. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12719. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12720. }
  12721. else {
  12722. if (this.parent) {
  12723. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12724. invertParentWorldMatrix.invert();
  12725. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12726. }
  12727. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12728. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12729. }
  12730. return this;
  12731. };
  12732. /**
  12733. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12734. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12735. * The passed axis is also normalized.
  12736. * Returns the AbstractMesh.
  12737. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12738. */
  12739. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12740. axis.normalize();
  12741. if (!this.rotationQuaternion) {
  12742. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12743. this.rotation.copyFromFloats(0, 0, 0);
  12744. }
  12745. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12746. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12747. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12748. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12749. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12750. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12751. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12752. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12753. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12754. return this;
  12755. };
  12756. /**
  12757. * Translates the mesh along the axis vector for the passed distance in the given space.
  12758. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12759. * Returns the AbstractMesh.
  12760. */
  12761. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12762. var displacementVector = axis.scale(distance);
  12763. if (!space || space === BABYLON.Space.LOCAL) {
  12764. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12765. this.setPositionWithLocalVector(tempV3);
  12766. }
  12767. else {
  12768. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12769. }
  12770. return this;
  12771. };
  12772. /**
  12773. * Adds a rotation step to the mesh current rotation.
  12774. * x, y, z are Euler angles expressed in radians.
  12775. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12776. * This means this rotation is made in the mesh local space only.
  12777. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12778. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12779. * ```javascript
  12780. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12781. * ```
  12782. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12783. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  12784. * Returns the AbstractMesh.
  12785. */
  12786. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12787. var rotationQuaternion;
  12788. if (this.rotationQuaternion) {
  12789. rotationQuaternion = this.rotationQuaternion;
  12790. }
  12791. else {
  12792. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12793. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12794. }
  12795. var accumulation = BABYLON.Tmp.Quaternion[0];
  12796. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12797. rotationQuaternion.multiplyInPlace(accumulation);
  12798. if (!this.rotationQuaternion) {
  12799. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12800. }
  12801. return this;
  12802. };
  12803. /**
  12804. * Retuns the mesh absolute position in the World.
  12805. * Returns a Vector3.
  12806. */
  12807. AbstractMesh.prototype.getAbsolutePosition = function () {
  12808. this.computeWorldMatrix();
  12809. return this._absolutePosition;
  12810. };
  12811. /**
  12812. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12813. * Returns the AbstractMesh.
  12814. */
  12815. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12816. if (!absolutePosition) {
  12817. return;
  12818. }
  12819. var absolutePositionX;
  12820. var absolutePositionY;
  12821. var absolutePositionZ;
  12822. if (absolutePosition.x === undefined) {
  12823. if (arguments.length < 3) {
  12824. return;
  12825. }
  12826. absolutePositionX = arguments[0];
  12827. absolutePositionY = arguments[1];
  12828. absolutePositionZ = arguments[2];
  12829. }
  12830. else {
  12831. absolutePositionX = absolutePosition.x;
  12832. absolutePositionY = absolutePosition.y;
  12833. absolutePositionZ = absolutePosition.z;
  12834. }
  12835. if (this.parent) {
  12836. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12837. invertParentWorldMatrix.invert();
  12838. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12839. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12840. }
  12841. else {
  12842. this.position.x = absolutePositionX;
  12843. this.position.y = absolutePositionY;
  12844. this.position.z = absolutePositionZ;
  12845. }
  12846. return this;
  12847. };
  12848. // ================================== Point of View Movement =================================
  12849. /**
  12850. * Perform relative position change from the point of view of behind the front of the mesh.
  12851. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12852. * Supports definition of mesh facing forward or backward.
  12853. * @param {number} amountRight
  12854. * @param {number} amountUp
  12855. * @param {number} amountForward
  12856. *
  12857. * Returns the AbstractMesh.
  12858. */
  12859. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12860. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12861. return this;
  12862. };
  12863. /**
  12864. * Calculate relative position change from the point of view of behind the front of the mesh.
  12865. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12866. * Supports definition of mesh facing forward or backward.
  12867. * @param {number} amountRight
  12868. * @param {number} amountUp
  12869. * @param {number} amountForward
  12870. *
  12871. * Returns a new Vector3.
  12872. */
  12873. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12874. var rotMatrix = new BABYLON.Matrix();
  12875. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12876. rotQuaternion.toRotationMatrix(rotMatrix);
  12877. var translationDelta = BABYLON.Vector3.Zero();
  12878. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12879. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12880. return translationDelta;
  12881. };
  12882. // ================================== Point of View Rotation =================================
  12883. /**
  12884. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12885. * Supports definition of mesh facing forward or backward.
  12886. * @param {number} flipBack
  12887. * @param {number} twirlClockwise
  12888. * @param {number} tiltRight
  12889. *
  12890. * Returns the AbstractMesh.
  12891. */
  12892. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12893. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12894. return this;
  12895. };
  12896. /**
  12897. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12898. * Supports definition of mesh facing forward or backward.
  12899. * @param {number} flipBack
  12900. * @param {number} twirlClockwise
  12901. * @param {number} tiltRight
  12902. *
  12903. * Returns a new Vector3.
  12904. */
  12905. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12906. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12907. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12908. };
  12909. /**
  12910. * Sets a new pivot matrix to the mesh.
  12911. * Returns the AbstractMesh.
  12912. */
  12913. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12914. this._pivotMatrix = matrix;
  12915. this._cache.pivotMatrixUpdated = true;
  12916. return this;
  12917. };
  12918. /**
  12919. * Returns the mesh pivot matrix.
  12920. * Default : Identity.
  12921. * A Matrix is returned.
  12922. */
  12923. AbstractMesh.prototype.getPivotMatrix = function () {
  12924. return this._pivotMatrix;
  12925. };
  12926. AbstractMesh.prototype._isSynchronized = function () {
  12927. if (this._isDirty) {
  12928. return false;
  12929. }
  12930. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12931. return false;
  12932. if (this._cache.pivotMatrixUpdated) {
  12933. return false;
  12934. }
  12935. if (this.infiniteDistance) {
  12936. return false;
  12937. }
  12938. if (!this._cache.position.equals(this.position))
  12939. return false;
  12940. if (this.rotationQuaternion) {
  12941. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12942. return false;
  12943. }
  12944. if (!this._cache.rotation.equals(this.rotation))
  12945. return false;
  12946. if (!this._cache.scaling.equals(this.scaling))
  12947. return false;
  12948. return true;
  12949. };
  12950. AbstractMesh.prototype._initCache = function () {
  12951. _super.prototype._initCache.call(this);
  12952. this._cache.localMatrixUpdated = false;
  12953. this._cache.position = BABYLON.Vector3.Zero();
  12954. this._cache.scaling = BABYLON.Vector3.Zero();
  12955. this._cache.rotation = BABYLON.Vector3.Zero();
  12956. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12957. this._cache.billboardMode = -1;
  12958. };
  12959. AbstractMesh.prototype.markAsDirty = function (property) {
  12960. if (property === "rotation") {
  12961. this.rotationQuaternion = null;
  12962. }
  12963. this._currentRenderId = Number.MAX_VALUE;
  12964. this._isDirty = true;
  12965. return this;
  12966. };
  12967. /**
  12968. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12969. * Returns the AbstractMesh.
  12970. */
  12971. AbstractMesh.prototype._updateBoundingInfo = function () {
  12972. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12973. this._boundingInfo.update(this.worldMatrixFromCache);
  12974. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12975. return this;
  12976. };
  12977. /**
  12978. * Update a mesh's children BoundingInfo objects only.
  12979. * Returns the AbstractMesh.
  12980. */
  12981. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12982. if (!this.subMeshes) {
  12983. return;
  12984. }
  12985. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12986. var subMesh = this.subMeshes[subIndex];
  12987. if (!subMesh.IsGlobal) {
  12988. subMesh.updateBoundingInfo(matrix);
  12989. }
  12990. }
  12991. return this;
  12992. };
  12993. /**
  12994. * Computes the mesh World matrix and returns it.
  12995. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12996. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12997. * If the parameter `force`is set to `true`, the actual computation is done.
  12998. * Returns the mesh World Matrix.
  12999. */
  13000. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13001. if (this._isWorldMatrixFrozen) {
  13002. return this._worldMatrix;
  13003. }
  13004. if (!force && this.isSynchronized(true)) {
  13005. this._currentRenderId = this.getScene().getRenderId();
  13006. return this._worldMatrix;
  13007. }
  13008. this._cache.position.copyFrom(this.position);
  13009. this._cache.scaling.copyFrom(this.scaling);
  13010. this._cache.pivotMatrixUpdated = false;
  13011. this._cache.billboardMode = this.billboardMode;
  13012. this._currentRenderId = this.getScene().getRenderId();
  13013. this._isDirty = false;
  13014. // Scaling
  13015. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13016. // Rotation
  13017. //rotate, if quaternion is set and rotation was used
  13018. if (this.rotationQuaternion) {
  13019. var len = this.rotation.length();
  13020. if (len) {
  13021. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13022. this.rotation.copyFromFloats(0, 0, 0);
  13023. }
  13024. }
  13025. if (this.rotationQuaternion) {
  13026. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13027. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13028. }
  13029. else {
  13030. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13031. this._cache.rotation.copyFrom(this.rotation);
  13032. }
  13033. // Translation
  13034. if (this.infiniteDistance && !this.parent) {
  13035. var camera = this.getScene().activeCamera;
  13036. if (camera) {
  13037. var cameraWorldMatrix = camera.getWorldMatrix();
  13038. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13039. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13040. }
  13041. }
  13042. else {
  13043. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13044. }
  13045. // Composing transformations
  13046. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13047. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13048. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13049. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13050. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13051. // Need to decompose each rotation here
  13052. var currentPosition = BABYLON.Tmp.Vector3[3];
  13053. if (this.parent && this.parent.getWorldMatrix) {
  13054. if (this._meshToBoneReferal) {
  13055. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13056. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13057. }
  13058. else {
  13059. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13060. }
  13061. }
  13062. else {
  13063. currentPosition.copyFrom(this.position);
  13064. }
  13065. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13066. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13067. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13068. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13069. }
  13070. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13071. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13072. }
  13073. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13074. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13075. }
  13076. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13077. }
  13078. else {
  13079. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13080. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13081. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13082. }
  13083. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13084. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13085. }
  13086. // Local world
  13087. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13088. // Parent
  13089. if (this.parent && this.parent.getWorldMatrix) {
  13090. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13091. if (this._meshToBoneReferal) {
  13092. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13093. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13094. }
  13095. else {
  13096. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13097. }
  13098. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13099. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13100. this._worldMatrix.copyFrom(this._localWorld);
  13101. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13102. }
  13103. else {
  13104. if (this._meshToBoneReferal) {
  13105. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13106. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13107. }
  13108. else {
  13109. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13110. }
  13111. }
  13112. this._markSyncedWithParent();
  13113. }
  13114. else {
  13115. this._worldMatrix.copyFrom(this._localWorld);
  13116. }
  13117. // Bounding info
  13118. this._updateBoundingInfo();
  13119. // Absolute position
  13120. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13121. // Callbacks
  13122. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13123. if (!this._poseMatrix) {
  13124. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13125. }
  13126. return this._worldMatrix;
  13127. };
  13128. /**
  13129. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13130. * @param func: callback function to add
  13131. *
  13132. * Returns the AbstractMesh.
  13133. */
  13134. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13135. this.onAfterWorldMatrixUpdateObservable.add(func);
  13136. return this;
  13137. };
  13138. /**
  13139. * Removes a registered callback function.
  13140. * Returns the AbstractMesh.
  13141. */
  13142. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13143. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13144. return this;
  13145. };
  13146. /**
  13147. * Sets the mesh position in its local space.
  13148. * Returns the AbstractMesh.
  13149. */
  13150. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13151. this.computeWorldMatrix();
  13152. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13153. return this;
  13154. };
  13155. /**
  13156. * Returns the mesh position in the local space from the current World matrix values.
  13157. * Returns a new Vector3.
  13158. */
  13159. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13160. this.computeWorldMatrix();
  13161. var invLocalWorldMatrix = this._localWorld.clone();
  13162. invLocalWorldMatrix.invert();
  13163. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13164. };
  13165. /**
  13166. * Translates the mesh along the passed Vector3 in its local space.
  13167. * Returns the AbstractMesh.
  13168. */
  13169. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13170. this.computeWorldMatrix(true);
  13171. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13172. return this;
  13173. };
  13174. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13175. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13176. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13177. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13178. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13179. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13180. /// <returns>Mesh oriented towards targetMesh</returns>
  13181. if (yawCor === void 0) { yawCor = 0; }
  13182. if (pitchCor === void 0) { pitchCor = 0; }
  13183. if (rollCor === void 0) { rollCor = 0; }
  13184. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13185. var dv = AbstractMesh._lookAtVectorCache;
  13186. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13187. targetPoint.subtractToRef(pos, dv);
  13188. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13189. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13190. var pitch = Math.atan2(dv.y, len);
  13191. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13192. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13193. return this;
  13194. };
  13195. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13196. this._meshToBoneReferal = affectedMesh;
  13197. this.parent = bone;
  13198. if (bone.getWorldMatrix().determinant() < 0) {
  13199. this.scalingDeterminant *= -1;
  13200. }
  13201. return this;
  13202. };
  13203. AbstractMesh.prototype.detachFromBone = function () {
  13204. if (this.parent.getWorldMatrix().determinant() < 0) {
  13205. this.scalingDeterminant *= -1;
  13206. }
  13207. this._meshToBoneReferal = null;
  13208. this.parent = null;
  13209. return this;
  13210. };
  13211. /**
  13212. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13213. * A mesh is in the frustum if its bounding box intersects the frustum.
  13214. * Boolean returned.
  13215. */
  13216. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13217. return this._boundingInfo.isInFrustum(frustumPlanes);
  13218. };
  13219. /**
  13220. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13221. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13222. * Boolean returned.
  13223. */
  13224. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13225. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13226. ;
  13227. };
  13228. /**
  13229. * True if the mesh intersects another mesh or a SolidParticle object.
  13230. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  13231. * Returns a boolean.
  13232. */
  13233. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13234. if (!this._boundingInfo || !mesh._boundingInfo) {
  13235. return false;
  13236. }
  13237. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13238. };
  13239. /**
  13240. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13241. * Returns a boolean.
  13242. */
  13243. AbstractMesh.prototype.intersectsPoint = function (point) {
  13244. if (!this._boundingInfo) {
  13245. return false;
  13246. }
  13247. return this._boundingInfo.intersectsPoint(point);
  13248. };
  13249. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13250. return this.physicsImpostor;
  13251. };
  13252. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13253. if (!camera) {
  13254. camera = this.getScene().activeCamera;
  13255. }
  13256. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13257. };
  13258. /**
  13259. * Returns the distance from the mesh to the active camera.
  13260. * Returns a float.
  13261. */
  13262. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13263. if (!camera) {
  13264. camera = this.getScene().activeCamera;
  13265. }
  13266. return this.absolutePosition.subtract(camera.position).length();
  13267. };
  13268. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13269. if (!this.physicsImpostor) {
  13270. return;
  13271. }
  13272. this.physicsImpostor.applyImpulse(force, contactPoint);
  13273. return this;
  13274. };
  13275. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13276. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13277. return;
  13278. }
  13279. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13280. mainPivot: pivot1,
  13281. connectedPivot: pivot2,
  13282. nativeParams: options
  13283. });
  13284. return this;
  13285. };
  13286. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13287. // Collisions
  13288. /**
  13289. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13290. * Default `false`.
  13291. */
  13292. get: function () {
  13293. return this._checkCollisions;
  13294. },
  13295. set: function (collisionEnabled) {
  13296. this._checkCollisions = collisionEnabled;
  13297. if (this.getScene().workerCollisions) {
  13298. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13299. }
  13300. },
  13301. enumerable: true,
  13302. configurable: true
  13303. });
  13304. AbstractMesh.prototype.moveWithCollisions = function (direction) {
  13305. var globalPosition = this.getAbsolutePosition();
  13306. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13307. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13308. if (!this._collider) {
  13309. this._collider = new BABYLON.Collider();
  13310. }
  13311. this._collider.radius = this.ellipsoid;
  13312. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, direction, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13313. return this;
  13314. };
  13315. // Submeshes octree
  13316. /**
  13317. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13318. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13319. * Returns an Octree of submeshes.
  13320. */
  13321. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13322. if (maxCapacity === void 0) { maxCapacity = 64; }
  13323. if (maxDepth === void 0) { maxDepth = 2; }
  13324. if (!this._submeshesOctree) {
  13325. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13326. }
  13327. this.computeWorldMatrix(true);
  13328. // Update octree
  13329. var bbox = this.getBoundingInfo().boundingBox;
  13330. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13331. return this._submeshesOctree;
  13332. };
  13333. // Collisions
  13334. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13335. this._generatePointsArray();
  13336. // Transformation
  13337. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13338. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13339. subMesh._lastColliderWorldVertices = [];
  13340. subMesh._trianglePlanes = [];
  13341. var start = subMesh.verticesStart;
  13342. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13343. for (var i = start; i < end; i++) {
  13344. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13345. }
  13346. }
  13347. // Collide
  13348. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13349. if (collider.collisionFound) {
  13350. collider.collidedMesh = this;
  13351. }
  13352. return this;
  13353. };
  13354. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13355. var subMeshes;
  13356. var len;
  13357. // Octrees
  13358. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13359. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13360. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13361. len = intersections.length;
  13362. subMeshes = intersections.data;
  13363. }
  13364. else {
  13365. subMeshes = this.subMeshes;
  13366. len = subMeshes.length;
  13367. }
  13368. for (var index = 0; index < len; index++) {
  13369. var subMesh = subMeshes[index];
  13370. // Bounding test
  13371. if (len > 1 && !subMesh._checkCollision(collider))
  13372. continue;
  13373. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13374. }
  13375. return this;
  13376. };
  13377. AbstractMesh.prototype._checkCollision = function (collider) {
  13378. // Bounding box test
  13379. if (!this._boundingInfo._checkCollision(collider))
  13380. return this;
  13381. // Transformation matrix
  13382. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13383. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13384. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13385. return this;
  13386. };
  13387. // Picking
  13388. AbstractMesh.prototype._generatePointsArray = function () {
  13389. return false;
  13390. };
  13391. /**
  13392. * Checks if the passed Ray intersects with the mesh.
  13393. * Returns an object PickingInfo.
  13394. */
  13395. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13396. var pickingInfo = new BABYLON.PickingInfo();
  13397. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13398. return pickingInfo;
  13399. }
  13400. if (!this._generatePointsArray()) {
  13401. return pickingInfo;
  13402. }
  13403. var intersectInfo = null;
  13404. // Octrees
  13405. var subMeshes;
  13406. var len;
  13407. if (this._submeshesOctree && this.useOctreeForPicking) {
  13408. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13409. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13410. len = intersections.length;
  13411. subMeshes = intersections.data;
  13412. }
  13413. else {
  13414. subMeshes = this.subMeshes;
  13415. len = subMeshes.length;
  13416. }
  13417. for (var index = 0; index < len; index++) {
  13418. var subMesh = subMeshes[index];
  13419. // Bounding test
  13420. if (len > 1 && !subMesh.canIntersects(ray))
  13421. continue;
  13422. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13423. if (currentIntersectInfo) {
  13424. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13425. intersectInfo = currentIntersectInfo;
  13426. intersectInfo.subMeshId = index;
  13427. if (fastCheck) {
  13428. break;
  13429. }
  13430. }
  13431. }
  13432. }
  13433. if (intersectInfo) {
  13434. // Get picked point
  13435. var world = this.getWorldMatrix();
  13436. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13437. var direction = ray.direction.clone();
  13438. direction = direction.scale(intersectInfo.distance);
  13439. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13440. var pickedPoint = worldOrigin.add(worldDirection);
  13441. // Return result
  13442. pickingInfo.hit = true;
  13443. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13444. pickingInfo.pickedPoint = pickedPoint;
  13445. pickingInfo.pickedMesh = this;
  13446. pickingInfo.bu = intersectInfo.bu;
  13447. pickingInfo.bv = intersectInfo.bv;
  13448. pickingInfo.faceId = intersectInfo.faceId;
  13449. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13450. return pickingInfo;
  13451. }
  13452. return pickingInfo;
  13453. };
  13454. /**
  13455. * Clones the mesh, used by the class Mesh.
  13456. * Just returns `null` for an AbstractMesh.
  13457. */
  13458. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13459. return null;
  13460. };
  13461. /**
  13462. * Disposes all the mesh submeshes.
  13463. * Returns the AbstractMesh.
  13464. */
  13465. AbstractMesh.prototype.releaseSubMeshes = function () {
  13466. if (this.subMeshes) {
  13467. while (this.subMeshes.length) {
  13468. this.subMeshes[0].dispose();
  13469. }
  13470. }
  13471. else {
  13472. this.subMeshes = new Array();
  13473. }
  13474. return this;
  13475. };
  13476. /**
  13477. * Disposes the AbstractMesh.
  13478. * Some internal references are kept for further use.
  13479. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13480. * Returns nothing.
  13481. */
  13482. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13483. var _this = this;
  13484. var index;
  13485. // Action manager
  13486. if (this.actionManager) {
  13487. this.actionManager.dispose();
  13488. this.actionManager = null;
  13489. }
  13490. // Skeleton
  13491. this.skeleton = null;
  13492. // Animations
  13493. this.getScene().stopAnimation(this);
  13494. // Physics
  13495. if (this.physicsImpostor) {
  13496. this.physicsImpostor.dispose();
  13497. }
  13498. // Intersections in progress
  13499. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13500. var other = this._intersectionsInProgress[index];
  13501. var pos = other._intersectionsInProgress.indexOf(this);
  13502. other._intersectionsInProgress.splice(pos, 1);
  13503. }
  13504. this._intersectionsInProgress = [];
  13505. // Lights
  13506. var lights = this.getScene().lights;
  13507. lights.forEach(function (light) {
  13508. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13509. if (meshIndex !== -1) {
  13510. light.includedOnlyMeshes.splice(meshIndex, 1);
  13511. }
  13512. meshIndex = light.excludedMeshes.indexOf(_this);
  13513. if (meshIndex !== -1) {
  13514. light.excludedMeshes.splice(meshIndex, 1);
  13515. }
  13516. // Shadow generators
  13517. var generator = light.getShadowGenerator();
  13518. if (generator) {
  13519. var shadowMap = generator.getShadowMap();
  13520. meshIndex = shadowMap.renderList.indexOf(_this);
  13521. if (meshIndex !== -1) {
  13522. shadowMap.renderList.splice(meshIndex, 1);
  13523. }
  13524. }
  13525. });
  13526. // Edges
  13527. if (this._edgesRenderer) {
  13528. this._edgesRenderer.dispose();
  13529. this._edgesRenderer = null;
  13530. }
  13531. // SubMeshes
  13532. if (this.getClassName() !== "InstancedMesh") {
  13533. this.releaseSubMeshes();
  13534. }
  13535. // Octree
  13536. var sceneOctree = this.getScene().selectionOctree;
  13537. if (sceneOctree) {
  13538. var index = sceneOctree.dynamicContent.indexOf(this);
  13539. if (index !== -1) {
  13540. sceneOctree.dynamicContent.splice(index, 1);
  13541. }
  13542. }
  13543. // Query
  13544. var engine = this.getScene().getEngine();
  13545. if (this._occlusionQuery) {
  13546. this._isOcclusionQueryInProgress = false;
  13547. engine.deleteQuery(this._occlusionQuery);
  13548. this._occlusionQuery = null;
  13549. }
  13550. // Engine
  13551. engine.wipeCaches();
  13552. // Remove from scene
  13553. this.getScene().removeMesh(this);
  13554. if (!doNotRecurse) {
  13555. // Particles
  13556. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13557. if (this.getScene().particleSystems[index].emitter === this) {
  13558. this.getScene().particleSystems[index].dispose();
  13559. index--;
  13560. }
  13561. }
  13562. // Children
  13563. var objects = this.getDescendants(true);
  13564. for (index = 0; index < objects.length; index++) {
  13565. objects[index].dispose();
  13566. }
  13567. }
  13568. else {
  13569. var childMeshes = this.getChildMeshes(true);
  13570. for (index = 0; index < childMeshes.length; index++) {
  13571. var child = childMeshes[index];
  13572. child.parent = null;
  13573. child.computeWorldMatrix(true);
  13574. }
  13575. }
  13576. // facet data
  13577. if (this._facetDataEnabled) {
  13578. this.disableFacetData();
  13579. }
  13580. this.onAfterWorldMatrixUpdateObservable.clear();
  13581. this.onCollideObservable.clear();
  13582. this.onCollisionPositionChangeObservable.clear();
  13583. this._isDisposed = true;
  13584. _super.prototype.dispose.call(this);
  13585. };
  13586. /**
  13587. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13588. * This Vector3 is expressed in the World space.
  13589. */
  13590. AbstractMesh.prototype.getDirection = function (localAxis) {
  13591. var result = BABYLON.Vector3.Zero();
  13592. this.getDirectionToRef(localAxis, result);
  13593. return result;
  13594. };
  13595. /**
  13596. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13597. * localAxis is expressed in the mesh local space.
  13598. * result is computed in the Wordl space from the mesh World matrix.
  13599. * Returns the AbstractMesh.
  13600. */
  13601. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13602. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13603. return this;
  13604. };
  13605. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13606. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13607. if (this.getScene().getRenderId() == 0) {
  13608. this.computeWorldMatrix(true);
  13609. }
  13610. var wm = this.getWorldMatrix();
  13611. if (space == BABYLON.Space.WORLD) {
  13612. var tmat = BABYLON.Tmp.Matrix[0];
  13613. wm.invertToRef(tmat);
  13614. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13615. }
  13616. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13617. this._pivotMatrix.m[12] = -point.x;
  13618. this._pivotMatrix.m[13] = -point.y;
  13619. this._pivotMatrix.m[14] = -point.z;
  13620. this._cache.pivotMatrixUpdated = true;
  13621. return this;
  13622. };
  13623. /**
  13624. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13625. */
  13626. AbstractMesh.prototype.getPivotPoint = function () {
  13627. var point = BABYLON.Vector3.Zero();
  13628. this.getPivotPointToRef(point);
  13629. return point;
  13630. };
  13631. /**
  13632. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13633. * Returns the AbstractMesh.
  13634. */
  13635. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13636. result.x = -this._pivotMatrix.m[12];
  13637. result.y = -this._pivotMatrix.m[13];
  13638. result.z = -this._pivotMatrix.m[14];
  13639. return this;
  13640. };
  13641. /**
  13642. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13643. */
  13644. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13645. var point = BABYLON.Vector3.Zero();
  13646. this.getAbsolutePivotPointToRef(point);
  13647. return point;
  13648. };
  13649. /**
  13650. * Defines the passed mesh as the parent of the current mesh.
  13651. * Returns the AbstractMesh.
  13652. */
  13653. AbstractMesh.prototype.setParent = function (mesh) {
  13654. var child = this;
  13655. var parent = mesh;
  13656. if (mesh == null) {
  13657. var rotation = BABYLON.Tmp.Quaternion[0];
  13658. var position = BABYLON.Tmp.Vector3[0];
  13659. var scale = BABYLON.Tmp.Vector3[1];
  13660. child.getWorldMatrix().decompose(scale, rotation, position);
  13661. if (child.rotationQuaternion) {
  13662. child.rotationQuaternion.copyFrom(rotation);
  13663. }
  13664. else {
  13665. rotation.toEulerAnglesToRef(child.rotation);
  13666. }
  13667. child.position.x = position.x;
  13668. child.position.y = position.y;
  13669. child.position.z = position.z;
  13670. }
  13671. else {
  13672. var rotation = BABYLON.Tmp.Quaternion[0];
  13673. var position = BABYLON.Tmp.Vector3[0];
  13674. var scale = BABYLON.Tmp.Vector3[1];
  13675. var m1 = BABYLON.Tmp.Matrix[0];
  13676. var m2 = BABYLON.Tmp.Matrix[1];
  13677. parent.getWorldMatrix().decompose(scale, rotation, position);
  13678. rotation.toRotationMatrix(m1);
  13679. m2.setTranslation(position);
  13680. m2.multiplyToRef(m1, m1);
  13681. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13682. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13683. m.decompose(scale, rotation, position);
  13684. if (child.rotationQuaternion) {
  13685. child.rotationQuaternion.copyFrom(rotation);
  13686. }
  13687. else {
  13688. rotation.toEulerAnglesToRef(child.rotation);
  13689. }
  13690. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13691. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13692. m.decompose(scale, rotation, position);
  13693. child.position.x = position.x;
  13694. child.position.y = position.y;
  13695. child.position.z = position.z;
  13696. }
  13697. child.parent = parent;
  13698. return this;
  13699. };
  13700. /**
  13701. * Adds the passed mesh as a child to the current mesh.
  13702. * Returns the AbstractMesh.
  13703. */
  13704. AbstractMesh.prototype.addChild = function (mesh) {
  13705. mesh.setParent(this);
  13706. return this;
  13707. };
  13708. /**
  13709. * Removes the passed mesh from the current mesh children list.
  13710. * Returns the AbstractMesh.
  13711. */
  13712. AbstractMesh.prototype.removeChild = function (mesh) {
  13713. mesh.setParent(null);
  13714. return this;
  13715. };
  13716. /**
  13717. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13718. * Returns the AbstractMesh.
  13719. */
  13720. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13721. result.x = this._pivotMatrix.m[12];
  13722. result.y = this._pivotMatrix.m[13];
  13723. result.z = this._pivotMatrix.m[14];
  13724. this.getPivotPointToRef(result);
  13725. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13726. return this;
  13727. };
  13728. // Facet data
  13729. /**
  13730. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13731. * Returns the AbstractMesh.
  13732. */
  13733. AbstractMesh.prototype._initFacetData = function () {
  13734. if (!this._facetNormals) {
  13735. this._facetNormals = new Array();
  13736. }
  13737. if (!this._facetPositions) {
  13738. this._facetPositions = new Array();
  13739. }
  13740. if (!this._facetPartitioning) {
  13741. this._facetPartitioning = new Array();
  13742. }
  13743. this._facetNb = this.getIndices().length / 3;
  13744. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13745. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13746. for (var f = 0; f < this._facetNb; f++) {
  13747. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13748. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13749. }
  13750. this._facetDataEnabled = true;
  13751. return this;
  13752. };
  13753. /**
  13754. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13755. * This method can be called within the render loop.
  13756. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  13757. * Returns the AbstractMesh.
  13758. */
  13759. AbstractMesh.prototype.updateFacetData = function () {
  13760. if (!this._facetDataEnabled) {
  13761. this._initFacetData();
  13762. }
  13763. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13764. var indices = this.getIndices();
  13765. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13766. var bInfo = this.getBoundingInfo();
  13767. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13768. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13769. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13770. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13771. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13772. this._subDiv.max = this._partitioningSubdivisions;
  13773. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13774. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13775. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13776. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13777. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13778. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13779. // set the parameters for ComputeNormals()
  13780. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13781. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13782. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13783. this._facetParameters.bInfo = bInfo;
  13784. this._facetParameters.bbSize = this._bbSize;
  13785. this._facetParameters.subDiv = this._subDiv;
  13786. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13787. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13788. return this;
  13789. };
  13790. /**
  13791. * Returns the facetLocalNormals array.
  13792. * The normals are expressed in the mesh local space.
  13793. */
  13794. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13795. if (!this._facetNormals) {
  13796. this.updateFacetData();
  13797. }
  13798. return this._facetNormals;
  13799. };
  13800. /**
  13801. * Returns the facetLocalPositions array.
  13802. * The facet positions are expressed in the mesh local space.
  13803. */
  13804. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13805. if (!this._facetPositions) {
  13806. this.updateFacetData();
  13807. }
  13808. return this._facetPositions;
  13809. };
  13810. /**
  13811. * Returns the facetLocalPartioning array.
  13812. */
  13813. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13814. if (!this._facetPartitioning) {
  13815. this.updateFacetData();
  13816. }
  13817. return this._facetPartitioning;
  13818. };
  13819. /**
  13820. * Returns the i-th facet position in the world system.
  13821. * This method allocates a new Vector3 per call.
  13822. */
  13823. AbstractMesh.prototype.getFacetPosition = function (i) {
  13824. var pos = BABYLON.Vector3.Zero();
  13825. this.getFacetPositionToRef(i, pos);
  13826. return pos;
  13827. };
  13828. /**
  13829. * Sets the reference Vector3 with the i-th facet position in the world system.
  13830. * Returns the AbstractMesh.
  13831. */
  13832. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13833. var localPos = (this.getFacetLocalPositions())[i];
  13834. var world = this.getWorldMatrix();
  13835. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13836. return this;
  13837. };
  13838. /**
  13839. * Returns the i-th facet normal in the world system.
  13840. * This method allocates a new Vector3 per call.
  13841. */
  13842. AbstractMesh.prototype.getFacetNormal = function (i) {
  13843. var norm = BABYLON.Vector3.Zero();
  13844. this.getFacetNormalToRef(i, norm);
  13845. return norm;
  13846. };
  13847. /**
  13848. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13849. * Returns the AbstractMesh.
  13850. */
  13851. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13852. var localNorm = (this.getFacetLocalNormals())[i];
  13853. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13854. return this;
  13855. };
  13856. /**
  13857. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  13858. */
  13859. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13860. var bInfo = this.getBoundingInfo();
  13861. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13862. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13863. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13864. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13865. return null;
  13866. }
  13867. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13868. };
  13869. /**
  13870. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13871. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13872. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13873. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13874. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13875. */
  13876. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13877. if (checkFace === void 0) { checkFace = false; }
  13878. if (facing === void 0) { facing = true; }
  13879. var world = this.getWorldMatrix();
  13880. var invMat = BABYLON.Tmp.Matrix[5];
  13881. world.invertToRef(invMat);
  13882. var invVect = BABYLON.Tmp.Vector3[8];
  13883. var closest = null;
  13884. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13885. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13886. if (projected) {
  13887. // tranform the local computed projected vector to world coordinates
  13888. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13889. }
  13890. return closest;
  13891. };
  13892. /**
  13893. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13894. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13895. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13896. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13897. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13898. */
  13899. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13900. if (checkFace === void 0) { checkFace = false; }
  13901. if (facing === void 0) { facing = true; }
  13902. var closest = null;
  13903. var tmpx = 0.0;
  13904. var tmpy = 0.0;
  13905. var tmpz = 0.0;
  13906. var d = 0.0; // tmp dot facet normal * facet position
  13907. var t0 = 0.0;
  13908. var projx = 0.0;
  13909. var projy = 0.0;
  13910. var projz = 0.0;
  13911. // Get all the facets in the same partitioning block than (x, y, z)
  13912. var facetPositions = this.getFacetLocalPositions();
  13913. var facetNormals = this.getFacetLocalNormals();
  13914. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13915. if (!facetsInBlock) {
  13916. return null;
  13917. }
  13918. // Get the closest facet to (x, y, z)
  13919. var shortest = Number.MAX_VALUE; // init distance vars
  13920. var tmpDistance = shortest;
  13921. var fib; // current facet in the block
  13922. var norm; // current facet normal
  13923. var p0; // current facet barycenter position
  13924. // loop on all the facets in the current partitioning block
  13925. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13926. fib = facetsInBlock[idx];
  13927. norm = facetNormals[fib];
  13928. p0 = facetPositions[fib];
  13929. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13930. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13931. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13932. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13933. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13934. projx = x + norm.x * t0;
  13935. projy = y + norm.y * t0;
  13936. projz = z + norm.z * t0;
  13937. tmpx = projx - x;
  13938. tmpy = projy - y;
  13939. tmpz = projz - z;
  13940. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13941. if (tmpDistance < shortest) {
  13942. shortest = tmpDistance;
  13943. closest = fib;
  13944. if (projected) {
  13945. projected.x = projx;
  13946. projected.y = projy;
  13947. projected.z = projz;
  13948. }
  13949. }
  13950. }
  13951. }
  13952. return closest;
  13953. };
  13954. /**
  13955. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13956. */
  13957. AbstractMesh.prototype.getFacetDataParameters = function () {
  13958. return this._facetParameters;
  13959. };
  13960. /**
  13961. * Disables the feature FacetData and frees the related memory.
  13962. * Returns the AbstractMesh.
  13963. */
  13964. AbstractMesh.prototype.disableFacetData = function () {
  13965. if (this._facetDataEnabled) {
  13966. this._facetDataEnabled = false;
  13967. this._facetPositions = null;
  13968. this._facetNormals = null;
  13969. this._facetPartitioning = null;
  13970. this._facetParameters = null;
  13971. }
  13972. return this;
  13973. };
  13974. /**
  13975. * Creates new normals data for the mesh.
  13976. * @param updatable.
  13977. */
  13978. AbstractMesh.prototype.createNormals = function (updatable) {
  13979. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13980. var indices = this.getIndices();
  13981. var normals;
  13982. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13983. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13984. }
  13985. else {
  13986. normals = [];
  13987. }
  13988. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13989. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13990. };
  13991. AbstractMesh.prototype.checkOcclusionQuery = function () {
  13992. var engine = this.getEngine();
  13993. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  13994. this._isOccluded = false;
  13995. return;
  13996. }
  13997. if (this.isOcclusionQueryInProgress) {
  13998. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  13999. if (isOcclusionQueryAvailable) {
  14000. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14001. this._isOcclusionQueryInProgress = false;
  14002. this._occlusionInternalRetryCounter = 0;
  14003. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14004. }
  14005. else {
  14006. this._occlusionInternalRetryCounter++;
  14007. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14008. this._isOcclusionQueryInProgress = false;
  14009. this._occlusionInternalRetryCounter = 0;
  14010. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14011. // if strict continue the last state of the object.
  14012. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14013. }
  14014. else {
  14015. return;
  14016. }
  14017. }
  14018. }
  14019. var scene = this.getScene();
  14020. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14021. if (!this._occlusionQuery) {
  14022. this._occlusionQuery = engine.createQuery();
  14023. }
  14024. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14025. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14026. engine.endQuery(this.occlusionQueryAlgorithmType);
  14027. this._isOcclusionQueryInProgress = true;
  14028. };
  14029. // Statics
  14030. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14031. AbstractMesh._BILLBOARDMODE_X = 1;
  14032. AbstractMesh._BILLBOARDMODE_Y = 2;
  14033. AbstractMesh._BILLBOARDMODE_Z = 4;
  14034. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14035. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14036. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14037. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14038. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14039. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14040. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14041. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14042. return AbstractMesh;
  14043. }(BABYLON.Node));
  14044. BABYLON.AbstractMesh = AbstractMesh;
  14045. })(BABYLON || (BABYLON = {}));
  14046. //# sourceMappingURL=babylon.abstractMesh.js.map
  14047. var BABYLON;
  14048. (function (BABYLON) {
  14049. var Light = (function (_super) {
  14050. __extends(Light, _super);
  14051. /**
  14052. * Creates a Light object in the scene.
  14053. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14054. */
  14055. function Light(name, scene) {
  14056. var _this = _super.call(this, name, scene) || this;
  14057. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14058. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14059. _this.intensity = 1.0;
  14060. _this.range = Number.MAX_VALUE;
  14061. /**
  14062. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14063. * of light.
  14064. */
  14065. _this._photometricScale = 1.0;
  14066. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14067. _this._radius = 0.00001;
  14068. _this.renderPriority = 0;
  14069. /**
  14070. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14071. * the current shadow generator.
  14072. */
  14073. _this.shadowEnabled = true;
  14074. _this._excludeWithLayerMask = 0;
  14075. _this._includeOnlyWithLayerMask = 0;
  14076. _this._lightmapMode = 0;
  14077. _this._excludedMeshesIds = new Array();
  14078. _this._includedOnlyMeshesIds = new Array();
  14079. _this.getScene().addLight(_this);
  14080. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14081. _this._buildUniformLayout();
  14082. _this.includedOnlyMeshes = new Array();
  14083. _this.excludedMeshes = new Array();
  14084. _this._resyncMeshes();
  14085. return _this;
  14086. }
  14087. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14088. /**
  14089. * If every light affecting the material is in this lightmapMode,
  14090. * material.lightmapTexture adds or multiplies
  14091. * (depends on material.useLightmapAsShadowmap)
  14092. * after every other light calculations.
  14093. */
  14094. get: function () {
  14095. return Light._LIGHTMAP_DEFAULT;
  14096. },
  14097. enumerable: true,
  14098. configurable: true
  14099. });
  14100. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14101. /**
  14102. * material.lightmapTexture as only diffuse lighting from this light
  14103. * adds pnly specular lighting from this light
  14104. * adds dynamic shadows
  14105. */
  14106. get: function () {
  14107. return Light._LIGHTMAP_SPECULAR;
  14108. },
  14109. enumerable: true,
  14110. configurable: true
  14111. });
  14112. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14113. /**
  14114. * material.lightmapTexture as only lighting
  14115. * no light calculation from this light
  14116. * only adds dynamic shadows from this light
  14117. */
  14118. get: function () {
  14119. return Light._LIGHTMAP_SHADOWSONLY;
  14120. },
  14121. enumerable: true,
  14122. configurable: true
  14123. });
  14124. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14125. /**
  14126. * Each light type uses the default quantity according to its type:
  14127. * point/spot lights use luminous intensity
  14128. * directional lights use illuminance
  14129. */
  14130. get: function () {
  14131. return Light._INTENSITYMODE_AUTOMATIC;
  14132. },
  14133. enumerable: true,
  14134. configurable: true
  14135. });
  14136. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14137. /**
  14138. * lumen (lm)
  14139. */
  14140. get: function () {
  14141. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14142. },
  14143. enumerable: true,
  14144. configurable: true
  14145. });
  14146. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14147. /**
  14148. * candela (lm/sr)
  14149. */
  14150. get: function () {
  14151. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14152. },
  14153. enumerable: true,
  14154. configurable: true
  14155. });
  14156. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14157. /**
  14158. * lux (lm/m^2)
  14159. */
  14160. get: function () {
  14161. return Light._INTENSITYMODE_ILLUMINANCE;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14167. /**
  14168. * nit (cd/m^2)
  14169. */
  14170. get: function () {
  14171. return Light._INTENSITYMODE_LUMINANCE;
  14172. },
  14173. enumerable: true,
  14174. configurable: true
  14175. });
  14176. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14177. /**
  14178. * Light type const id of the point light.
  14179. */
  14180. get: function () {
  14181. return Light._LIGHTTYPEID_POINTLIGHT;
  14182. },
  14183. enumerable: true,
  14184. configurable: true
  14185. });
  14186. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14187. /**
  14188. * Light type const id of the directional light.
  14189. */
  14190. get: function () {
  14191. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14192. },
  14193. enumerable: true,
  14194. configurable: true
  14195. });
  14196. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14197. /**
  14198. * Light type const id of the spot light.
  14199. */
  14200. get: function () {
  14201. return Light._LIGHTTYPEID_SPOTLIGHT;
  14202. },
  14203. enumerable: true,
  14204. configurable: true
  14205. });
  14206. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14207. /**
  14208. * Light type const id of the hemispheric light.
  14209. */
  14210. get: function () {
  14211. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14212. },
  14213. enumerable: true,
  14214. configurable: true
  14215. });
  14216. Object.defineProperty(Light.prototype, "intensityMode", {
  14217. /**
  14218. * Gets the photometric scale used to interpret the intensity.
  14219. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14220. */
  14221. get: function () {
  14222. return this._intensityMode;
  14223. },
  14224. /**
  14225. * Sets the photometric scale used to interpret the intensity.
  14226. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14227. */
  14228. set: function (value) {
  14229. this._intensityMode = value;
  14230. this._computePhotometricScale();
  14231. },
  14232. enumerable: true,
  14233. configurable: true
  14234. });
  14235. ;
  14236. ;
  14237. Object.defineProperty(Light.prototype, "radius", {
  14238. /**
  14239. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14240. */
  14241. get: function () {
  14242. return this._radius;
  14243. },
  14244. /**
  14245. * sets the light radius used by PBR Materials to simulate soft area lights.
  14246. */
  14247. set: function (value) {
  14248. this._radius = value;
  14249. this._computePhotometricScale();
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. ;
  14255. ;
  14256. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14257. get: function () {
  14258. return this._includedOnlyMeshes;
  14259. },
  14260. set: function (value) {
  14261. this._includedOnlyMeshes = value;
  14262. this._hookArrayForIncludedOnly(value);
  14263. },
  14264. enumerable: true,
  14265. configurable: true
  14266. });
  14267. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14268. get: function () {
  14269. return this._excludedMeshes;
  14270. },
  14271. set: function (value) {
  14272. this._excludedMeshes = value;
  14273. this._hookArrayForExcluded(value);
  14274. },
  14275. enumerable: true,
  14276. configurable: true
  14277. });
  14278. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14279. get: function () {
  14280. return this._excludeWithLayerMask;
  14281. },
  14282. set: function (value) {
  14283. this._excludeWithLayerMask = value;
  14284. this._resyncMeshes();
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14290. get: function () {
  14291. return this._includeOnlyWithLayerMask;
  14292. },
  14293. set: function (value) {
  14294. this._includeOnlyWithLayerMask = value;
  14295. this._resyncMeshes();
  14296. },
  14297. enumerable: true,
  14298. configurable: true
  14299. });
  14300. Object.defineProperty(Light.prototype, "lightmapMode", {
  14301. get: function () {
  14302. return this._lightmapMode;
  14303. },
  14304. set: function (value) {
  14305. if (this._lightmapMode === value) {
  14306. return;
  14307. }
  14308. this._lightmapMode = value;
  14309. this._markMeshesAsLightDirty();
  14310. },
  14311. enumerable: true,
  14312. configurable: true
  14313. });
  14314. Light.prototype._buildUniformLayout = function () {
  14315. // Overridden
  14316. };
  14317. /**
  14318. * Returns the string "Light".
  14319. */
  14320. Light.prototype.getClassName = function () {
  14321. return "Light";
  14322. };
  14323. /**
  14324. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14325. */
  14326. Light.prototype.toString = function (fullDetails) {
  14327. var ret = "Name: " + this.name;
  14328. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14329. if (this.animations) {
  14330. for (var i = 0; i < this.animations.length; i++) {
  14331. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14332. }
  14333. }
  14334. if (fullDetails) {
  14335. }
  14336. return ret;
  14337. };
  14338. /**
  14339. * Set the enabled state of this node.
  14340. * @param {boolean} value - the new enabled state
  14341. * @see isEnabled
  14342. */
  14343. Light.prototype.setEnabled = function (value) {
  14344. _super.prototype.setEnabled.call(this, value);
  14345. this._resyncMeshes();
  14346. };
  14347. /**
  14348. * Returns the Light associated shadow generator.
  14349. */
  14350. Light.prototype.getShadowGenerator = function () {
  14351. return this._shadowGenerator;
  14352. };
  14353. /**
  14354. * Returns a Vector3, the absolute light position in the World.
  14355. */
  14356. Light.prototype.getAbsolutePosition = function () {
  14357. return BABYLON.Vector3.Zero();
  14358. };
  14359. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14360. };
  14361. Light.prototype._getWorldMatrix = function () {
  14362. return BABYLON.Matrix.Identity();
  14363. };
  14364. /**
  14365. * Boolean : True if the light will affect the passed mesh.
  14366. */
  14367. Light.prototype.canAffectMesh = function (mesh) {
  14368. if (!mesh) {
  14369. return true;
  14370. }
  14371. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14372. return false;
  14373. }
  14374. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14375. return false;
  14376. }
  14377. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14378. return false;
  14379. }
  14380. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14381. return false;
  14382. }
  14383. return true;
  14384. };
  14385. /**
  14386. * Returns the light World matrix.
  14387. */
  14388. Light.prototype.getWorldMatrix = function () {
  14389. this._currentRenderId = this.getScene().getRenderId();
  14390. var worldMatrix = this._getWorldMatrix();
  14391. if (this.parent && this.parent.getWorldMatrix) {
  14392. if (!this._parentedWorldMatrix) {
  14393. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14394. }
  14395. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14396. this._markSyncedWithParent();
  14397. return this._parentedWorldMatrix;
  14398. }
  14399. return worldMatrix;
  14400. };
  14401. /**
  14402. * Sort function to order lights for rendering.
  14403. * @param a First Light object to compare to second.
  14404. * @param b Second Light object to compare first.
  14405. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14406. */
  14407. Light.compareLightsPriority = function (a, b) {
  14408. //shadow-casting lights have priority over non-shadow-casting lights
  14409. //the renderPrioirty is a secondary sort criterion
  14410. if (a.shadowEnabled !== b.shadowEnabled) {
  14411. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14412. }
  14413. return b.renderPriority - a.renderPriority;
  14414. };
  14415. /**
  14416. * Disposes the light.
  14417. */
  14418. Light.prototype.dispose = function () {
  14419. if (this._shadowGenerator) {
  14420. this._shadowGenerator.dispose();
  14421. this._shadowGenerator = null;
  14422. }
  14423. // Animations
  14424. this.getScene().stopAnimation(this);
  14425. // Remove from meshes
  14426. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14427. var mesh = _a[_i];
  14428. mesh._removeLightSource(this);
  14429. }
  14430. this._uniformBuffer.dispose();
  14431. // Remove from scene
  14432. this.getScene().removeLight(this);
  14433. _super.prototype.dispose.call(this);
  14434. };
  14435. /**
  14436. * Returns the light type ID (integer).
  14437. */
  14438. Light.prototype.getTypeID = function () {
  14439. return 0;
  14440. };
  14441. /**
  14442. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14443. */
  14444. Light.prototype.getScaledIntensity = function () {
  14445. return this._photometricScale * this.intensity;
  14446. };
  14447. /**
  14448. * Returns a new Light object, named "name", from the current one.
  14449. */
  14450. Light.prototype.clone = function (name) {
  14451. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14452. };
  14453. /**
  14454. * Serializes the current light into a Serialization object.
  14455. * Returns the serialized object.
  14456. */
  14457. Light.prototype.serialize = function () {
  14458. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14459. // Type
  14460. serializationObject.type = this.getTypeID();
  14461. // Parent
  14462. if (this.parent) {
  14463. serializationObject.parentId = this.parent.id;
  14464. }
  14465. // Inclusion / exclusions
  14466. if (this.excludedMeshes.length > 0) {
  14467. serializationObject.excludedMeshesIds = [];
  14468. this.excludedMeshes.forEach(function (mesh) {
  14469. serializationObject.excludedMeshesIds.push(mesh.id);
  14470. });
  14471. }
  14472. if (this.includedOnlyMeshes.length > 0) {
  14473. serializationObject.includedOnlyMeshesIds = [];
  14474. this.includedOnlyMeshes.forEach(function (mesh) {
  14475. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14476. });
  14477. }
  14478. // Animations
  14479. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14480. serializationObject.ranges = this.serializeAnimationRanges();
  14481. return serializationObject;
  14482. };
  14483. /**
  14484. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14485. * This new light is named "name" and added to the passed scene.
  14486. */
  14487. Light.GetConstructorFromName = function (type, name, scene) {
  14488. switch (type) {
  14489. case 0:
  14490. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14491. case 1:
  14492. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14493. case 2:
  14494. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14495. case 3:
  14496. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14497. }
  14498. };
  14499. /**
  14500. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14501. */
  14502. Light.Parse = function (parsedLight, scene) {
  14503. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14504. // Inclusion / exclusions
  14505. if (parsedLight.excludedMeshesIds) {
  14506. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14507. }
  14508. if (parsedLight.includedOnlyMeshesIds) {
  14509. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14510. }
  14511. // Parent
  14512. if (parsedLight.parentId) {
  14513. light._waitingParentId = parsedLight.parentId;
  14514. }
  14515. // Animations
  14516. if (parsedLight.animations) {
  14517. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14518. var parsedAnimation = parsedLight.animations[animationIndex];
  14519. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14520. }
  14521. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14522. }
  14523. if (parsedLight.autoAnimate) {
  14524. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14525. }
  14526. return light;
  14527. };
  14528. Light.prototype._hookArrayForExcluded = function (array) {
  14529. var _this = this;
  14530. var oldPush = array.push;
  14531. array.push = function () {
  14532. var items = [];
  14533. for (var _i = 0; _i < arguments.length; _i++) {
  14534. items[_i] = arguments[_i];
  14535. }
  14536. var result = oldPush.apply(array, items);
  14537. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14538. var item = items_1[_a];
  14539. item._resyncLighSource(_this);
  14540. }
  14541. return result;
  14542. };
  14543. var oldSplice = array.splice;
  14544. array.splice = function (index, deleteCount) {
  14545. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14546. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14547. var item = deleted_1[_i];
  14548. item._resyncLighSource(_this);
  14549. }
  14550. return deleted;
  14551. };
  14552. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14553. var item = array_1[_i];
  14554. item._resyncLighSource(this);
  14555. }
  14556. };
  14557. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14558. var _this = this;
  14559. var oldPush = array.push;
  14560. array.push = function () {
  14561. var items = [];
  14562. for (var _i = 0; _i < arguments.length; _i++) {
  14563. items[_i] = arguments[_i];
  14564. }
  14565. var result = oldPush.apply(array, items);
  14566. _this._resyncMeshes();
  14567. return result;
  14568. };
  14569. var oldSplice = array.splice;
  14570. array.splice = function (index, deleteCount) {
  14571. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14572. _this._resyncMeshes();
  14573. return deleted;
  14574. };
  14575. this._resyncMeshes();
  14576. };
  14577. Light.prototype._resyncMeshes = function () {
  14578. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14579. var mesh = _a[_i];
  14580. mesh._resyncLighSource(this);
  14581. }
  14582. };
  14583. Light.prototype._markMeshesAsLightDirty = function () {
  14584. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14585. var mesh = _a[_i];
  14586. if (mesh._lightSources.indexOf(this) !== -1) {
  14587. mesh._markSubMeshesAsLightDirty();
  14588. }
  14589. }
  14590. };
  14591. /**
  14592. * Recomputes the cached photometric scale if needed.
  14593. */
  14594. Light.prototype._computePhotometricScale = function () {
  14595. this._photometricScale = this._getPhotometricScale();
  14596. this.getScene().resetCachedMaterial();
  14597. };
  14598. /**
  14599. * Returns the Photometric Scale according to the light type and intensity mode.
  14600. */
  14601. Light.prototype._getPhotometricScale = function () {
  14602. var photometricScale = 0.0;
  14603. var lightTypeID = this.getTypeID();
  14604. //get photometric mode
  14605. var photometricMode = this.intensityMode;
  14606. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14607. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14608. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14609. }
  14610. else {
  14611. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14612. }
  14613. }
  14614. //compute photometric scale
  14615. switch (lightTypeID) {
  14616. case Light.LIGHTTYPEID_POINTLIGHT:
  14617. case Light.LIGHTTYPEID_SPOTLIGHT:
  14618. switch (photometricMode) {
  14619. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14620. photometricScale = 1.0 / (4.0 * Math.PI);
  14621. break;
  14622. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14623. photometricScale = 1.0;
  14624. break;
  14625. case Light.INTENSITYMODE_LUMINANCE:
  14626. photometricScale = this.radius * this.radius;
  14627. break;
  14628. }
  14629. break;
  14630. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14631. switch (photometricMode) {
  14632. case Light.INTENSITYMODE_ILLUMINANCE:
  14633. photometricScale = 1.0;
  14634. break;
  14635. case Light.INTENSITYMODE_LUMINANCE:
  14636. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14637. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14638. var apexAngleRadians = this.radius;
  14639. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14640. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14641. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14642. photometricScale = solidAngle;
  14643. break;
  14644. }
  14645. break;
  14646. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14647. // No fall off in hemisperic light.
  14648. photometricScale = 1.0;
  14649. break;
  14650. }
  14651. return photometricScale;
  14652. };
  14653. Light.prototype._reorderLightsInScene = function () {
  14654. var scene = this.getScene();
  14655. if (this.renderPriority != 0) {
  14656. scene.requireLightSorting = true;
  14657. }
  14658. this.getScene().sortLightsByPriority();
  14659. };
  14660. //lightmapMode Consts
  14661. Light._LIGHTMAP_DEFAULT = 0;
  14662. Light._LIGHTMAP_SPECULAR = 1;
  14663. Light._LIGHTMAP_SHADOWSONLY = 2;
  14664. // Intensity Mode Consts
  14665. Light._INTENSITYMODE_AUTOMATIC = 0;
  14666. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14667. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14668. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14669. Light._INTENSITYMODE_LUMINANCE = 4;
  14670. // Light types ids const.
  14671. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14672. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14673. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14674. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14675. __decorate([
  14676. BABYLON.serializeAsColor3()
  14677. ], Light.prototype, "diffuse", void 0);
  14678. __decorate([
  14679. BABYLON.serializeAsColor3()
  14680. ], Light.prototype, "specular", void 0);
  14681. __decorate([
  14682. BABYLON.serialize()
  14683. ], Light.prototype, "intensity", void 0);
  14684. __decorate([
  14685. BABYLON.serialize()
  14686. ], Light.prototype, "range", void 0);
  14687. __decorate([
  14688. BABYLON.serialize()
  14689. ], Light.prototype, "intensityMode", null);
  14690. __decorate([
  14691. BABYLON.serialize()
  14692. ], Light.prototype, "radius", null);
  14693. __decorate([
  14694. BABYLON.serialize()
  14695. ], Light.prototype, "_renderPriority", void 0);
  14696. __decorate([
  14697. BABYLON.expandToProperty("_reorderLightsInScene")
  14698. ], Light.prototype, "renderPriority", void 0);
  14699. __decorate([
  14700. BABYLON.serialize()
  14701. ], Light.prototype, "shadowEnabled", void 0);
  14702. __decorate([
  14703. BABYLON.serialize("excludeWithLayerMask")
  14704. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14705. __decorate([
  14706. BABYLON.serialize("includeOnlyWithLayerMask")
  14707. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14708. __decorate([
  14709. BABYLON.serialize("lightmapMode")
  14710. ], Light.prototype, "_lightmapMode", void 0);
  14711. return Light;
  14712. }(BABYLON.Node));
  14713. BABYLON.Light = Light;
  14714. })(BABYLON || (BABYLON = {}));
  14715. //# sourceMappingURL=babylon.light.js.map
  14716. var BABYLON;
  14717. (function (BABYLON) {
  14718. var Camera = (function (_super) {
  14719. __extends(Camera, _super);
  14720. function Camera(name, position, scene) {
  14721. var _this = _super.call(this, name, scene) || this;
  14722. _this.upVector = BABYLON.Vector3.Up();
  14723. _this.orthoLeft = null;
  14724. _this.orthoRight = null;
  14725. _this.orthoBottom = null;
  14726. _this.orthoTop = null;
  14727. _this.fov = 0.8;
  14728. _this.minZ = 1;
  14729. _this.maxZ = 10000.0;
  14730. _this.inertia = 0.9;
  14731. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14732. _this.isIntermediate = false;
  14733. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14734. _this.layerMask = 0x0FFFFFFF;
  14735. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14736. // Camera rig members
  14737. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14738. _this._rigCameras = new Array();
  14739. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14740. _this.customRenderTargets = new Array();
  14741. // Observables
  14742. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14743. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14744. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14745. // Cache
  14746. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14747. _this._projectionMatrix = new BABYLON.Matrix();
  14748. _this._doNotComputeProjectionMatrix = false;
  14749. _this._postProcesses = new Array();
  14750. _this._transformMatrix = BABYLON.Matrix.Zero();
  14751. _this._activeMeshes = new BABYLON.SmartArray(256);
  14752. _this._globalPosition = BABYLON.Vector3.Zero();
  14753. _this._refreshFrustumPlanes = true;
  14754. _this.getScene().addCamera(_this);
  14755. if (!_this.getScene().activeCamera) {
  14756. _this.getScene().activeCamera = _this;
  14757. }
  14758. _this.position = position;
  14759. return _this;
  14760. }
  14761. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14762. get: function () {
  14763. return Camera._PERSPECTIVE_CAMERA;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14769. get: function () {
  14770. return Camera._ORTHOGRAPHIC_CAMERA;
  14771. },
  14772. enumerable: true,
  14773. configurable: true
  14774. });
  14775. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14776. get: function () {
  14777. return Camera._FOVMODE_VERTICAL_FIXED;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14783. get: function () {
  14784. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14790. get: function () {
  14791. return Camera._RIG_MODE_NONE;
  14792. },
  14793. enumerable: true,
  14794. configurable: true
  14795. });
  14796. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14797. get: function () {
  14798. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14804. get: function () {
  14805. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14811. get: function () {
  14812. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14813. },
  14814. enumerable: true,
  14815. configurable: true
  14816. });
  14817. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14818. get: function () {
  14819. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14820. },
  14821. enumerable: true,
  14822. configurable: true
  14823. });
  14824. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14825. get: function () {
  14826. return Camera._RIG_MODE_VR;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14832. get: function () {
  14833. return Camera._RIG_MODE_WEBVR;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Camera.prototype.getClassName = function () {
  14839. return "Camera";
  14840. };
  14841. /**
  14842. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14843. */
  14844. Camera.prototype.toString = function (fullDetails) {
  14845. var ret = "Name: " + this.name;
  14846. ret += ", type: " + this.getClassName();
  14847. if (this.animations) {
  14848. for (var i = 0; i < this.animations.length; i++) {
  14849. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14850. }
  14851. }
  14852. if (fullDetails) {
  14853. }
  14854. return ret;
  14855. };
  14856. Object.defineProperty(Camera.prototype, "globalPosition", {
  14857. get: function () {
  14858. return this._globalPosition;
  14859. },
  14860. enumerable: true,
  14861. configurable: true
  14862. });
  14863. Camera.prototype.getActiveMeshes = function () {
  14864. return this._activeMeshes;
  14865. };
  14866. Camera.prototype.isActiveMesh = function (mesh) {
  14867. return (this._activeMeshes.indexOf(mesh) !== -1);
  14868. };
  14869. //Cache
  14870. Camera.prototype._initCache = function () {
  14871. _super.prototype._initCache.call(this);
  14872. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14873. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14874. this._cache.mode = undefined;
  14875. this._cache.minZ = undefined;
  14876. this._cache.maxZ = undefined;
  14877. this._cache.fov = undefined;
  14878. this._cache.fovMode = undefined;
  14879. this._cache.aspectRatio = undefined;
  14880. this._cache.orthoLeft = undefined;
  14881. this._cache.orthoRight = undefined;
  14882. this._cache.orthoBottom = undefined;
  14883. this._cache.orthoTop = undefined;
  14884. this._cache.renderWidth = undefined;
  14885. this._cache.renderHeight = undefined;
  14886. };
  14887. Camera.prototype._updateCache = function (ignoreParentClass) {
  14888. if (!ignoreParentClass) {
  14889. _super.prototype._updateCache.call(this);
  14890. }
  14891. var engine = this.getEngine();
  14892. this._cache.position.copyFrom(this.position);
  14893. this._cache.upVector.copyFrom(this.upVector);
  14894. this._cache.mode = this.mode;
  14895. this._cache.minZ = this.minZ;
  14896. this._cache.maxZ = this.maxZ;
  14897. this._cache.fov = this.fov;
  14898. this._cache.fovMode = this.fovMode;
  14899. this._cache.aspectRatio = engine.getAspectRatio(this);
  14900. this._cache.orthoLeft = this.orthoLeft;
  14901. this._cache.orthoRight = this.orthoRight;
  14902. this._cache.orthoBottom = this.orthoBottom;
  14903. this._cache.orthoTop = this.orthoTop;
  14904. this._cache.renderWidth = engine.getRenderWidth();
  14905. this._cache.renderHeight = engine.getRenderHeight();
  14906. };
  14907. Camera.prototype._updateFromScene = function () {
  14908. this.updateCache();
  14909. this.update();
  14910. };
  14911. // Synchronized
  14912. Camera.prototype._isSynchronized = function () {
  14913. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14914. };
  14915. Camera.prototype._isSynchronizedViewMatrix = function () {
  14916. if (!_super.prototype._isSynchronized.call(this))
  14917. return false;
  14918. return this._cache.position.equals(this.position)
  14919. && this._cache.upVector.equals(this.upVector)
  14920. && this.isSynchronizedWithParent();
  14921. };
  14922. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14923. var check = this._cache.mode === this.mode
  14924. && this._cache.minZ === this.minZ
  14925. && this._cache.maxZ === this.maxZ;
  14926. if (!check) {
  14927. return false;
  14928. }
  14929. var engine = this.getEngine();
  14930. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14931. check = this._cache.fov === this.fov
  14932. && this._cache.fovMode === this.fovMode
  14933. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14934. }
  14935. else {
  14936. check = this._cache.orthoLeft === this.orthoLeft
  14937. && this._cache.orthoRight === this.orthoRight
  14938. && this._cache.orthoBottom === this.orthoBottom
  14939. && this._cache.orthoTop === this.orthoTop
  14940. && this._cache.renderWidth === engine.getRenderWidth()
  14941. && this._cache.renderHeight === engine.getRenderHeight();
  14942. }
  14943. return check;
  14944. };
  14945. // Controls
  14946. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14947. };
  14948. Camera.prototype.detachControl = function (element) {
  14949. };
  14950. Camera.prototype.update = function () {
  14951. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14952. this._updateRigCameras();
  14953. }
  14954. this._checkInputs();
  14955. };
  14956. Camera.prototype._checkInputs = function () {
  14957. this.onAfterCheckInputsObservable.notifyObservers(this);
  14958. };
  14959. Object.defineProperty(Camera.prototype, "rigCameras", {
  14960. get: function () {
  14961. return this._rigCameras;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14967. get: function () {
  14968. return this._rigPostProcess;
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14974. // invalidate framebuffer
  14975. if (this._postProcesses.length > 0) {
  14976. this._postProcesses[0].markTextureDirty();
  14977. }
  14978. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14979. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14980. var cam = this._rigCameras[i];
  14981. var rigPostProcess = cam._rigPostProcess;
  14982. // for VR rig, there does not have to be a post process
  14983. if (rigPostProcess) {
  14984. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14985. if (isPass) {
  14986. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14987. cam.isIntermediate = this._postProcesses.length === 0;
  14988. }
  14989. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14990. rigPostProcess.markTextureDirty();
  14991. }
  14992. else {
  14993. cam._postProcesses = this._postProcesses.slice(0);
  14994. }
  14995. }
  14996. };
  14997. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14998. if (insertAt === void 0) { insertAt = null; }
  14999. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15000. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15001. return 0;
  15002. }
  15003. if (insertAt == null || insertAt < 0) {
  15004. this._postProcesses.push(postProcess);
  15005. }
  15006. else {
  15007. this._postProcesses.splice(insertAt, 0, postProcess);
  15008. }
  15009. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15010. return this._postProcesses.indexOf(postProcess);
  15011. };
  15012. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15013. if (atIndices === void 0) { atIndices = null; }
  15014. var result = [];
  15015. var i;
  15016. var index;
  15017. if (!atIndices) {
  15018. var idx = this._postProcesses.indexOf(postProcess);
  15019. if (idx !== -1) {
  15020. this._postProcesses.splice(idx, 1);
  15021. }
  15022. }
  15023. else {
  15024. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15025. // iterate descending, so can just splice as we go
  15026. for (i = atIndices.length - 1; i >= 0; i--) {
  15027. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15028. result.push(i);
  15029. continue;
  15030. }
  15031. index = atIndices[i];
  15032. this._postProcesses.splice(index, 1);
  15033. }
  15034. }
  15035. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15036. return result;
  15037. };
  15038. Camera.prototype.getWorldMatrix = function () {
  15039. if (!this._worldMatrix) {
  15040. this._worldMatrix = BABYLON.Matrix.Identity();
  15041. }
  15042. var viewMatrix = this.getViewMatrix();
  15043. viewMatrix.invertToRef(this._worldMatrix);
  15044. return this._worldMatrix;
  15045. };
  15046. Camera.prototype._getViewMatrix = function () {
  15047. return BABYLON.Matrix.Identity();
  15048. };
  15049. Camera.prototype.getViewMatrix = function (force) {
  15050. if (!force && this._isSynchronizedViewMatrix()) {
  15051. return this._computedViewMatrix;
  15052. }
  15053. this._computedViewMatrix = this._getViewMatrix();
  15054. this._currentRenderId = this.getScene().getRenderId();
  15055. this._refreshFrustumPlanes = true;
  15056. if (!this.parent || !this.parent.getWorldMatrix) {
  15057. this._globalPosition.copyFrom(this.position);
  15058. }
  15059. else {
  15060. if (!this._worldMatrix) {
  15061. this._worldMatrix = BABYLON.Matrix.Identity();
  15062. }
  15063. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15064. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15065. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15066. this._computedViewMatrix.invert();
  15067. this._markSyncedWithParent();
  15068. }
  15069. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15070. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15071. }
  15072. this.onViewMatrixChangedObservable.notifyObservers(this);
  15073. return this._computedViewMatrix;
  15074. };
  15075. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15076. this._doNotComputeProjectionMatrix = true;
  15077. if (projection !== undefined) {
  15078. this._projectionMatrix = projection;
  15079. }
  15080. };
  15081. ;
  15082. Camera.prototype.unfreezeProjectionMatrix = function () {
  15083. this._doNotComputeProjectionMatrix = false;
  15084. };
  15085. ;
  15086. Camera.prototype.getProjectionMatrix = function (force) {
  15087. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15088. return this._projectionMatrix;
  15089. }
  15090. this._refreshFrustumPlanes = true;
  15091. var engine = this.getEngine();
  15092. var scene = this.getScene();
  15093. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15094. if (this.minZ <= 0) {
  15095. this.minZ = 0.1;
  15096. }
  15097. if (scene.useRightHandedSystem) {
  15098. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15099. }
  15100. else {
  15101. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15102. }
  15103. }
  15104. else {
  15105. var halfWidth = engine.getRenderWidth() / 2.0;
  15106. var halfHeight = engine.getRenderHeight() / 2.0;
  15107. if (scene.useRightHandedSystem) {
  15108. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15109. }
  15110. else {
  15111. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15112. }
  15113. }
  15114. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15115. return this._projectionMatrix;
  15116. };
  15117. Camera.prototype.getTranformationMatrix = function () {
  15118. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15119. return this._transformMatrix;
  15120. };
  15121. Camera.prototype.updateFrustumPlanes = function () {
  15122. if (!this._refreshFrustumPlanes) {
  15123. return;
  15124. }
  15125. this.getTranformationMatrix();
  15126. if (!this._frustumPlanes) {
  15127. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15128. }
  15129. else {
  15130. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15131. }
  15132. this._refreshFrustumPlanes = false;
  15133. };
  15134. Camera.prototype.isInFrustum = function (target) {
  15135. this.updateFrustumPlanes();
  15136. return target.isInFrustum(this._frustumPlanes);
  15137. };
  15138. Camera.prototype.isCompletelyInFrustum = function (target) {
  15139. this.updateFrustumPlanes();
  15140. return target.isCompletelyInFrustum(this._frustumPlanes);
  15141. };
  15142. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15143. if (length === void 0) { length = 100; }
  15144. if (!transform) {
  15145. transform = this.getWorldMatrix();
  15146. }
  15147. if (!origin) {
  15148. origin = this.position;
  15149. }
  15150. var forward = new BABYLON.Vector3(0, 0, 1);
  15151. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15152. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15153. return new BABYLON.Ray(origin, direction, length);
  15154. };
  15155. Camera.prototype.dispose = function () {
  15156. // Observables
  15157. this.onViewMatrixChangedObservable.clear();
  15158. this.onProjectionMatrixChangedObservable.clear();
  15159. this.onAfterCheckInputsObservable.clear();
  15160. // Inputs
  15161. if (this.inputs) {
  15162. this.inputs.clear();
  15163. }
  15164. // Animations
  15165. this.getScene().stopAnimation(this);
  15166. // Remove from scene
  15167. this.getScene().removeCamera(this);
  15168. while (this._rigCameras.length > 0) {
  15169. this._rigCameras.pop().dispose();
  15170. }
  15171. // Postprocesses
  15172. var i = this._postProcesses.length;
  15173. while (--i >= 0) {
  15174. this._postProcesses[i].dispose(this);
  15175. }
  15176. // Render targets
  15177. var i = this.customRenderTargets.length;
  15178. while (--i >= 0) {
  15179. this.customRenderTargets[i].dispose();
  15180. }
  15181. this.customRenderTargets = [];
  15182. // Active Meshes
  15183. this._activeMeshes.dispose();
  15184. _super.prototype.dispose.call(this);
  15185. };
  15186. Object.defineProperty(Camera.prototype, "leftCamera", {
  15187. // ---- Camera rigs section ----
  15188. get: function () {
  15189. if (this._rigCameras.length < 1) {
  15190. return undefined;
  15191. }
  15192. return this._rigCameras[0];
  15193. },
  15194. enumerable: true,
  15195. configurable: true
  15196. });
  15197. Object.defineProperty(Camera.prototype, "rightCamera", {
  15198. get: function () {
  15199. if (this._rigCameras.length < 2) {
  15200. return undefined;
  15201. }
  15202. return this._rigCameras[1];
  15203. },
  15204. enumerable: true,
  15205. configurable: true
  15206. });
  15207. Camera.prototype.getLeftTarget = function () {
  15208. if (this._rigCameras.length < 1) {
  15209. return undefined;
  15210. }
  15211. return this._rigCameras[0].getTarget();
  15212. };
  15213. Camera.prototype.getRightTarget = function () {
  15214. if (this._rigCameras.length < 2) {
  15215. return undefined;
  15216. }
  15217. return this._rigCameras[1].getTarget();
  15218. };
  15219. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15220. while (this._rigCameras.length > 0) {
  15221. this._rigCameras.pop().dispose();
  15222. }
  15223. this.cameraRigMode = mode;
  15224. this._cameraRigParams = {};
  15225. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15226. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15227. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15228. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15229. // create the rig cameras, unless none
  15230. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15231. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15232. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15233. }
  15234. switch (this.cameraRigMode) {
  15235. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15236. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15237. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15238. break;
  15239. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15240. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15241. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15242. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15243. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15244. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15245. break;
  15246. case Camera.RIG_MODE_VR:
  15247. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15248. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15249. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15250. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15251. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15252. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15253. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15254. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15255. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15256. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15257. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15258. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15259. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15260. if (metrics.compensateDistortion) {
  15261. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15262. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15263. }
  15264. break;
  15265. case Camera.RIG_MODE_WEBVR:
  15266. if (rigParams.vrDisplay) {
  15267. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15268. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15269. //Left eye
  15270. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15271. this._rigCameras[0].setCameraRigParameter("left", true);
  15272. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15273. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15274. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15275. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15276. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15277. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15278. this._rigCameras[0].parent = this;
  15279. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15280. //Right eye
  15281. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15282. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15283. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15284. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15285. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15286. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15287. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15288. this._rigCameras[1].parent = this;
  15289. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15290. }
  15291. break;
  15292. }
  15293. this._cascadePostProcessesToRigCams();
  15294. this.
  15295. update();
  15296. };
  15297. Camera.prototype._getVRProjectionMatrix = function () {
  15298. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15299. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15300. return this._projectionMatrix;
  15301. };
  15302. Camera.prototype._updateCameraRotationMatrix = function () {
  15303. //Here for WebVR
  15304. };
  15305. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15306. //Here for WebVR
  15307. };
  15308. /**
  15309. * This function MUST be overwritten by the different WebVR cameras available.
  15310. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15311. */
  15312. Camera.prototype._getWebVRProjectionMatrix = function () {
  15313. return BABYLON.Matrix.Identity();
  15314. };
  15315. /**
  15316. * This function MUST be overwritten by the different WebVR cameras available.
  15317. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15318. */
  15319. Camera.prototype._getWebVRViewMatrix = function () {
  15320. return BABYLON.Matrix.Identity();
  15321. };
  15322. Camera.prototype.setCameraRigParameter = function (name, value) {
  15323. if (!this._cameraRigParams) {
  15324. this._cameraRigParams = {};
  15325. }
  15326. this._cameraRigParams[name] = value;
  15327. //provisionnally:
  15328. if (name === "interaxialDistance") {
  15329. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15330. }
  15331. };
  15332. /**
  15333. * needs to be overridden by children so sub has required properties to be copied
  15334. */
  15335. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15336. return null;
  15337. };
  15338. /**
  15339. * May need to be overridden by children
  15340. */
  15341. Camera.prototype._updateRigCameras = function () {
  15342. for (var i = 0; i < this._rigCameras.length; i++) {
  15343. this._rigCameras[i].minZ = this.minZ;
  15344. this._rigCameras[i].maxZ = this.maxZ;
  15345. this._rigCameras[i].fov = this.fov;
  15346. }
  15347. // only update viewport when ANAGLYPH
  15348. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15349. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15350. }
  15351. };
  15352. Camera.prototype._setupInputs = function () {
  15353. };
  15354. Camera.prototype.serialize = function () {
  15355. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15356. // Type
  15357. serializationObject.type = this.getClassName();
  15358. // Parent
  15359. if (this.parent) {
  15360. serializationObject.parentId = this.parent.id;
  15361. }
  15362. if (this.inputs) {
  15363. this.inputs.serialize(serializationObject);
  15364. }
  15365. // Animations
  15366. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15367. serializationObject.ranges = this.serializeAnimationRanges();
  15368. return serializationObject;
  15369. };
  15370. Camera.prototype.clone = function (name) {
  15371. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15372. };
  15373. Camera.prototype.getDirection = function (localAxis) {
  15374. var result = BABYLON.Vector3.Zero();
  15375. this.getDirectionToRef(localAxis, result);
  15376. return result;
  15377. };
  15378. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15379. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15380. };
  15381. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15382. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15383. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15384. switch (type) {
  15385. case "ArcRotateCamera":
  15386. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15387. case "DeviceOrientationCamera":
  15388. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15389. case "FollowCamera":
  15390. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15391. case "ArcFollowCamera":
  15392. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15393. case "GamepadCamera":
  15394. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15395. case "TouchCamera":
  15396. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15397. case "VirtualJoysticksCamera":
  15398. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15399. case "WebVRFreeCamera":
  15400. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15401. case "WebVRGamepadCamera":
  15402. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15403. case "VRDeviceOrientationFreeCamera":
  15404. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15405. case "VRDeviceOrientationGamepadCamera":
  15406. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15407. case "AnaglyphArcRotateCamera":
  15408. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15409. case "AnaglyphFreeCamera":
  15410. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15411. case "AnaglyphGamepadCamera":
  15412. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15413. case "AnaglyphUniversalCamera":
  15414. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15415. case "StereoscopicArcRotateCamera":
  15416. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15417. case "StereoscopicFreeCamera":
  15418. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15419. case "StereoscopicGamepadCamera":
  15420. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15421. case "StereoscopicUniversalCamera":
  15422. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15423. case "FreeCamera":// Forcing Universal here
  15424. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15425. default:// Universal Camera is the default value
  15426. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15427. }
  15428. };
  15429. Camera.Parse = function (parsedCamera, scene) {
  15430. var type = parsedCamera.type;
  15431. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15432. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15433. // Parent
  15434. if (parsedCamera.parentId) {
  15435. camera._waitingParentId = parsedCamera.parentId;
  15436. }
  15437. //If camera has an input manager, let it parse inputs settings
  15438. if (camera.inputs) {
  15439. camera.inputs.parse(parsedCamera);
  15440. camera._setupInputs();
  15441. }
  15442. if (camera.setPosition) {
  15443. camera.position.copyFromFloats(0, 0, 0);
  15444. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15445. }
  15446. // Target
  15447. if (parsedCamera.target) {
  15448. if (camera.setTarget) {
  15449. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15450. }
  15451. }
  15452. // Apply 3d rig, when found
  15453. if (parsedCamera.cameraRigMode) {
  15454. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15455. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15456. }
  15457. // Animations
  15458. if (parsedCamera.animations) {
  15459. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15460. var parsedAnimation = parsedCamera.animations[animationIndex];
  15461. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15462. }
  15463. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15464. }
  15465. if (parsedCamera.autoAnimate) {
  15466. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15467. }
  15468. return camera;
  15469. };
  15470. // Statics
  15471. Camera._PERSPECTIVE_CAMERA = 0;
  15472. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15473. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15474. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15475. Camera._RIG_MODE_NONE = 0;
  15476. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15477. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15478. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15479. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15480. Camera._RIG_MODE_VR = 20;
  15481. Camera._RIG_MODE_WEBVR = 21;
  15482. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15483. __decorate([
  15484. BABYLON.serializeAsVector3()
  15485. ], Camera.prototype, "position", void 0);
  15486. __decorate([
  15487. BABYLON.serializeAsVector3()
  15488. ], Camera.prototype, "upVector", void 0);
  15489. __decorate([
  15490. BABYLON.serialize()
  15491. ], Camera.prototype, "orthoLeft", void 0);
  15492. __decorate([
  15493. BABYLON.serialize()
  15494. ], Camera.prototype, "orthoRight", void 0);
  15495. __decorate([
  15496. BABYLON.serialize()
  15497. ], Camera.prototype, "orthoBottom", void 0);
  15498. __decorate([
  15499. BABYLON.serialize()
  15500. ], Camera.prototype, "orthoTop", void 0);
  15501. __decorate([
  15502. BABYLON.serialize()
  15503. ], Camera.prototype, "fov", void 0);
  15504. __decorate([
  15505. BABYLON.serialize()
  15506. ], Camera.prototype, "minZ", void 0);
  15507. __decorate([
  15508. BABYLON.serialize()
  15509. ], Camera.prototype, "maxZ", void 0);
  15510. __decorate([
  15511. BABYLON.serialize()
  15512. ], Camera.prototype, "inertia", void 0);
  15513. __decorate([
  15514. BABYLON.serialize()
  15515. ], Camera.prototype, "mode", void 0);
  15516. __decorate([
  15517. BABYLON.serialize()
  15518. ], Camera.prototype, "layerMask", void 0);
  15519. __decorate([
  15520. BABYLON.serialize()
  15521. ], Camera.prototype, "fovMode", void 0);
  15522. __decorate([
  15523. BABYLON.serialize()
  15524. ], Camera.prototype, "cameraRigMode", void 0);
  15525. __decorate([
  15526. BABYLON.serialize()
  15527. ], Camera.prototype, "interaxialDistance", void 0);
  15528. __decorate([
  15529. BABYLON.serialize()
  15530. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15531. return Camera;
  15532. }(BABYLON.Node));
  15533. BABYLON.Camera = Camera;
  15534. })(BABYLON || (BABYLON = {}));
  15535. //# sourceMappingURL=babylon.camera.js.map
  15536. var BABYLON;
  15537. (function (BABYLON) {
  15538. var RenderingManager = (function () {
  15539. function RenderingManager(scene) {
  15540. this._renderingGroups = new Array();
  15541. this._autoClearDepthStencil = {};
  15542. this._customOpaqueSortCompareFn = {};
  15543. this._customAlphaTestSortCompareFn = {};
  15544. this._customTransparentSortCompareFn = {};
  15545. this._renderinGroupInfo = null;
  15546. this._scene = scene;
  15547. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15548. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15549. }
  15550. }
  15551. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15552. if (depth === void 0) { depth = true; }
  15553. if (stencil === void 0) { stencil = true; }
  15554. if (this._depthStencilBufferAlreadyCleaned) {
  15555. return;
  15556. }
  15557. this._scene.getEngine().clear(null, false, depth, stencil);
  15558. this._depthStencilBufferAlreadyCleaned = true;
  15559. };
  15560. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15561. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15562. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15563. var info = null;
  15564. if (observable) {
  15565. if (!this._renderinGroupInfo) {
  15566. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15567. }
  15568. info = this._renderinGroupInfo;
  15569. info.scene = this._scene;
  15570. info.camera = this._scene.activeCamera;
  15571. }
  15572. // Dispatch sprites
  15573. if (renderSprites) {
  15574. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15575. var manager = this._scene.spriteManagers[index];
  15576. this.dispatchSprites(manager);
  15577. }
  15578. }
  15579. // Render
  15580. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15581. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15582. var renderingGroup = this._renderingGroups[index];
  15583. if (!renderingGroup && !observable)
  15584. continue;
  15585. this._currentIndex = index;
  15586. var renderingGroupMask = 0;
  15587. // Fire PRECLEAR stage
  15588. if (observable) {
  15589. renderingGroupMask = Math.pow(2, index);
  15590. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15591. info.renderingGroupId = index;
  15592. observable.notifyObservers(info, renderingGroupMask);
  15593. }
  15594. // Clear depth/stencil if needed
  15595. if (RenderingManager.AUTOCLEAR) {
  15596. var autoClear = this._autoClearDepthStencil[index];
  15597. if (autoClear && autoClear.autoClear) {
  15598. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15599. }
  15600. }
  15601. if (observable) {
  15602. // Fire PREOPAQUE stage
  15603. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15604. observable.notifyObservers(info, renderingGroupMask);
  15605. // Fire PRETRANSPARENT stage
  15606. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15607. observable.notifyObservers(info, renderingGroupMask);
  15608. }
  15609. if (renderingGroup)
  15610. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15611. // Fire POSTTRANSPARENT stage
  15612. if (observable) {
  15613. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15614. observable.notifyObservers(info, renderingGroupMask);
  15615. }
  15616. }
  15617. };
  15618. RenderingManager.prototype.reset = function () {
  15619. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15620. var renderingGroup = this._renderingGroups[index];
  15621. if (renderingGroup) {
  15622. renderingGroup.prepare();
  15623. }
  15624. }
  15625. };
  15626. RenderingManager.prototype.dispose = function () {
  15627. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15628. var renderingGroup = this._renderingGroups[index];
  15629. if (renderingGroup) {
  15630. renderingGroup.dispose();
  15631. }
  15632. }
  15633. this._renderingGroups.length = 0;
  15634. };
  15635. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15636. if (!this._renderingGroups[renderingGroupId]) {
  15637. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15638. }
  15639. };
  15640. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15641. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15642. this._prepareRenderingGroup(renderingGroupId);
  15643. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15644. };
  15645. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15646. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15647. this._prepareRenderingGroup(renderingGroupId);
  15648. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15649. };
  15650. RenderingManager.prototype.dispatch = function (subMesh) {
  15651. var mesh = subMesh.getMesh();
  15652. var renderingGroupId = mesh.renderingGroupId || 0;
  15653. this._prepareRenderingGroup(renderingGroupId);
  15654. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15655. };
  15656. /**
  15657. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15658. * This allowed control for front to back rendering or reversly depending of the special needs.
  15659. *
  15660. * @param renderingGroupId The rendering group id corresponding to its index
  15661. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15662. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15663. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15664. */
  15665. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15666. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15667. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15668. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15669. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15670. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15671. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15672. if (this._renderingGroups[renderingGroupId]) {
  15673. var group = this._renderingGroups[renderingGroupId];
  15674. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15675. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15676. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15677. }
  15678. };
  15679. /**
  15680. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15681. *
  15682. * @param renderingGroupId The rendering group id corresponding to its index
  15683. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15684. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15685. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15686. */
  15687. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15688. if (depth === void 0) { depth = true; }
  15689. if (stencil === void 0) { stencil = true; }
  15690. this._autoClearDepthStencil[renderingGroupId] = {
  15691. autoClear: autoClearDepthStencil,
  15692. depth: depth,
  15693. stencil: stencil
  15694. };
  15695. };
  15696. /**
  15697. * The max id used for rendering groups (not included)
  15698. */
  15699. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15700. /**
  15701. * The min id used for rendering groups (included)
  15702. */
  15703. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15704. /**
  15705. * Used to globally prevent autoclearing scenes.
  15706. */
  15707. RenderingManager.AUTOCLEAR = true;
  15708. return RenderingManager;
  15709. }());
  15710. BABYLON.RenderingManager = RenderingManager;
  15711. })(BABYLON || (BABYLON = {}));
  15712. //# sourceMappingURL=babylon.renderingManager.js.map
  15713. var BABYLON;
  15714. (function (BABYLON) {
  15715. var RenderingGroup = (function () {
  15716. /**
  15717. * Creates a new rendering group.
  15718. * @param index The rendering group index
  15719. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15720. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15721. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15722. */
  15723. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15724. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15725. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15726. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15727. this.index = index;
  15728. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15729. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15730. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15731. this._particleSystems = new BABYLON.SmartArray(256);
  15732. this._spriteManagers = new BABYLON.SmartArray(256);
  15733. this._edgesRenderers = new BABYLON.SmartArray(16);
  15734. this._scene = scene;
  15735. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15736. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15737. this.transparentSortCompareFn = transparentSortCompareFn;
  15738. }
  15739. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15740. /**
  15741. * Set the opaque sort comparison function.
  15742. * If null the sub meshes will be render in the order they were created
  15743. */
  15744. set: function (value) {
  15745. this._opaqueSortCompareFn = value;
  15746. if (value) {
  15747. this._renderOpaque = this.renderOpaqueSorted;
  15748. }
  15749. else {
  15750. this._renderOpaque = RenderingGroup.renderUnsorted;
  15751. }
  15752. },
  15753. enumerable: true,
  15754. configurable: true
  15755. });
  15756. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15757. /**
  15758. * Set the alpha test sort comparison function.
  15759. * If null the sub meshes will be render in the order they were created
  15760. */
  15761. set: function (value) {
  15762. this._alphaTestSortCompareFn = value;
  15763. if (value) {
  15764. this._renderAlphaTest = this.renderAlphaTestSorted;
  15765. }
  15766. else {
  15767. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15768. }
  15769. },
  15770. enumerable: true,
  15771. configurable: true
  15772. });
  15773. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15774. /**
  15775. * Set the transparent sort comparison function.
  15776. * If null the sub meshes will be render in the order they were created
  15777. */
  15778. set: function (value) {
  15779. if (value) {
  15780. this._transparentSortCompareFn = value;
  15781. }
  15782. else {
  15783. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15784. }
  15785. this._renderTransparent = this.renderTransparentSorted;
  15786. },
  15787. enumerable: true,
  15788. configurable: true
  15789. });
  15790. /**
  15791. * Render all the sub meshes contained in the group.
  15792. * @param customRenderFunction Used to override the default render behaviour of the group.
  15793. * @returns true if rendered some submeshes.
  15794. */
  15795. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15796. if (customRenderFunction) {
  15797. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15798. return;
  15799. }
  15800. var engine = this._scene.getEngine();
  15801. // Opaque
  15802. if (this._opaqueSubMeshes.length !== 0) {
  15803. this._renderOpaque(this._opaqueSubMeshes);
  15804. }
  15805. // Alpha test
  15806. if (this._alphaTestSubMeshes.length !== 0) {
  15807. engine.setAlphaTesting(true);
  15808. this._renderAlphaTest(this._alphaTestSubMeshes);
  15809. engine.setAlphaTesting(false);
  15810. }
  15811. var stencilState = engine.getStencilBuffer();
  15812. engine.setStencilBuffer(false);
  15813. // Sprites
  15814. if (renderSprites) {
  15815. this._renderSprites();
  15816. }
  15817. // Particles
  15818. if (renderParticles) {
  15819. this._renderParticles(activeMeshes);
  15820. }
  15821. if (this.onBeforeTransparentRendering) {
  15822. this.onBeforeTransparentRendering();
  15823. }
  15824. // Transparent
  15825. if (this._transparentSubMeshes.length !== 0) {
  15826. this._renderTransparent(this._transparentSubMeshes);
  15827. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15828. }
  15829. // Set back stencil to false in case it changes before the edge renderer.
  15830. engine.setStencilBuffer(false);
  15831. // Edges
  15832. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15833. this._edgesRenderers.data[edgesRendererIndex].render();
  15834. }
  15835. // Restore Stencil state.
  15836. engine.setStencilBuffer(stencilState);
  15837. };
  15838. /**
  15839. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15840. * @param subMeshes The submeshes to render
  15841. */
  15842. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15843. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15844. };
  15845. /**
  15846. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15847. * @param subMeshes The submeshes to render
  15848. */
  15849. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15850. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15851. };
  15852. /**
  15853. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15854. * @param subMeshes The submeshes to render
  15855. */
  15856. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15857. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15858. };
  15859. /**
  15860. * Renders the submeshes in a specified order.
  15861. * @param subMeshes The submeshes to sort before render
  15862. * @param sortCompareFn The comparison function use to sort
  15863. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15864. * @param transparent Specifies to activate blending if true
  15865. */
  15866. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15867. var subIndex = 0;
  15868. var subMesh;
  15869. for (; subIndex < subMeshes.length; subIndex++) {
  15870. subMesh = subMeshes.data[subIndex];
  15871. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15872. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15873. }
  15874. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15875. sortedArray.sort(sortCompareFn);
  15876. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15877. subMesh = sortedArray[subIndex];
  15878. subMesh.render(transparent);
  15879. }
  15880. };
  15881. /**
  15882. * Renders the submeshes in the order they were dispatched (no sort applied).
  15883. * @param subMeshes The submeshes to render
  15884. */
  15885. RenderingGroup.renderUnsorted = function (subMeshes) {
  15886. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15887. var submesh = subMeshes.data[subIndex];
  15888. submesh.render(false);
  15889. }
  15890. };
  15891. /**
  15892. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15893. * are rendered back to front if in the same alpha index.
  15894. *
  15895. * @param a The first submesh
  15896. * @param b The second submesh
  15897. * @returns The result of the comparison
  15898. */
  15899. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15900. // Alpha index first
  15901. if (a._alphaIndex > b._alphaIndex) {
  15902. return 1;
  15903. }
  15904. if (a._alphaIndex < b._alphaIndex) {
  15905. return -1;
  15906. }
  15907. // Then distance to camera
  15908. return RenderingGroup.backToFrontSortCompare(a, b);
  15909. };
  15910. /**
  15911. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15912. * are rendered back to front.
  15913. *
  15914. * @param a The first submesh
  15915. * @param b The second submesh
  15916. * @returns The result of the comparison
  15917. */
  15918. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15919. // Then distance to camera
  15920. if (a._distanceToCamera < b._distanceToCamera) {
  15921. return 1;
  15922. }
  15923. if (a._distanceToCamera > b._distanceToCamera) {
  15924. return -1;
  15925. }
  15926. return 0;
  15927. };
  15928. /**
  15929. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15930. * are rendered front to back (prevent overdraw).
  15931. *
  15932. * @param a The first submesh
  15933. * @param b The second submesh
  15934. * @returns The result of the comparison
  15935. */
  15936. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15937. // Then distance to camera
  15938. if (a._distanceToCamera < b._distanceToCamera) {
  15939. return -1;
  15940. }
  15941. if (a._distanceToCamera > b._distanceToCamera) {
  15942. return 1;
  15943. }
  15944. return 0;
  15945. };
  15946. /**
  15947. * Resets the different lists of submeshes to prepare a new frame.
  15948. */
  15949. RenderingGroup.prototype.prepare = function () {
  15950. this._opaqueSubMeshes.reset();
  15951. this._transparentSubMeshes.reset();
  15952. this._alphaTestSubMeshes.reset();
  15953. this._particleSystems.reset();
  15954. this._spriteManagers.reset();
  15955. this._edgesRenderers.reset();
  15956. };
  15957. RenderingGroup.prototype.dispose = function () {
  15958. this._opaqueSubMeshes.dispose();
  15959. this._transparentSubMeshes.dispose();
  15960. this._alphaTestSubMeshes.dispose();
  15961. this._particleSystems.dispose();
  15962. this._spriteManagers.dispose();
  15963. this._edgesRenderers.dispose();
  15964. };
  15965. /**
  15966. * Inserts the submesh in its correct queue depending on its material.
  15967. * @param subMesh The submesh to dispatch
  15968. */
  15969. RenderingGroup.prototype.dispatch = function (subMesh) {
  15970. var material = subMesh.getMaterial();
  15971. var mesh = subMesh.getMesh();
  15972. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15973. this._transparentSubMeshes.push(subMesh);
  15974. }
  15975. else if (material.needAlphaTesting()) {
  15976. this._alphaTestSubMeshes.push(subMesh);
  15977. }
  15978. else {
  15979. this._opaqueSubMeshes.push(subMesh); // Opaque
  15980. }
  15981. if (mesh._edgesRenderer) {
  15982. this._edgesRenderers.push(mesh._edgesRenderer);
  15983. }
  15984. };
  15985. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15986. this._spriteManagers.push(spriteManager);
  15987. };
  15988. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15989. this._particleSystems.push(particleSystem);
  15990. };
  15991. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15992. if (this._particleSystems.length === 0) {
  15993. return;
  15994. }
  15995. // Particles
  15996. var activeCamera = this._scene.activeCamera;
  15997. this._scene._particlesDuration.beginMonitoring();
  15998. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15999. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16000. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16001. continue;
  16002. }
  16003. var emitter = particleSystem.emitter;
  16004. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16005. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16006. }
  16007. }
  16008. this._scene._particlesDuration.endMonitoring(false);
  16009. };
  16010. RenderingGroup.prototype._renderSprites = function () {
  16011. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16012. return;
  16013. }
  16014. // Sprites
  16015. var activeCamera = this._scene.activeCamera;
  16016. this._scene._spritesDuration.beginMonitoring();
  16017. for (var id = 0; id < this._spriteManagers.length; id++) {
  16018. var spriteManager = this._spriteManagers.data[id];
  16019. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16020. spriteManager.render();
  16021. }
  16022. }
  16023. this._scene._spritesDuration.endMonitoring(false);
  16024. };
  16025. return RenderingGroup;
  16026. }());
  16027. BABYLON.RenderingGroup = RenderingGroup;
  16028. })(BABYLON || (BABYLON = {}));
  16029. //# sourceMappingURL=babylon.renderingGroup.js.map
  16030. var BABYLON;
  16031. (function (BABYLON) {
  16032. var ClickInfo = (function () {
  16033. function ClickInfo() {
  16034. this._singleClick = false;
  16035. this._doubleClick = false;
  16036. this._hasSwiped = false;
  16037. this._ignore = false;
  16038. }
  16039. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16040. get: function () {
  16041. return this._singleClick;
  16042. },
  16043. set: function (b) {
  16044. this._singleClick = b;
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16050. get: function () {
  16051. return this._doubleClick;
  16052. },
  16053. set: function (b) {
  16054. this._doubleClick = b;
  16055. },
  16056. enumerable: true,
  16057. configurable: true
  16058. });
  16059. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16060. get: function () {
  16061. return this._hasSwiped;
  16062. },
  16063. set: function (b) {
  16064. this._hasSwiped = b;
  16065. },
  16066. enumerable: true,
  16067. configurable: true
  16068. });
  16069. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16070. get: function () {
  16071. return this._ignore;
  16072. },
  16073. set: function (b) {
  16074. this._ignore = b;
  16075. },
  16076. enumerable: true,
  16077. configurable: true
  16078. });
  16079. return ClickInfo;
  16080. }());
  16081. var PointerEventTypes = (function () {
  16082. function PointerEventTypes() {
  16083. }
  16084. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16085. get: function () {
  16086. return PointerEventTypes._POINTERDOWN;
  16087. },
  16088. enumerable: true,
  16089. configurable: true
  16090. });
  16091. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16092. get: function () {
  16093. return PointerEventTypes._POINTERUP;
  16094. },
  16095. enumerable: true,
  16096. configurable: true
  16097. });
  16098. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16099. get: function () {
  16100. return PointerEventTypes._POINTERMOVE;
  16101. },
  16102. enumerable: true,
  16103. configurable: true
  16104. });
  16105. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16106. get: function () {
  16107. return PointerEventTypes._POINTERWHEEL;
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16113. get: function () {
  16114. return PointerEventTypes._POINTERPICK;
  16115. },
  16116. enumerable: true,
  16117. configurable: true
  16118. });
  16119. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  16120. get: function () {
  16121. return PointerEventTypes._POINTERTAP;
  16122. },
  16123. enumerable: true,
  16124. configurable: true
  16125. });
  16126. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  16127. get: function () {
  16128. return PointerEventTypes._POINTERDOUBLETAP;
  16129. },
  16130. enumerable: true,
  16131. configurable: true
  16132. });
  16133. PointerEventTypes._POINTERDOWN = 0x01;
  16134. PointerEventTypes._POINTERUP = 0x02;
  16135. PointerEventTypes._POINTERMOVE = 0x04;
  16136. PointerEventTypes._POINTERWHEEL = 0x08;
  16137. PointerEventTypes._POINTERPICK = 0x10;
  16138. PointerEventTypes._POINTERTAP = 0x20;
  16139. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  16140. return PointerEventTypes;
  16141. }());
  16142. BABYLON.PointerEventTypes = PointerEventTypes;
  16143. var PointerInfoBase = (function () {
  16144. function PointerInfoBase(type, event) {
  16145. this.type = type;
  16146. this.event = event;
  16147. }
  16148. return PointerInfoBase;
  16149. }());
  16150. BABYLON.PointerInfoBase = PointerInfoBase;
  16151. /**
  16152. * This class is used to store pointer related info for the onPrePointerObservable event.
  16153. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16154. */
  16155. var PointerInfoPre = (function (_super) {
  16156. __extends(PointerInfoPre, _super);
  16157. function PointerInfoPre(type, event, localX, localY) {
  16158. var _this = _super.call(this, type, event) || this;
  16159. _this.skipOnPointerObservable = false;
  16160. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16161. return _this;
  16162. }
  16163. return PointerInfoPre;
  16164. }(PointerInfoBase));
  16165. BABYLON.PointerInfoPre = PointerInfoPre;
  16166. /**
  16167. * This type contains all the data related to a pointer event in Babylon.js.
  16168. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  16169. */
  16170. var PointerInfo = (function (_super) {
  16171. __extends(PointerInfo, _super);
  16172. function PointerInfo(type, event, pickInfo) {
  16173. var _this = _super.call(this, type, event) || this;
  16174. _this.pickInfo = pickInfo;
  16175. return _this;
  16176. }
  16177. return PointerInfo;
  16178. }(PointerInfoBase));
  16179. BABYLON.PointerInfo = PointerInfo;
  16180. /**
  16181. * This class is used by the onRenderingGroupObservable
  16182. */
  16183. var RenderingGroupInfo = (function () {
  16184. function RenderingGroupInfo() {
  16185. }
  16186. /**
  16187. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16188. * This stage will be fired no matter what
  16189. */
  16190. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16191. /**
  16192. * Called before opaque object are rendered.
  16193. * This stage will be fired only if there's 3D Opaque content to render
  16194. */
  16195. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16196. /**
  16197. * Called after the opaque objects are rendered and before the transparent ones
  16198. * This stage will be fired only if there's 3D transparent content to render
  16199. */
  16200. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16201. /**
  16202. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16203. * This stage will be fired no matter what
  16204. */
  16205. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16206. return RenderingGroupInfo;
  16207. }());
  16208. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16209. /**
  16210. * Represents a scene to be rendered by the engine.
  16211. * @see http://doc.babylonjs.com/page.php?p=21911
  16212. */
  16213. var Scene = (function () {
  16214. /**
  16215. * @constructor
  16216. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16217. */
  16218. function Scene(engine) {
  16219. // Members
  16220. this.autoClear = true;
  16221. this.autoClearDepthAndStencil = true;
  16222. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16223. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16224. this.forceWireframe = false;
  16225. this._forcePointsCloud = false;
  16226. this.forceShowBoundingBoxes = false;
  16227. this.animationsEnabled = true;
  16228. this.constantlyUpdateMeshUnderPointer = false;
  16229. this.hoverCursor = "pointer";
  16230. this.defaultCursor = "";
  16231. // Metadata
  16232. this.metadata = null;
  16233. // Events
  16234. /**
  16235. * An event triggered when the scene is disposed.
  16236. * @type {BABYLON.Observable}
  16237. */
  16238. this.onDisposeObservable = new BABYLON.Observable();
  16239. /**
  16240. * An event triggered before rendering the scene
  16241. * @type {BABYLON.Observable}
  16242. */
  16243. this.onBeforeRenderObservable = new BABYLON.Observable();
  16244. /**
  16245. * An event triggered after rendering the scene
  16246. * @type {BABYLON.Observable}
  16247. */
  16248. this.onAfterRenderObservable = new BABYLON.Observable();
  16249. /**
  16250. * An event triggered when the scene is ready
  16251. * @type {BABYLON.Observable}
  16252. */
  16253. this.onReadyObservable = new BABYLON.Observable();
  16254. /**
  16255. * An event triggered before rendering a camera
  16256. * @type {BABYLON.Observable}
  16257. */
  16258. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16259. /**
  16260. * An event triggered after rendering a camera
  16261. * @type {BABYLON.Observable}
  16262. */
  16263. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16264. /**
  16265. * An event triggered when a camera is created
  16266. * @type {BABYLON.Observable}
  16267. */
  16268. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16269. /**
  16270. * An event triggered when a camera is removed
  16271. * @type {BABYLON.Observable}
  16272. */
  16273. this.onCameraRemovedObservable = new BABYLON.Observable();
  16274. /**
  16275. * An event triggered when a light is created
  16276. * @type {BABYLON.Observable}
  16277. */
  16278. this.onNewLightAddedObservable = new BABYLON.Observable();
  16279. /**
  16280. * An event triggered when a light is removed
  16281. * @type {BABYLON.Observable}
  16282. */
  16283. this.onLightRemovedObservable = new BABYLON.Observable();
  16284. /**
  16285. * An event triggered when a geometry is created
  16286. * @type {BABYLON.Observable}
  16287. */
  16288. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16289. /**
  16290. * An event triggered when a geometry is removed
  16291. * @type {BABYLON.Observable}
  16292. */
  16293. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16294. /**
  16295. * An event triggered when a mesh is created
  16296. * @type {BABYLON.Observable}
  16297. */
  16298. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16299. /**
  16300. * An event triggered when a mesh is removed
  16301. * @type {BABYLON.Observable}
  16302. */
  16303. this.onMeshRemovedObservable = new BABYLON.Observable();
  16304. /**
  16305. * An event triggered before calculating deterministic simulation step
  16306. * @type {BABYLON.Observable}
  16307. */
  16308. this.onBeforeStepObservable = new BABYLON.Observable();
  16309. /**
  16310. * An event triggered after calculating deterministic simulation step
  16311. * @type {BABYLON.Observable}
  16312. */
  16313. this.onAfterStepObservable = new BABYLON.Observable();
  16314. /**
  16315. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16316. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16317. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  16318. */
  16319. this.onRenderingGroupObservable = new BABYLON.Observable();
  16320. // Animations
  16321. this.animations = [];
  16322. /**
  16323. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  16324. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16325. */
  16326. this.onPrePointerObservable = new BABYLON.Observable();
  16327. /**
  16328. * Observable event triggered each time an input event is received from the rendering canvas
  16329. */
  16330. this.onPointerObservable = new BABYLON.Observable();
  16331. this._meshPickProceed = false;
  16332. this._previousHasSwiped = false;
  16333. this._currentPickResult = null;
  16334. this._previousPickResult = null;
  16335. this._isButtonPressed = false;
  16336. this._doubleClickOccured = false;
  16337. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16338. this.cameraToUseForPointers = null;
  16339. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16340. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16341. this._startingPointerTime = 0;
  16342. this._previousStartingPointerTime = 0;
  16343. // Deterministic lockstep
  16344. this._timeAccumulator = 0;
  16345. this._currentStepId = 0;
  16346. this._currentInternalStep = 0;
  16347. // Coordinate system
  16348. /**
  16349. * use right-handed coordinate system on this scene.
  16350. * @type {boolean}
  16351. */
  16352. this._useRightHandedSystem = false;
  16353. // Fog
  16354. this._fogEnabled = true;
  16355. this._fogMode = Scene.FOGMODE_NONE;
  16356. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16357. this.fogDensity = 0.1;
  16358. this.fogStart = 0;
  16359. this.fogEnd = 1000.0;
  16360. // Lights
  16361. /**
  16362. * is shadow enabled on this scene.
  16363. * @type {boolean}
  16364. */
  16365. this._shadowsEnabled = true;
  16366. /**
  16367. * is light enabled on this scene.
  16368. * @type {boolean}
  16369. */
  16370. this._lightsEnabled = true;
  16371. /**
  16372. * All of the lights added to this scene.
  16373. * @see BABYLON.Light
  16374. * @type {BABYLON.Light[]}
  16375. */
  16376. this.lights = new Array();
  16377. // Cameras
  16378. /** All of the cameras added to this scene. */
  16379. this.cameras = new Array();
  16380. /** All of the active cameras added to this scene. */
  16381. this.activeCameras = new Array();
  16382. // Meshes
  16383. /**
  16384. * All of the (abstract) meshes added to this scene.
  16385. * @see BABYLON.AbstractMesh
  16386. * @type {BABYLON.AbstractMesh[]}
  16387. */
  16388. this.meshes = new Array();
  16389. // Geometries
  16390. this._geometries = new Array();
  16391. this.materials = new Array();
  16392. this.multiMaterials = new Array();
  16393. // Textures
  16394. this._texturesEnabled = true;
  16395. this.textures = new Array();
  16396. // Particles
  16397. this.particlesEnabled = true;
  16398. this.particleSystems = new Array();
  16399. // Sprites
  16400. this.spritesEnabled = true;
  16401. this.spriteManagers = new Array();
  16402. // Layers
  16403. this.layers = new Array();
  16404. this.highlightLayers = new Array();
  16405. // Skeletons
  16406. this._skeletonsEnabled = true;
  16407. this.skeletons = new Array();
  16408. // Morph targets
  16409. this.morphTargetManagers = new Array();
  16410. // Lens flares
  16411. this.lensFlaresEnabled = true;
  16412. this.lensFlareSystems = new Array();
  16413. // Collisions
  16414. this.collisionsEnabled = true;
  16415. /** Defines the gravity applied to this scene */
  16416. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16417. // Postprocesses
  16418. this.postProcesses = new Array();
  16419. this.postProcessesEnabled = true;
  16420. // Customs render targets
  16421. this.renderTargetsEnabled = true;
  16422. this.dumpNextRenderTargets = false;
  16423. this.customRenderTargets = new Array();
  16424. // Imported meshes
  16425. this.importedMeshesFiles = new Array();
  16426. // Probes
  16427. this.probesEnabled = true;
  16428. this.reflectionProbes = new Array();
  16429. this._actionManagers = new Array();
  16430. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16431. // Procedural textures
  16432. this.proceduralTexturesEnabled = true;
  16433. this._proceduralTextures = new Array();
  16434. this.soundTracks = new Array();
  16435. this._audioEnabled = true;
  16436. this._headphone = false;
  16437. // Performance counters
  16438. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16439. this._totalLightsCounter = new BABYLON.PerfCounter();
  16440. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16441. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16442. this._totalVertices = new BABYLON.PerfCounter();
  16443. this._activeIndices = new BABYLON.PerfCounter();
  16444. this._activeParticles = new BABYLON.PerfCounter();
  16445. this._lastFrameDuration = new BABYLON.PerfCounter();
  16446. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16447. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16448. this._particlesDuration = new BABYLON.PerfCounter();
  16449. this._renderDuration = new BABYLON.PerfCounter();
  16450. this._spritesDuration = new BABYLON.PerfCounter();
  16451. this._activeBones = new BABYLON.PerfCounter();
  16452. this._animationTime = 0;
  16453. this.animationTimeScale = 1;
  16454. this._renderId = 0;
  16455. this._executeWhenReadyTimeoutId = -1;
  16456. this._intermediateRendering = false;
  16457. this._viewUpdateFlag = -1;
  16458. this._projectionUpdateFlag = -1;
  16459. this._toBeDisposed = new BABYLON.SmartArray(256);
  16460. this._pendingData = []; //ANY
  16461. this._activeMeshes = new BABYLON.SmartArray(256);
  16462. this._processedMaterials = new BABYLON.SmartArray(256);
  16463. this._renderTargets = new BABYLON.SmartArray(256);
  16464. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16465. this._activeSkeletons = new BABYLON.SmartArray(32);
  16466. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16467. this._activeAnimatables = new Array();
  16468. this._transformMatrix = BABYLON.Matrix.Zero();
  16469. this.requireLightSorting = false;
  16470. this._uniqueIdCounter = 0;
  16471. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16472. this._engine.scenes.push(this);
  16473. this._uid = null;
  16474. this._renderingManager = new BABYLON.RenderingManager(this);
  16475. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16476. if (BABYLON.OutlineRenderer) {
  16477. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16478. }
  16479. this.attachControl();
  16480. if (BABYLON.SoundTrack) {
  16481. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16482. }
  16483. //simplification queue
  16484. if (BABYLON.SimplificationQueue) {
  16485. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16486. }
  16487. //collision coordinator initialization. For now legacy per default.
  16488. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16489. // Uniform Buffer
  16490. this._createUbo();
  16491. // Default Image processing definition.
  16492. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16493. }
  16494. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16495. /** The fog is deactivated */
  16496. get: function () {
  16497. return Scene._FOGMODE_NONE;
  16498. },
  16499. enumerable: true,
  16500. configurable: true
  16501. });
  16502. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16503. /** The fog density is following an exponential function */
  16504. get: function () {
  16505. return Scene._FOGMODE_EXP;
  16506. },
  16507. enumerable: true,
  16508. configurable: true
  16509. });
  16510. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16511. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16512. get: function () {
  16513. return Scene._FOGMODE_EXP2;
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16519. /** The fog density is following a linear function. */
  16520. get: function () {
  16521. return Scene._FOGMODE_LINEAR;
  16522. },
  16523. enumerable: true,
  16524. configurable: true
  16525. });
  16526. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16527. /**
  16528. * Texture used in all pbr material as the reflection texture.
  16529. * As in the majority of the scene they are the same (exception for multi room and so on),
  16530. * this is easier to reference from here than from all the materials.
  16531. */
  16532. get: function () {
  16533. return this._environmentTexture;
  16534. },
  16535. /**
  16536. * Texture used in all pbr material as the reflection texture.
  16537. * As in the majority of the scene they are the same (exception for multi room and so on),
  16538. * this is easier to set here than in all the materials.
  16539. */
  16540. set: function (value) {
  16541. this._environmentTexture = value;
  16542. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16543. },
  16544. enumerable: true,
  16545. configurable: true
  16546. });
  16547. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16548. /**
  16549. * Default image processing configuration used either in the rendering
  16550. * Forward main pass or through the imageProcessingPostProcess if present.
  16551. * As in the majority of the scene they are the same (exception for multi camera),
  16552. * this is easier to reference from here than from all the materials and post process.
  16553. *
  16554. * No setter as we it is a shared configuration, you can set the values instead.
  16555. */
  16556. get: function () {
  16557. return this._imageProcessingConfiguration;
  16558. },
  16559. enumerable: true,
  16560. configurable: true
  16561. });
  16562. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16563. get: function () {
  16564. return this._forcePointsCloud;
  16565. },
  16566. set: function (value) {
  16567. if (this._forcePointsCloud === value) {
  16568. return;
  16569. }
  16570. this._forcePointsCloud = value;
  16571. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16572. },
  16573. enumerable: true,
  16574. configurable: true
  16575. });
  16576. Object.defineProperty(Scene.prototype, "onDispose", {
  16577. /** A function to be executed when this scene is disposed. */
  16578. set: function (callback) {
  16579. if (this._onDisposeObserver) {
  16580. this.onDisposeObservable.remove(this._onDisposeObserver);
  16581. }
  16582. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16583. },
  16584. enumerable: true,
  16585. configurable: true
  16586. });
  16587. Object.defineProperty(Scene.prototype, "beforeRender", {
  16588. /** A function to be executed before rendering this scene */
  16589. set: function (callback) {
  16590. if (this._onBeforeRenderObserver) {
  16591. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16592. }
  16593. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16594. },
  16595. enumerable: true,
  16596. configurable: true
  16597. });
  16598. Object.defineProperty(Scene.prototype, "afterRender", {
  16599. /** A function to be executed after rendering this scene */
  16600. set: function (callback) {
  16601. if (this._onAfterRenderObserver) {
  16602. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16603. }
  16604. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16605. },
  16606. enumerable: true,
  16607. configurable: true
  16608. });
  16609. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16610. set: function (callback) {
  16611. if (this._onBeforeCameraRenderObserver) {
  16612. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16613. }
  16614. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16615. },
  16616. enumerable: true,
  16617. configurable: true
  16618. });
  16619. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16620. set: function (callback) {
  16621. if (this._onAfterCameraRenderObserver) {
  16622. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16623. }
  16624. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16630. get: function () {
  16631. if (!this._gamepadManager) {
  16632. this._gamepadManager = new BABYLON.GamepadManager();
  16633. }
  16634. return this._gamepadManager;
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16640. get: function () {
  16641. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16642. },
  16643. enumerable: true,
  16644. configurable: true
  16645. });
  16646. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16647. get: function () {
  16648. return this._useRightHandedSystem;
  16649. },
  16650. set: function (value) {
  16651. if (this._useRightHandedSystem === value) {
  16652. return;
  16653. }
  16654. this._useRightHandedSystem = value;
  16655. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16656. },
  16657. enumerable: true,
  16658. configurable: true
  16659. });
  16660. Scene.prototype.setStepId = function (newStepId) {
  16661. this._currentStepId = newStepId;
  16662. };
  16663. ;
  16664. Scene.prototype.getStepId = function () {
  16665. return this._currentStepId;
  16666. };
  16667. ;
  16668. Scene.prototype.getInternalStep = function () {
  16669. return this._currentInternalStep;
  16670. };
  16671. ;
  16672. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16673. get: function () {
  16674. return this._fogEnabled;
  16675. },
  16676. /**
  16677. * is fog enabled on this scene.
  16678. */
  16679. set: function (value) {
  16680. if (this._fogEnabled === value) {
  16681. return;
  16682. }
  16683. this._fogEnabled = value;
  16684. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16685. },
  16686. enumerable: true,
  16687. configurable: true
  16688. });
  16689. Object.defineProperty(Scene.prototype, "fogMode", {
  16690. get: function () {
  16691. return this._fogMode;
  16692. },
  16693. set: function (value) {
  16694. if (this._fogMode === value) {
  16695. return;
  16696. }
  16697. this._fogMode = value;
  16698. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16699. },
  16700. enumerable: true,
  16701. configurable: true
  16702. });
  16703. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16704. get: function () {
  16705. return this._shadowsEnabled;
  16706. },
  16707. set: function (value) {
  16708. if (this._shadowsEnabled === value) {
  16709. return;
  16710. }
  16711. this._shadowsEnabled = value;
  16712. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16718. get: function () {
  16719. return this._lightsEnabled;
  16720. },
  16721. set: function (value) {
  16722. if (this._lightsEnabled === value) {
  16723. return;
  16724. }
  16725. this._lightsEnabled = value;
  16726. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16727. },
  16728. enumerable: true,
  16729. configurable: true
  16730. });
  16731. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16732. /** The default material used on meshes when no material is affected */
  16733. get: function () {
  16734. if (!this._defaultMaterial) {
  16735. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16736. }
  16737. return this._defaultMaterial;
  16738. },
  16739. /** The default material used on meshes when no material is affected */
  16740. set: function (value) {
  16741. this._defaultMaterial = value;
  16742. },
  16743. enumerable: true,
  16744. configurable: true
  16745. });
  16746. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16747. get: function () {
  16748. return this._texturesEnabled;
  16749. },
  16750. set: function (value) {
  16751. if (this._texturesEnabled === value) {
  16752. return;
  16753. }
  16754. this._texturesEnabled = value;
  16755. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16756. },
  16757. enumerable: true,
  16758. configurable: true
  16759. });
  16760. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16761. get: function () {
  16762. return this._skeletonsEnabled;
  16763. },
  16764. set: function (value) {
  16765. if (this._skeletonsEnabled === value) {
  16766. return;
  16767. }
  16768. this._skeletonsEnabled = value;
  16769. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16770. },
  16771. enumerable: true,
  16772. configurable: true
  16773. });
  16774. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16775. get: function () {
  16776. if (!this._postProcessRenderPipelineManager) {
  16777. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16778. }
  16779. return this._postProcessRenderPipelineManager;
  16780. },
  16781. enumerable: true,
  16782. configurable: true
  16783. });
  16784. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16785. get: function () {
  16786. return this._frustumPlanes;
  16787. },
  16788. enumerable: true,
  16789. configurable: true
  16790. });
  16791. Object.defineProperty(Scene.prototype, "debugLayer", {
  16792. // Properties
  16793. get: function () {
  16794. if (!this._debugLayer) {
  16795. this._debugLayer = new BABYLON.DebugLayer(this);
  16796. }
  16797. return this._debugLayer;
  16798. },
  16799. enumerable: true,
  16800. configurable: true
  16801. });
  16802. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16803. get: function () {
  16804. return this._workerCollisions;
  16805. },
  16806. set: function (enabled) {
  16807. if (!BABYLON.CollisionCoordinatorLegacy) {
  16808. return;
  16809. }
  16810. enabled = (enabled && !!Worker);
  16811. this._workerCollisions = enabled;
  16812. if (this.collisionCoordinator) {
  16813. this.collisionCoordinator.destroy();
  16814. }
  16815. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16816. this.collisionCoordinator.init(this);
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16822. get: function () {
  16823. return this._selectionOctree;
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16829. /**
  16830. * The mesh that is currently under the pointer.
  16831. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16832. */
  16833. get: function () {
  16834. return this._pointerOverMesh;
  16835. },
  16836. enumerable: true,
  16837. configurable: true
  16838. });
  16839. Object.defineProperty(Scene.prototype, "pointerX", {
  16840. /**
  16841. * Current on-screen X position of the pointer
  16842. * @return {number} X position of the pointer
  16843. */
  16844. get: function () {
  16845. return this._pointerX;
  16846. },
  16847. enumerable: true,
  16848. configurable: true
  16849. });
  16850. Object.defineProperty(Scene.prototype, "pointerY", {
  16851. /**
  16852. * Current on-screen Y position of the pointer
  16853. * @return {number} Y position of the pointer
  16854. */
  16855. get: function () {
  16856. return this._pointerY;
  16857. },
  16858. enumerable: true,
  16859. configurable: true
  16860. });
  16861. Scene.prototype.getCachedMaterial = function () {
  16862. return this._cachedMaterial;
  16863. };
  16864. Scene.prototype.getCachedEffect = function () {
  16865. return this._cachedEffect;
  16866. };
  16867. Scene.prototype.getCachedVisibility = function () {
  16868. return this._cachedVisibility;
  16869. };
  16870. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16871. if (visibility === void 0) { visibility = 1; }
  16872. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16873. };
  16874. Scene.prototype.getBoundingBoxRenderer = function () {
  16875. if (!this._boundingBoxRenderer) {
  16876. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16877. }
  16878. return this._boundingBoxRenderer;
  16879. };
  16880. Scene.prototype.getOutlineRenderer = function () {
  16881. return this._outlineRenderer;
  16882. };
  16883. Scene.prototype.getEngine = function () {
  16884. return this._engine;
  16885. };
  16886. Scene.prototype.getTotalVertices = function () {
  16887. return this._totalVertices.current;
  16888. };
  16889. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16890. get: function () {
  16891. return this._totalVertices;
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Scene.prototype.getActiveIndices = function () {
  16897. return this._activeIndices.current;
  16898. };
  16899. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16900. get: function () {
  16901. return this._activeIndices;
  16902. },
  16903. enumerable: true,
  16904. configurable: true
  16905. });
  16906. Scene.prototype.getActiveParticles = function () {
  16907. return this._activeParticles.current;
  16908. };
  16909. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16910. get: function () {
  16911. return this._activeParticles;
  16912. },
  16913. enumerable: true,
  16914. configurable: true
  16915. });
  16916. Scene.prototype.getActiveBones = function () {
  16917. return this._activeBones.current;
  16918. };
  16919. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16920. get: function () {
  16921. return this._activeBones;
  16922. },
  16923. enumerable: true,
  16924. configurable: true
  16925. });
  16926. // Stats
  16927. Scene.prototype.getLastFrameDuration = function () {
  16928. return this._lastFrameDuration.current;
  16929. };
  16930. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16931. get: function () {
  16932. return this._lastFrameDuration;
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16938. return this._evaluateActiveMeshesDuration.current;
  16939. };
  16940. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16941. get: function () {
  16942. return this._evaluateActiveMeshesDuration;
  16943. },
  16944. enumerable: true,
  16945. configurable: true
  16946. });
  16947. Scene.prototype.getActiveMeshes = function () {
  16948. return this._activeMeshes;
  16949. };
  16950. Scene.prototype.getRenderTargetsDuration = function () {
  16951. return this._renderTargetsDuration.current;
  16952. };
  16953. Scene.prototype.getRenderDuration = function () {
  16954. return this._renderDuration.current;
  16955. };
  16956. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16957. get: function () {
  16958. return this._renderDuration;
  16959. },
  16960. enumerable: true,
  16961. configurable: true
  16962. });
  16963. Scene.prototype.getParticlesDuration = function () {
  16964. return this._particlesDuration.current;
  16965. };
  16966. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16967. get: function () {
  16968. return this._particlesDuration;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. Scene.prototype.getSpritesDuration = function () {
  16974. return this._spritesDuration.current;
  16975. };
  16976. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16977. get: function () {
  16978. return this._spritesDuration;
  16979. },
  16980. enumerable: true,
  16981. configurable: true
  16982. });
  16983. Scene.prototype.getAnimationRatio = function () {
  16984. return this._animationRatio;
  16985. };
  16986. Scene.prototype.getRenderId = function () {
  16987. return this._renderId;
  16988. };
  16989. Scene.prototype.incrementRenderId = function () {
  16990. this._renderId++;
  16991. };
  16992. Scene.prototype._updatePointerPosition = function (evt) {
  16993. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16994. this._pointerX = evt.clientX - canvasRect.left;
  16995. this._pointerY = evt.clientY - canvasRect.top;
  16996. this._unTranslatedPointerX = this._pointerX;
  16997. this._unTranslatedPointerY = this._pointerY;
  16998. };
  16999. Scene.prototype._createUbo = function () {
  17000. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17001. this._sceneUbo.addUniform("viewProjection", 16);
  17002. this._sceneUbo.addUniform("view", 16);
  17003. };
  17004. // Pointers handling
  17005. /**
  17006. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17007. * @param attachUp defines if you want to attach events to pointerup
  17008. * @param attachDown defines if you want to attach events to pointerdown
  17009. * @param attachMove defines if you want to attach events to pointermove
  17010. */
  17011. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17012. var _this = this;
  17013. if (attachUp === void 0) { attachUp = true; }
  17014. if (attachDown === void 0) { attachDown = true; }
  17015. if (attachMove === void 0) { attachMove = true; }
  17016. this._initActionManager = function (act, clickInfo) {
  17017. if (!_this._meshPickProceed) {
  17018. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17019. _this._currentPickResult = pickResult;
  17020. if (pickResult) {
  17021. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17022. }
  17023. _this._meshPickProceed = true;
  17024. }
  17025. return act;
  17026. };
  17027. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17028. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17029. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17030. btn !== _this._previousButtonPressed) {
  17031. _this._doubleClickOccured = false;
  17032. clickInfo.singleClick = true;
  17033. clickInfo.ignore = false;
  17034. cb(clickInfo, _this._currentPickResult);
  17035. }
  17036. };
  17037. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17038. var clickInfo = new ClickInfo();
  17039. _this._currentPickResult = null;
  17040. var act;
  17041. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  17042. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  17043. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17044. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17045. act = _this._initActionManager(act, clickInfo);
  17046. if (act)
  17047. checkPicking = act.hasPickTriggers;
  17048. }
  17049. if (checkPicking) {
  17050. var btn = evt.button;
  17051. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17052. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17053. if (!clickInfo.hasSwiped) {
  17054. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17055. if (!checkSingleClickImmediately) {
  17056. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  17057. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17058. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17059. act = _this._initActionManager(act, clickInfo);
  17060. if (act)
  17061. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17062. }
  17063. }
  17064. if (checkSingleClickImmediately) {
  17065. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17066. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17067. btn !== _this._previousButtonPressed) {
  17068. clickInfo.singleClick = true;
  17069. cb(clickInfo, _this._currentPickResult);
  17070. }
  17071. }
  17072. else {
  17073. // wait that no double click has been raised during the double click delay
  17074. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17075. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17076. }
  17077. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  17078. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17079. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17080. act = _this._initActionManager(act, clickInfo);
  17081. if (act)
  17082. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17083. }
  17084. if (checkDoubleClick) {
  17085. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17086. if (btn === _this._previousButtonPressed &&
  17087. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17088. !_this._doubleClickOccured) {
  17089. // pointer has not moved for 2 clicks, it's a double click
  17090. if (!clickInfo.hasSwiped &&
  17091. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17092. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17093. _this._previousStartingPointerTime = 0;
  17094. _this._doubleClickOccured = true;
  17095. clickInfo.doubleClick = true;
  17096. clickInfo.ignore = false;
  17097. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17098. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17099. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17100. cb(clickInfo, _this._currentPickResult);
  17101. }
  17102. else {
  17103. _this._doubleClickOccured = false;
  17104. _this._previousStartingPointerTime = _this._startingPointerTime;
  17105. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17106. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17107. _this._previousButtonPressed = btn;
  17108. _this._previousHasSwiped = clickInfo.hasSwiped;
  17109. if (Scene.ExclusiveDoubleClickMode) {
  17110. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17111. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17112. }
  17113. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17114. cb(clickInfo, _this._previousPickResult);
  17115. }
  17116. else {
  17117. cb(clickInfo, _this._currentPickResult);
  17118. }
  17119. }
  17120. }
  17121. else {
  17122. _this._doubleClickOccured = false;
  17123. _this._previousStartingPointerTime = _this._startingPointerTime;
  17124. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17125. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17126. _this._previousButtonPressed = btn;
  17127. _this._previousHasSwiped = clickInfo.hasSwiped;
  17128. }
  17129. }
  17130. }
  17131. }
  17132. clickInfo.ignore = true;
  17133. cb(clickInfo, _this._currentPickResult);
  17134. };
  17135. var spritePredicate = function (sprite) {
  17136. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17137. };
  17138. this._onPointerMove = function (evt) {
  17139. _this._updatePointerPosition(evt);
  17140. // PreObservable support
  17141. if (_this.onPrePointerObservable.hasObservers()) {
  17142. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17143. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17144. _this.onPrePointerObservable.notifyObservers(pi, type);
  17145. if (pi.skipOnPointerObservable) {
  17146. return;
  17147. }
  17148. }
  17149. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17150. return;
  17151. }
  17152. var canvas = _this._engine.getRenderingCanvas();
  17153. if (!_this.pointerMovePredicate) {
  17154. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17155. }
  17156. // Meshes
  17157. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17158. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17159. _this.setPointerOverSprite(null);
  17160. _this.setPointerOverMesh(pickResult.pickedMesh);
  17161. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17162. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17163. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17164. }
  17165. else {
  17166. canvas.style.cursor = _this.hoverCursor;
  17167. }
  17168. }
  17169. else {
  17170. canvas.style.cursor = _this.defaultCursor;
  17171. }
  17172. }
  17173. else {
  17174. _this.setPointerOverMesh(null);
  17175. // Sprites
  17176. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17177. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17178. _this.setPointerOverSprite(pickResult.pickedSprite);
  17179. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17180. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17181. }
  17182. else {
  17183. canvas.style.cursor = _this.hoverCursor;
  17184. }
  17185. }
  17186. else {
  17187. _this.setPointerOverSprite(null);
  17188. // Restore pointer
  17189. canvas.style.cursor = _this.defaultCursor;
  17190. }
  17191. }
  17192. if (_this.onPointerMove) {
  17193. _this.onPointerMove(evt, pickResult);
  17194. }
  17195. if (_this.onPointerObservable.hasObservers()) {
  17196. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17197. var pi = new PointerInfo(type, evt, pickResult);
  17198. _this.onPointerObservable.notifyObservers(pi, type);
  17199. }
  17200. };
  17201. this._onPointerDown = function (evt) {
  17202. _this._isButtonPressed = true;
  17203. _this._pickedDownMesh = null;
  17204. _this._meshPickProceed = false;
  17205. _this._updatePointerPosition(evt);
  17206. // PreObservable support
  17207. if (_this.onPrePointerObservable.hasObservers()) {
  17208. var type = PointerEventTypes.POINTERDOWN;
  17209. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17210. _this.onPrePointerObservable.notifyObservers(pi, type);
  17211. if (pi.skipOnPointerObservable) {
  17212. return;
  17213. }
  17214. }
  17215. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17216. return;
  17217. }
  17218. _this._startingPointerPosition.x = _this._pointerX;
  17219. _this._startingPointerPosition.y = _this._pointerY;
  17220. _this._startingPointerTime = new Date().getTime();
  17221. if (!_this.pointerDownPredicate) {
  17222. _this.pointerDownPredicate = function (mesh) {
  17223. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17224. };
  17225. }
  17226. // Meshes
  17227. _this._pickedDownMesh = null;
  17228. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17229. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17230. _this._pickedDownMesh = pickResult.pickedMesh;
  17231. var actionManager = pickResult.pickedMesh.actionManager;
  17232. if (actionManager) {
  17233. if (actionManager.hasPickTriggers) {
  17234. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17235. switch (evt.button) {
  17236. case 0:
  17237. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17238. break;
  17239. case 1:
  17240. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17241. break;
  17242. case 2:
  17243. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17244. break;
  17245. }
  17246. }
  17247. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17248. window.setTimeout((function () {
  17249. var _this = this;
  17250. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh; }, false, this.cameraToUseForPointers);
  17251. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17252. if (this._isButtonPressed &&
  17253. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17254. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17255. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17256. this._startingPointerTime = 0;
  17257. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17258. }
  17259. }
  17260. }).bind(_this), Scene.LongPressDelay);
  17261. }
  17262. }
  17263. }
  17264. if (_this.onPointerDown) {
  17265. _this.onPointerDown(evt, pickResult);
  17266. }
  17267. if (_this.onPointerObservable.hasObservers()) {
  17268. var type = PointerEventTypes.POINTERDOWN;
  17269. var pi = new PointerInfo(type, evt, pickResult);
  17270. _this.onPointerObservable.notifyObservers(pi, type);
  17271. }
  17272. // Sprites
  17273. _this._pickedDownSprite = null;
  17274. if (_this.spriteManagers.length > 0) {
  17275. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17276. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17277. if (pickResult.pickedSprite.actionManager) {
  17278. _this._pickedDownSprite = pickResult.pickedSprite;
  17279. switch (evt.button) {
  17280. case 0:
  17281. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17282. break;
  17283. case 1:
  17284. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17285. break;
  17286. case 2:
  17287. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17288. break;
  17289. }
  17290. if (pickResult.pickedSprite.actionManager) {
  17291. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17292. }
  17293. }
  17294. }
  17295. }
  17296. };
  17297. this._onPointerUp = function (evt) {
  17298. _this._isButtonPressed = false;
  17299. _this._pickedUpMesh = null;
  17300. _this._meshPickProceed = false;
  17301. _this._updatePointerPosition(evt);
  17302. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17303. // PreObservable support
  17304. if (this.onPrePointerObservable.hasObservers()) {
  17305. if (!clickInfo.ignore) {
  17306. if (!clickInfo.hasSwiped) {
  17307. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17308. var type = PointerEventTypes.POINTERTAP;
  17309. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17310. this.onPrePointerObservable.notifyObservers(pi, type);
  17311. if (pi.skipOnPointerObservable) {
  17312. return;
  17313. }
  17314. }
  17315. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17316. var type = PointerEventTypes.POINTERDOUBLETAP;
  17317. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17318. this.onPrePointerObservable.notifyObservers(pi, type);
  17319. if (pi.skipOnPointerObservable) {
  17320. return;
  17321. }
  17322. }
  17323. }
  17324. }
  17325. else {
  17326. var type = PointerEventTypes.POINTERUP;
  17327. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17328. this.onPrePointerObservable.notifyObservers(pi, type);
  17329. if (pi.skipOnPointerObservable) {
  17330. return;
  17331. }
  17332. }
  17333. }
  17334. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17335. return;
  17336. }
  17337. if (!this.pointerUpPredicate) {
  17338. this.pointerUpPredicate = function (mesh) {
  17339. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17340. };
  17341. }
  17342. // Meshes
  17343. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17344. this._initActionManager(null, clickInfo);
  17345. }
  17346. if (!pickResult) {
  17347. pickResult = this._currentPickResult;
  17348. }
  17349. if (pickResult && pickResult && pickResult.pickedMesh) {
  17350. this._pickedUpMesh = pickResult.pickedMesh;
  17351. if (this._pickedDownMesh === this._pickedUpMesh) {
  17352. if (this.onPointerPick) {
  17353. this.onPointerPick(evt, pickResult);
  17354. }
  17355. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17356. var type = PointerEventTypes.POINTERPICK;
  17357. var pi = new PointerInfo(type, evt, pickResult);
  17358. this.onPointerObservable.notifyObservers(pi, type);
  17359. }
  17360. }
  17361. if (pickResult.pickedMesh.actionManager) {
  17362. if (clickInfo.ignore) {
  17363. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17364. }
  17365. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17366. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17367. }
  17368. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17369. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17370. }
  17371. }
  17372. }
  17373. if (this._pickedDownMesh &&
  17374. this._pickedDownMesh.actionManager &&
  17375. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17376. this._pickedDownMesh !== this._pickedUpMesh) {
  17377. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17378. }
  17379. if (this.onPointerUp) {
  17380. this.onPointerUp(evt, pickResult);
  17381. }
  17382. if (this.onPointerObservable.hasObservers()) {
  17383. if (!clickInfo.ignore) {
  17384. if (!clickInfo.hasSwiped) {
  17385. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17386. var type = PointerEventTypes.POINTERTAP;
  17387. var pi = new PointerInfo(type, evt, pickResult);
  17388. this.onPointerObservable.notifyObservers(pi, type);
  17389. }
  17390. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17391. var type = PointerEventTypes.POINTERDOUBLETAP;
  17392. var pi = new PointerInfo(type, evt, pickResult);
  17393. this.onPointerObservable.notifyObservers(pi, type);
  17394. }
  17395. }
  17396. }
  17397. else {
  17398. var type = PointerEventTypes.POINTERUP;
  17399. var pi = new PointerInfo(type, evt, pickResult);
  17400. this.onPointerObservable.notifyObservers(pi, type);
  17401. }
  17402. }
  17403. // Sprites
  17404. if (this.spriteManagers.length > 0) {
  17405. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17406. if (pickResult.hit && pickResult.pickedSprite) {
  17407. if (pickResult.pickedSprite.actionManager) {
  17408. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17409. if (pickResult.pickedSprite.actionManager) {
  17410. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17411. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17412. }
  17413. }
  17414. }
  17415. }
  17416. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17417. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17418. }
  17419. }
  17420. this._previousPickResult = this._currentPickResult;
  17421. }).bind(_this));
  17422. };
  17423. this._onKeyDown = function (evt) {
  17424. if (_this.actionManager) {
  17425. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17426. }
  17427. };
  17428. this._onKeyUp = function (evt) {
  17429. if (_this.actionManager) {
  17430. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17431. }
  17432. };
  17433. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17434. var canvas = this._engine.getRenderingCanvas();
  17435. if (attachMove) {
  17436. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17437. // Wheel
  17438. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17439. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17440. }
  17441. if (attachDown) {
  17442. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17443. }
  17444. if (attachUp) {
  17445. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17446. }
  17447. canvas.tabIndex = 1;
  17448. canvas.addEventListener("keydown", this._onKeyDown, false);
  17449. canvas.addEventListener("keyup", this._onKeyUp, false);
  17450. };
  17451. Scene.prototype.detachControl = function () {
  17452. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17453. var canvas = this._engine.getRenderingCanvas();
  17454. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17455. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17456. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17457. // Wheel
  17458. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17459. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17460. canvas.removeEventListener("keydown", this._onKeyDown);
  17461. canvas.removeEventListener("keyup", this._onKeyUp);
  17462. };
  17463. // Ready
  17464. Scene.prototype.isReady = function () {
  17465. if (this._pendingData.length > 0) {
  17466. return false;
  17467. }
  17468. var index;
  17469. // Geometries
  17470. for (index = 0; index < this._geometries.length; index++) {
  17471. var geometry = this._geometries[index];
  17472. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17473. return false;
  17474. }
  17475. }
  17476. // Meshes
  17477. for (index = 0; index < this.meshes.length; index++) {
  17478. var mesh = this.meshes[index];
  17479. if (!mesh.isEnabled()) {
  17480. continue;
  17481. }
  17482. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17483. continue;
  17484. }
  17485. if (!mesh.isReady()) {
  17486. return false;
  17487. }
  17488. var mat = mesh.material;
  17489. if (mat) {
  17490. if (!mat.isReady(mesh)) {
  17491. return false;
  17492. }
  17493. }
  17494. }
  17495. return true;
  17496. };
  17497. Scene.prototype.resetCachedMaterial = function () {
  17498. this._cachedMaterial = null;
  17499. this._cachedEffect = null;
  17500. this._cachedVisibility = null;
  17501. };
  17502. Scene.prototype.registerBeforeRender = function (func) {
  17503. this.onBeforeRenderObservable.add(func);
  17504. };
  17505. Scene.prototype.unregisterBeforeRender = function (func) {
  17506. this.onBeforeRenderObservable.removeCallback(func);
  17507. };
  17508. Scene.prototype.registerAfterRender = function (func) {
  17509. this.onAfterRenderObservable.add(func);
  17510. };
  17511. Scene.prototype.unregisterAfterRender = function (func) {
  17512. this.onAfterRenderObservable.removeCallback(func);
  17513. };
  17514. Scene.prototype._addPendingData = function (data) {
  17515. this._pendingData.push(data);
  17516. };
  17517. Scene.prototype._removePendingData = function (data) {
  17518. var index = this._pendingData.indexOf(data);
  17519. if (index !== -1) {
  17520. this._pendingData.splice(index, 1);
  17521. }
  17522. };
  17523. Scene.prototype.getWaitingItemsCount = function () {
  17524. return this._pendingData.length;
  17525. };
  17526. /**
  17527. * Registers a function to be executed when the scene is ready.
  17528. * @param {Function} func - the function to be executed.
  17529. */
  17530. Scene.prototype.executeWhenReady = function (func) {
  17531. var _this = this;
  17532. this.onReadyObservable.add(func);
  17533. if (this._executeWhenReadyTimeoutId !== -1) {
  17534. return;
  17535. }
  17536. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17537. _this._checkIsReady();
  17538. }, 150);
  17539. };
  17540. Scene.prototype._checkIsReady = function () {
  17541. var _this = this;
  17542. if (this.isReady()) {
  17543. this.onReadyObservable.notifyObservers(this);
  17544. this.onReadyObservable.clear();
  17545. this._executeWhenReadyTimeoutId = -1;
  17546. return;
  17547. }
  17548. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17549. _this._checkIsReady();
  17550. }, 150);
  17551. };
  17552. // Animations
  17553. /**
  17554. * Will start the animation sequence of a given target
  17555. * @param target - the target
  17556. * @param {number} from - from which frame should animation start
  17557. * @param {number} to - till which frame should animation run.
  17558. * @param {boolean} [loop] - should the animation loop
  17559. * @param {number} [speedRatio] - the speed in which to run the animation
  17560. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17561. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17562. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17563. * See BABYLON.Animatable
  17564. */
  17565. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17566. if (speedRatio === void 0) { speedRatio = 1.0; }
  17567. if (from > to && speedRatio > 0) {
  17568. speedRatio *= -1;
  17569. }
  17570. this.stopAnimation(target);
  17571. if (!animatable) {
  17572. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17573. }
  17574. // Local animations
  17575. if (target.animations) {
  17576. animatable.appendAnimations(target, target.animations);
  17577. }
  17578. // Children animations
  17579. if (target.getAnimatables) {
  17580. var animatables = target.getAnimatables();
  17581. for (var index = 0; index < animatables.length; index++) {
  17582. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17583. }
  17584. }
  17585. animatable.reset();
  17586. return animatable;
  17587. };
  17588. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17589. if (speedRatio === undefined) {
  17590. speedRatio = 1.0;
  17591. }
  17592. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17593. return animatable;
  17594. };
  17595. Scene.prototype.getAnimatableByTarget = function (target) {
  17596. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17597. if (this._activeAnimatables[index].target === target) {
  17598. return this._activeAnimatables[index];
  17599. }
  17600. }
  17601. return null;
  17602. };
  17603. Object.defineProperty(Scene.prototype, "Animatables", {
  17604. get: function () {
  17605. return this._activeAnimatables;
  17606. },
  17607. enumerable: true,
  17608. configurable: true
  17609. });
  17610. /**
  17611. * Will stop the animation of the given target
  17612. * @param target - the target
  17613. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17614. * @see beginAnimation
  17615. */
  17616. Scene.prototype.stopAnimation = function (target, animationName) {
  17617. var animatable = this.getAnimatableByTarget(target);
  17618. if (animatable) {
  17619. animatable.stop(animationName);
  17620. }
  17621. };
  17622. Scene.prototype._animate = function () {
  17623. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17624. return;
  17625. }
  17626. // Getting time
  17627. var now = BABYLON.Tools.Now;
  17628. if (!this._animationTimeLast) {
  17629. if (this._pendingData.length > 0) {
  17630. return;
  17631. }
  17632. this._animationTimeLast = now;
  17633. }
  17634. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17635. this._animationTime += deltaTime;
  17636. this._animationTimeLast = now;
  17637. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17638. this._activeAnimatables[index]._animate(this._animationTime);
  17639. }
  17640. };
  17641. // Matrix
  17642. Scene.prototype.getViewMatrix = function () {
  17643. return this._viewMatrix;
  17644. };
  17645. Scene.prototype.getProjectionMatrix = function () {
  17646. return this._projectionMatrix;
  17647. };
  17648. Scene.prototype.getTransformMatrix = function () {
  17649. return this._transformMatrix;
  17650. };
  17651. Scene.prototype.setTransformMatrix = function (view, projection) {
  17652. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17653. return;
  17654. }
  17655. this._viewUpdateFlag = view.updateFlag;
  17656. this._projectionUpdateFlag = projection.updateFlag;
  17657. this._viewMatrix = view;
  17658. this._projectionMatrix = projection;
  17659. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17660. // Update frustum
  17661. if (!this._frustumPlanes) {
  17662. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17663. }
  17664. else {
  17665. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17666. }
  17667. if (this._sceneUbo.useUbo) {
  17668. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17669. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17670. this._sceneUbo.update();
  17671. }
  17672. };
  17673. Scene.prototype.getSceneUniformBuffer = function () {
  17674. return this._sceneUbo;
  17675. };
  17676. // Methods
  17677. Scene.prototype.getUniqueId = function () {
  17678. var result = this._uniqueIdCounter;
  17679. this._uniqueIdCounter++;
  17680. return result;
  17681. };
  17682. Scene.prototype.addMesh = function (newMesh) {
  17683. newMesh.uniqueId = this.getUniqueId();
  17684. var position = this.meshes.push(newMesh);
  17685. //notify the collision coordinator
  17686. if (this.collisionCoordinator) {
  17687. this.collisionCoordinator.onMeshAdded(newMesh);
  17688. }
  17689. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17690. };
  17691. Scene.prototype.removeMesh = function (toRemove) {
  17692. var index = this.meshes.indexOf(toRemove);
  17693. if (index !== -1) {
  17694. // Remove from the scene if mesh found
  17695. this.meshes.splice(index, 1);
  17696. }
  17697. //notify the collision coordinator
  17698. if (this.collisionCoordinator) {
  17699. this.collisionCoordinator.onMeshRemoved(toRemove);
  17700. }
  17701. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17702. return index;
  17703. };
  17704. Scene.prototype.removeSkeleton = function (toRemove) {
  17705. var index = this.skeletons.indexOf(toRemove);
  17706. if (index !== -1) {
  17707. // Remove from the scene if found
  17708. this.skeletons.splice(index, 1);
  17709. }
  17710. return index;
  17711. };
  17712. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17713. var index = this.morphTargetManagers.indexOf(toRemove);
  17714. if (index !== -1) {
  17715. // Remove from the scene if found
  17716. this.morphTargetManagers.splice(index, 1);
  17717. }
  17718. return index;
  17719. };
  17720. Scene.prototype.removeLight = function (toRemove) {
  17721. var index = this.lights.indexOf(toRemove);
  17722. if (index !== -1) {
  17723. // Remove from the scene if mesh found
  17724. this.lights.splice(index, 1);
  17725. this.sortLightsByPriority();
  17726. }
  17727. this.onLightRemovedObservable.notifyObservers(toRemove);
  17728. return index;
  17729. };
  17730. Scene.prototype.removeCamera = function (toRemove) {
  17731. var index = this.cameras.indexOf(toRemove);
  17732. if (index !== -1) {
  17733. // Remove from the scene if mesh found
  17734. this.cameras.splice(index, 1);
  17735. }
  17736. // Remove from activeCameras
  17737. var index2 = this.activeCameras.indexOf(toRemove);
  17738. if (index2 !== -1) {
  17739. // Remove from the scene if mesh found
  17740. this.activeCameras.splice(index2, 1);
  17741. }
  17742. // Reset the activeCamera
  17743. if (this.activeCamera === toRemove) {
  17744. if (this.cameras.length > 0) {
  17745. this.activeCamera = this.cameras[0];
  17746. }
  17747. else {
  17748. this.activeCamera = null;
  17749. }
  17750. }
  17751. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17752. return index;
  17753. };
  17754. Scene.prototype.addLight = function (newLight) {
  17755. newLight.uniqueId = this.getUniqueId();
  17756. this.lights.push(newLight);
  17757. this.sortLightsByPriority();
  17758. this.onNewLightAddedObservable.notifyObservers(newLight);
  17759. };
  17760. Scene.prototype.sortLightsByPriority = function () {
  17761. if (this.requireLightSorting) {
  17762. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17763. }
  17764. };
  17765. Scene.prototype.addCamera = function (newCamera) {
  17766. newCamera.uniqueId = this.getUniqueId();
  17767. var position = this.cameras.push(newCamera);
  17768. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17769. };
  17770. /**
  17771. * Switch active camera
  17772. * @param {Camera} newCamera - new active camera
  17773. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17774. */
  17775. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17776. if (attachControl === void 0) { attachControl = true; }
  17777. var canvas = this._engine.getRenderingCanvas();
  17778. this.activeCamera.detachControl(canvas);
  17779. this.activeCamera = newCamera;
  17780. if (attachControl) {
  17781. newCamera.attachControl(canvas);
  17782. }
  17783. };
  17784. /**
  17785. * sets the active camera of the scene using its ID
  17786. * @param {string} id - the camera's ID
  17787. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17788. * @see activeCamera
  17789. */
  17790. Scene.prototype.setActiveCameraByID = function (id) {
  17791. var camera = this.getCameraByID(id);
  17792. if (camera) {
  17793. this.activeCamera = camera;
  17794. return camera;
  17795. }
  17796. return null;
  17797. };
  17798. /**
  17799. * sets the active camera of the scene using its name
  17800. * @param {string} name - the camera's name
  17801. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17802. * @see activeCamera
  17803. */
  17804. Scene.prototype.setActiveCameraByName = function (name) {
  17805. var camera = this.getCameraByName(name);
  17806. if (camera) {
  17807. this.activeCamera = camera;
  17808. return camera;
  17809. }
  17810. return null;
  17811. };
  17812. /**
  17813. * get a material using its id
  17814. * @param {string} the material's ID
  17815. * @return {BABYLON.Material|null} the material or null if none found.
  17816. */
  17817. Scene.prototype.getMaterialByID = function (id) {
  17818. for (var index = 0; index < this.materials.length; index++) {
  17819. if (this.materials[index].id === id) {
  17820. return this.materials[index];
  17821. }
  17822. }
  17823. return null;
  17824. };
  17825. /**
  17826. * get a material using its name
  17827. * @param {string} the material's name
  17828. * @return {BABYLON.Material|null} the material or null if none found.
  17829. */
  17830. Scene.prototype.getMaterialByName = function (name) {
  17831. for (var index = 0; index < this.materials.length; index++) {
  17832. if (this.materials[index].name === name) {
  17833. return this.materials[index];
  17834. }
  17835. }
  17836. return null;
  17837. };
  17838. Scene.prototype.getLensFlareSystemByName = function (name) {
  17839. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17840. if (this.lensFlareSystems[index].name === name) {
  17841. return this.lensFlareSystems[index];
  17842. }
  17843. }
  17844. return null;
  17845. };
  17846. Scene.prototype.getLensFlareSystemByID = function (id) {
  17847. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17848. if (this.lensFlareSystems[index].id === id) {
  17849. return this.lensFlareSystems[index];
  17850. }
  17851. }
  17852. return null;
  17853. };
  17854. Scene.prototype.getCameraByID = function (id) {
  17855. for (var index = 0; index < this.cameras.length; index++) {
  17856. if (this.cameras[index].id === id) {
  17857. return this.cameras[index];
  17858. }
  17859. }
  17860. return null;
  17861. };
  17862. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17863. for (var index = 0; index < this.cameras.length; index++) {
  17864. if (this.cameras[index].uniqueId === uniqueId) {
  17865. return this.cameras[index];
  17866. }
  17867. }
  17868. return null;
  17869. };
  17870. /**
  17871. * get a camera using its name
  17872. * @param {string} the camera's name
  17873. * @return {BABYLON.Camera|null} the camera or null if none found.
  17874. */
  17875. Scene.prototype.getCameraByName = function (name) {
  17876. for (var index = 0; index < this.cameras.length; index++) {
  17877. if (this.cameras[index].name === name) {
  17878. return this.cameras[index];
  17879. }
  17880. }
  17881. return null;
  17882. };
  17883. /**
  17884. * get a bone using its id
  17885. * @param {string} the bone's id
  17886. * @return {BABYLON.Bone|null} the bone or null if not found
  17887. */
  17888. Scene.prototype.getBoneByID = function (id) {
  17889. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17890. var skeleton = this.skeletons[skeletonIndex];
  17891. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17892. if (skeleton.bones[boneIndex].id === id) {
  17893. return skeleton.bones[boneIndex];
  17894. }
  17895. }
  17896. }
  17897. return null;
  17898. };
  17899. /**
  17900. * get a bone using its id
  17901. * @param {string} the bone's name
  17902. * @return {BABYLON.Bone|null} the bone or null if not found
  17903. */
  17904. Scene.prototype.getBoneByName = function (name) {
  17905. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17906. var skeleton = this.skeletons[skeletonIndex];
  17907. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17908. if (skeleton.bones[boneIndex].name === name) {
  17909. return skeleton.bones[boneIndex];
  17910. }
  17911. }
  17912. }
  17913. return null;
  17914. };
  17915. /**
  17916. * get a light node using its name
  17917. * @param {string} the light's name
  17918. * @return {BABYLON.Light|null} the light or null if none found.
  17919. */
  17920. Scene.prototype.getLightByName = function (name) {
  17921. for (var index = 0; index < this.lights.length; index++) {
  17922. if (this.lights[index].name === name) {
  17923. return this.lights[index];
  17924. }
  17925. }
  17926. return null;
  17927. };
  17928. /**
  17929. * get a light node using its ID
  17930. * @param {string} the light's id
  17931. * @return {BABYLON.Light|null} the light or null if none found.
  17932. */
  17933. Scene.prototype.getLightByID = function (id) {
  17934. for (var index = 0; index < this.lights.length; index++) {
  17935. if (this.lights[index].id === id) {
  17936. return this.lights[index];
  17937. }
  17938. }
  17939. return null;
  17940. };
  17941. /**
  17942. * get a light node using its scene-generated unique ID
  17943. * @param {number} the light's unique id
  17944. * @return {BABYLON.Light|null} the light or null if none found.
  17945. */
  17946. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17947. for (var index = 0; index < this.lights.length; index++) {
  17948. if (this.lights[index].uniqueId === uniqueId) {
  17949. return this.lights[index];
  17950. }
  17951. }
  17952. return null;
  17953. };
  17954. /**
  17955. * get a particle system by id
  17956. * @param id {number} the particle system id
  17957. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17958. */
  17959. Scene.prototype.getParticleSystemByID = function (id) {
  17960. for (var index = 0; index < this.particleSystems.length; index++) {
  17961. if (this.particleSystems[index].id === id) {
  17962. return this.particleSystems[index];
  17963. }
  17964. }
  17965. return null;
  17966. };
  17967. /**
  17968. * get a geometry using its ID
  17969. * @param {string} the geometry's id
  17970. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17971. */
  17972. Scene.prototype.getGeometryByID = function (id) {
  17973. for (var index = 0; index < this._geometries.length; index++) {
  17974. if (this._geometries[index].id === id) {
  17975. return this._geometries[index];
  17976. }
  17977. }
  17978. return null;
  17979. };
  17980. /**
  17981. * add a new geometry to this scene.
  17982. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17983. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17984. * @return {boolean} was the geometry added or not
  17985. */
  17986. Scene.prototype.pushGeometry = function (geometry, force) {
  17987. if (!force && this.getGeometryByID(geometry.id)) {
  17988. return false;
  17989. }
  17990. this._geometries.push(geometry);
  17991. //notify the collision coordinator
  17992. if (this.collisionCoordinator) {
  17993. this.collisionCoordinator.onGeometryAdded(geometry);
  17994. }
  17995. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17996. return true;
  17997. };
  17998. /**
  17999. * Removes an existing geometry
  18000. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18001. * @return {boolean} was the geometry removed or not
  18002. */
  18003. Scene.prototype.removeGeometry = function (geometry) {
  18004. var index = this._geometries.indexOf(geometry);
  18005. if (index > -1) {
  18006. this._geometries.splice(index, 1);
  18007. //notify the collision coordinator
  18008. if (this.collisionCoordinator) {
  18009. this.collisionCoordinator.onGeometryDeleted(geometry);
  18010. }
  18011. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18012. return true;
  18013. }
  18014. return false;
  18015. };
  18016. Scene.prototype.getGeometries = function () {
  18017. return this._geometries;
  18018. };
  18019. /**
  18020. * Get the first added mesh found of a given ID
  18021. * @param {string} id - the id to search for
  18022. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18023. */
  18024. Scene.prototype.getMeshByID = function (id) {
  18025. for (var index = 0; index < this.meshes.length; index++) {
  18026. if (this.meshes[index].id === id) {
  18027. return this.meshes[index];
  18028. }
  18029. }
  18030. return null;
  18031. };
  18032. Scene.prototype.getMeshesByID = function (id) {
  18033. return this.meshes.filter(function (m) {
  18034. return m.id === id;
  18035. });
  18036. };
  18037. /**
  18038. * Get a mesh with its auto-generated unique id
  18039. * @param {number} uniqueId - the unique id to search for
  18040. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18041. */
  18042. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18043. for (var index = 0; index < this.meshes.length; index++) {
  18044. if (this.meshes[index].uniqueId === uniqueId) {
  18045. return this.meshes[index];
  18046. }
  18047. }
  18048. return null;
  18049. };
  18050. /**
  18051. * Get a the last added mesh found of a given ID
  18052. * @param {string} id - the id to search for
  18053. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18054. */
  18055. Scene.prototype.getLastMeshByID = function (id) {
  18056. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18057. if (this.meshes[index].id === id) {
  18058. return this.meshes[index];
  18059. }
  18060. }
  18061. return null;
  18062. };
  18063. /**
  18064. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18065. * @param {string} id - the id to search for
  18066. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18067. */
  18068. Scene.prototype.getLastEntryByID = function (id) {
  18069. var index;
  18070. for (index = this.meshes.length - 1; index >= 0; index--) {
  18071. if (this.meshes[index].id === id) {
  18072. return this.meshes[index];
  18073. }
  18074. }
  18075. for (index = this.cameras.length - 1; index >= 0; index--) {
  18076. if (this.cameras[index].id === id) {
  18077. return this.cameras[index];
  18078. }
  18079. }
  18080. for (index = this.lights.length - 1; index >= 0; index--) {
  18081. if (this.lights[index].id === id) {
  18082. return this.lights[index];
  18083. }
  18084. }
  18085. return null;
  18086. };
  18087. Scene.prototype.getNodeByID = function (id) {
  18088. var mesh = this.getMeshByID(id);
  18089. if (mesh) {
  18090. return mesh;
  18091. }
  18092. var light = this.getLightByID(id);
  18093. if (light) {
  18094. return light;
  18095. }
  18096. var camera = this.getCameraByID(id);
  18097. if (camera) {
  18098. return camera;
  18099. }
  18100. var bone = this.getBoneByID(id);
  18101. return bone;
  18102. };
  18103. Scene.prototype.getNodeByName = function (name) {
  18104. var mesh = this.getMeshByName(name);
  18105. if (mesh) {
  18106. return mesh;
  18107. }
  18108. var light = this.getLightByName(name);
  18109. if (light) {
  18110. return light;
  18111. }
  18112. var camera = this.getCameraByName(name);
  18113. if (camera) {
  18114. return camera;
  18115. }
  18116. var bone = this.getBoneByName(name);
  18117. return bone;
  18118. };
  18119. Scene.prototype.getMeshByName = function (name) {
  18120. for (var index = 0; index < this.meshes.length; index++) {
  18121. if (this.meshes[index].name === name) {
  18122. return this.meshes[index];
  18123. }
  18124. }
  18125. return null;
  18126. };
  18127. Scene.prototype.getSoundByName = function (name) {
  18128. var index;
  18129. if (BABYLON.AudioEngine) {
  18130. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18131. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18132. return this.mainSoundTrack.soundCollection[index];
  18133. }
  18134. }
  18135. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18136. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18137. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18138. return this.soundTracks[sdIndex].soundCollection[index];
  18139. }
  18140. }
  18141. }
  18142. }
  18143. return null;
  18144. };
  18145. Scene.prototype.getLastSkeletonByID = function (id) {
  18146. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18147. if (this.skeletons[index].id === id) {
  18148. return this.skeletons[index];
  18149. }
  18150. }
  18151. return null;
  18152. };
  18153. Scene.prototype.getSkeletonById = function (id) {
  18154. for (var index = 0; index < this.skeletons.length; index++) {
  18155. if (this.skeletons[index].id === id) {
  18156. return this.skeletons[index];
  18157. }
  18158. }
  18159. return null;
  18160. };
  18161. Scene.prototype.getSkeletonByName = function (name) {
  18162. for (var index = 0; index < this.skeletons.length; index++) {
  18163. if (this.skeletons[index].name === name) {
  18164. return this.skeletons[index];
  18165. }
  18166. }
  18167. return null;
  18168. };
  18169. Scene.prototype.getMorphTargetManagerById = function (id) {
  18170. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18171. if (this.morphTargetManagers[index].uniqueId === id) {
  18172. return this.morphTargetManagers[index];
  18173. }
  18174. }
  18175. return null;
  18176. };
  18177. Scene.prototype.isActiveMesh = function (mesh) {
  18178. return (this._activeMeshes.indexOf(mesh) !== -1);
  18179. };
  18180. /**
  18181. * Return a the first highlight layer of the scene with a given name.
  18182. * @param name The name of the highlight layer to look for.
  18183. * @return The highlight layer if found otherwise null.
  18184. */
  18185. Scene.prototype.getHighlightLayerByName = function (name) {
  18186. for (var index = 0; index < this.highlightLayers.length; index++) {
  18187. if (this.highlightLayers[index].name === name) {
  18188. return this.highlightLayers[index];
  18189. }
  18190. }
  18191. return null;
  18192. };
  18193. Object.defineProperty(Scene.prototype, "uid", {
  18194. /**
  18195. * Return a unique id as a string which can serve as an identifier for the scene
  18196. */
  18197. get: function () {
  18198. if (!this._uid) {
  18199. this._uid = BABYLON.Tools.RandomId();
  18200. }
  18201. return this._uid;
  18202. },
  18203. enumerable: true,
  18204. configurable: true
  18205. });
  18206. /**
  18207. * Add an externaly attached data from its key.
  18208. * This method call will fail and return false, if such key already exists.
  18209. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18210. * @param key the unique key that identifies the data
  18211. * @param data the data object to associate to the key for this Engine instance
  18212. * @return true if no such key were already present and the data was added successfully, false otherwise
  18213. */
  18214. Scene.prototype.addExternalData = function (key, data) {
  18215. if (!this._externalData) {
  18216. this._externalData = new BABYLON.StringDictionary();
  18217. }
  18218. return this._externalData.add(key, data);
  18219. };
  18220. /**
  18221. * Get an externaly attached data from its key
  18222. * @param key the unique key that identifies the data
  18223. * @return the associated data, if present (can be null), or undefined if not present
  18224. */
  18225. Scene.prototype.getExternalData = function (key) {
  18226. if (!this._externalData) {
  18227. return null;
  18228. }
  18229. return this._externalData.get(key);
  18230. };
  18231. /**
  18232. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18233. * @param key the unique key that identifies the data
  18234. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18235. * @return the associated data, can be null if the factory returned null.
  18236. */
  18237. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18238. if (!this._externalData) {
  18239. this._externalData = new BABYLON.StringDictionary();
  18240. }
  18241. return this._externalData.getOrAddWithFactory(key, factory);
  18242. };
  18243. /**
  18244. * Remove an externaly attached data from the Engine instance
  18245. * @param key the unique key that identifies the data
  18246. * @return true if the data was successfully removed, false if it doesn't exist
  18247. */
  18248. Scene.prototype.removeExternalData = function (key) {
  18249. return this._externalData.remove(key);
  18250. };
  18251. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18252. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18253. var material = subMesh.getMaterial();
  18254. if (mesh.showSubMeshesBoundingBox) {
  18255. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18256. }
  18257. if (material) {
  18258. // Render targets
  18259. if (material.getRenderTargetTextures) {
  18260. if (this._processedMaterials.indexOf(material) === -1) {
  18261. this._processedMaterials.push(material);
  18262. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18263. }
  18264. }
  18265. // Dispatch
  18266. this._activeIndices.addCount(subMesh.indexCount, false);
  18267. this._renderingManager.dispatch(subMesh);
  18268. }
  18269. }
  18270. };
  18271. Scene.prototype._isInIntermediateRendering = function () {
  18272. return this._intermediateRendering;
  18273. };
  18274. Scene.prototype._evaluateActiveMeshes = function () {
  18275. this.activeCamera._activeMeshes.reset();
  18276. this._activeMeshes.reset();
  18277. this._renderingManager.reset();
  18278. this._processedMaterials.reset();
  18279. this._activeParticleSystems.reset();
  18280. this._activeSkeletons.reset();
  18281. this._softwareSkinnedMeshes.reset();
  18282. if (this._boundingBoxRenderer) {
  18283. this._boundingBoxRenderer.reset();
  18284. }
  18285. // Meshes
  18286. var meshes;
  18287. var len;
  18288. if (this._selectionOctree) {
  18289. var selection = this._selectionOctree.select(this._frustumPlanes);
  18290. meshes = selection.data;
  18291. len = selection.length;
  18292. }
  18293. else {
  18294. len = this.meshes.length;
  18295. meshes = this.meshes;
  18296. }
  18297. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18298. var mesh = meshes[meshIndex];
  18299. if (mesh.isBlocked) {
  18300. continue;
  18301. }
  18302. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18303. if (!mesh.isReady() || !mesh.isEnabled()) {
  18304. continue;
  18305. }
  18306. mesh.computeWorldMatrix();
  18307. // Intersections
  18308. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18309. this._meshesForIntersections.pushNoDuplicate(mesh);
  18310. }
  18311. // Switch to current LOD
  18312. var meshLOD = mesh.getLOD(this.activeCamera);
  18313. if (!meshLOD) {
  18314. continue;
  18315. }
  18316. mesh._preActivate();
  18317. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18318. this._activeMeshes.push(mesh);
  18319. this.activeCamera._activeMeshes.push(mesh);
  18320. mesh._activate(this._renderId);
  18321. if (meshLOD !== mesh) {
  18322. meshLOD._activate(this._renderId);
  18323. }
  18324. this._activeMesh(mesh, meshLOD);
  18325. }
  18326. }
  18327. // Particle systems
  18328. this._particlesDuration.beginMonitoring();
  18329. var beforeParticlesDate = BABYLON.Tools.Now;
  18330. if (this.particlesEnabled) {
  18331. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18332. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18333. var particleSystem = this.particleSystems[particleIndex];
  18334. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18335. continue;
  18336. }
  18337. var emitter = particleSystem.emitter;
  18338. if (!emitter.position || emitter.isEnabled()) {
  18339. this._activeParticleSystems.push(particleSystem);
  18340. particleSystem.animate();
  18341. this._renderingManager.dispatchParticles(particleSystem);
  18342. }
  18343. }
  18344. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18345. }
  18346. this._particlesDuration.endMonitoring(false);
  18347. };
  18348. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18349. if (mesh.skeleton && this.skeletonsEnabled) {
  18350. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18351. mesh.skeleton.prepare();
  18352. }
  18353. if (!mesh.computeBonesUsingShaders) {
  18354. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18355. }
  18356. }
  18357. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18358. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18359. }
  18360. if (mesh && mesh.subMeshes) {
  18361. // Submeshes Octrees
  18362. var len;
  18363. var subMeshes;
  18364. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18365. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18366. len = intersections.length;
  18367. subMeshes = intersections.data;
  18368. }
  18369. else {
  18370. subMeshes = mesh.subMeshes;
  18371. len = subMeshes.length;
  18372. }
  18373. for (var subIndex = 0; subIndex < len; subIndex++) {
  18374. var subMesh = subMeshes[subIndex];
  18375. this._evaluateSubMesh(subMesh, mesh);
  18376. }
  18377. }
  18378. };
  18379. Scene.prototype.updateTransformMatrix = function (force) {
  18380. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18381. };
  18382. Scene.prototype._renderForCamera = function (camera) {
  18383. var engine = this._engine;
  18384. var startTime = BABYLON.Tools.Now;
  18385. this.activeCamera = camera;
  18386. if (!this.activeCamera)
  18387. throw new Error("Active camera not set");
  18388. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18389. // Viewport
  18390. engine.setViewport(this.activeCamera.viewport);
  18391. // Camera
  18392. this.resetCachedMaterial();
  18393. this._renderId++;
  18394. this.updateTransformMatrix();
  18395. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18396. // Meshes
  18397. this._evaluateActiveMeshesDuration.beginMonitoring();
  18398. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18399. this._evaluateActiveMeshes();
  18400. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18401. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18402. // Software skinning
  18403. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18404. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18405. mesh.applySkeleton(mesh.skeleton);
  18406. }
  18407. // Render targets
  18408. this._renderTargetsDuration.beginMonitoring();
  18409. var needsRestoreFrameBuffer = false;
  18410. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18411. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18412. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18413. }
  18414. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18415. this._intermediateRendering = true;
  18416. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18417. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18418. var renderTarget = this._renderTargets.data[renderIndex];
  18419. if (renderTarget._shouldRender()) {
  18420. this._renderId++;
  18421. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18422. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18423. }
  18424. }
  18425. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18426. this._intermediateRendering = false;
  18427. this._renderId++;
  18428. needsRestoreFrameBuffer = true; // Restore back buffer
  18429. }
  18430. // Render HighlightLayer Texture
  18431. var stencilState = this._engine.getStencilBuffer();
  18432. var renderhighlights = false;
  18433. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18434. this._intermediateRendering = true;
  18435. for (var i = 0; i < this.highlightLayers.length; i++) {
  18436. var highlightLayer = this.highlightLayers[i];
  18437. if (highlightLayer.shouldRender() &&
  18438. (!highlightLayer.camera ||
  18439. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18440. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18441. renderhighlights = true;
  18442. var renderTarget = highlightLayer._mainTexture;
  18443. if (renderTarget._shouldRender()) {
  18444. this._renderId++;
  18445. renderTarget.render(false, false);
  18446. needsRestoreFrameBuffer = true;
  18447. }
  18448. }
  18449. }
  18450. this._intermediateRendering = false;
  18451. this._renderId++;
  18452. }
  18453. if (needsRestoreFrameBuffer) {
  18454. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18455. }
  18456. this._renderTargetsDuration.endMonitoring(false);
  18457. // Prepare Frame
  18458. this.postProcessManager._prepareFrame();
  18459. this._renderDuration.beginMonitoring();
  18460. // Backgrounds
  18461. var layerIndex;
  18462. var layer;
  18463. if (this.layers.length) {
  18464. engine.setDepthBuffer(false);
  18465. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18466. layer = this.layers[layerIndex];
  18467. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18468. layer.render();
  18469. }
  18470. }
  18471. engine.setDepthBuffer(true);
  18472. }
  18473. // Render
  18474. BABYLON.Tools.StartPerformanceCounter("Main render");
  18475. // Activate HighlightLayer stencil
  18476. if (renderhighlights) {
  18477. this._engine.setStencilBuffer(true);
  18478. }
  18479. this._renderingManager.render(null, null, true, true);
  18480. // Restore HighlightLayer stencil
  18481. if (renderhighlights) {
  18482. this._engine.setStencilBuffer(stencilState);
  18483. }
  18484. BABYLON.Tools.EndPerformanceCounter("Main render");
  18485. // Bounding boxes
  18486. if (this._boundingBoxRenderer) {
  18487. this._boundingBoxRenderer.render();
  18488. }
  18489. // Lens flares
  18490. if (this.lensFlaresEnabled) {
  18491. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18492. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18493. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18494. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18495. lensFlareSystem.render();
  18496. }
  18497. }
  18498. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18499. }
  18500. // Foregrounds
  18501. if (this.layers.length) {
  18502. engine.setDepthBuffer(false);
  18503. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18504. layer = this.layers[layerIndex];
  18505. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18506. layer.render();
  18507. }
  18508. }
  18509. engine.setDepthBuffer(true);
  18510. }
  18511. // Highlight Layer
  18512. if (renderhighlights) {
  18513. engine.setDepthBuffer(false);
  18514. for (var i = 0; i < this.highlightLayers.length; i++) {
  18515. if (this.highlightLayers[i].shouldRender()) {
  18516. this.highlightLayers[i].render();
  18517. }
  18518. }
  18519. engine.setDepthBuffer(true);
  18520. }
  18521. this._renderDuration.endMonitoring(false);
  18522. // Finalize frame
  18523. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18524. // Update camera
  18525. this.activeCamera._updateFromScene();
  18526. // Reset some special arrays
  18527. this._renderTargets.reset();
  18528. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18529. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18530. };
  18531. Scene.prototype._processSubCameras = function (camera) {
  18532. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18533. this._renderForCamera(camera);
  18534. return;
  18535. }
  18536. // rig cameras
  18537. for (var index = 0; index < camera._rigCameras.length; index++) {
  18538. this._renderForCamera(camera._rigCameras[index]);
  18539. }
  18540. this.activeCamera = camera;
  18541. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18542. // Update camera
  18543. this.activeCamera._updateFromScene();
  18544. };
  18545. Scene.prototype._checkIntersections = function () {
  18546. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18547. var sourceMesh = this._meshesForIntersections.data[index];
  18548. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18549. var action = sourceMesh.actionManager.actions[actionIndex];
  18550. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18551. var parameters = action.getTriggerParameter();
  18552. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18553. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18554. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18555. if (areIntersecting && currentIntersectionInProgress === -1) {
  18556. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18557. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18558. sourceMesh._intersectionsInProgress.push(otherMesh);
  18559. }
  18560. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18561. sourceMesh._intersectionsInProgress.push(otherMesh);
  18562. }
  18563. }
  18564. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18565. //They intersected, and now they don't.
  18566. //is this trigger an exit trigger? execute an event.
  18567. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18568. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18569. }
  18570. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18571. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18572. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18573. }
  18574. }
  18575. }
  18576. }
  18577. }
  18578. };
  18579. Scene.prototype.render = function () {
  18580. if (this.isDisposed) {
  18581. return;
  18582. }
  18583. this._lastFrameDuration.beginMonitoring();
  18584. this._particlesDuration.fetchNewFrame();
  18585. this._spritesDuration.fetchNewFrame();
  18586. this._activeParticles.fetchNewFrame();
  18587. this._renderDuration.fetchNewFrame();
  18588. this._renderTargetsDuration.fetchNewFrame();
  18589. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18590. this._totalVertices.fetchNewFrame();
  18591. this._activeIndices.fetchNewFrame();
  18592. this._activeBones.fetchNewFrame();
  18593. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18594. this._meshesForIntersections.reset();
  18595. this.resetCachedMaterial();
  18596. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18597. // Actions
  18598. if (this.actionManager) {
  18599. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18600. }
  18601. //Simplification Queue
  18602. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18603. this.simplificationQueue.executeNext();
  18604. }
  18605. if (this._engine.isDeterministicLockStep()) {
  18606. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18607. var defaultTimeStep = (60.0 / 1000.0);
  18608. if (this._physicsEngine) {
  18609. defaultTimeStep = this._physicsEngine.getTimeStep();
  18610. }
  18611. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18612. this._timeAccumulator += deltaTime;
  18613. // compute the amount of fixed steps we should have taken since the last step
  18614. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18615. internalSteps = Math.min(internalSteps, maxSubSteps);
  18616. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18617. this.onBeforeStepObservable.notifyObservers(this);
  18618. // Animations
  18619. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18620. this._animate();
  18621. // Physics
  18622. if (this._physicsEngine) {
  18623. BABYLON.Tools.StartPerformanceCounter("Physics");
  18624. this._physicsEngine._step(defaultTimeStep);
  18625. BABYLON.Tools.EndPerformanceCounter("Physics");
  18626. }
  18627. this._timeAccumulator -= defaultTimeStep;
  18628. this.onAfterStepObservable.notifyObservers(this);
  18629. this._currentStepId++;
  18630. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18631. // Q: can this be optimized by putting some code in the afterStep callback?
  18632. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18633. // would return incorrect positions for internal stepIds (non-rendered steps)
  18634. this._evaluateActiveMeshes();
  18635. }
  18636. }
  18637. }
  18638. else {
  18639. // Animations
  18640. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18641. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18642. this._animate();
  18643. // Physics
  18644. if (this._physicsEngine) {
  18645. BABYLON.Tools.StartPerformanceCounter("Physics");
  18646. this._physicsEngine._step(deltaTime / 1000.0);
  18647. BABYLON.Tools.EndPerformanceCounter("Physics");
  18648. }
  18649. }
  18650. // Before render
  18651. this.onBeforeRenderObservable.notifyObservers(this);
  18652. // Customs render targets
  18653. this._renderTargetsDuration.beginMonitoring();
  18654. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18655. var engine = this.getEngine();
  18656. var currentActiveCamera = this.activeCamera;
  18657. if (this.renderTargetsEnabled) {
  18658. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18659. this._intermediateRendering = true;
  18660. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18661. var renderTarget = this.customRenderTargets[customIndex];
  18662. if (renderTarget._shouldRender()) {
  18663. this._renderId++;
  18664. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18665. if (!this.activeCamera)
  18666. throw new Error("Active camera not set");
  18667. // Viewport
  18668. engine.setViewport(this.activeCamera.viewport);
  18669. // Camera
  18670. this.updateTransformMatrix();
  18671. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18672. }
  18673. }
  18674. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18675. this._intermediateRendering = false;
  18676. this._renderId++;
  18677. }
  18678. // Restore back buffer
  18679. if (this.customRenderTargets.length > 0) {
  18680. engine.restoreDefaultFramebuffer();
  18681. }
  18682. this._renderTargetsDuration.endMonitoring();
  18683. this.activeCamera = currentActiveCamera;
  18684. // Procedural textures
  18685. if (this.proceduralTexturesEnabled) {
  18686. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18687. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18688. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18689. if (proceduralTexture._shouldRender()) {
  18690. proceduralTexture.render();
  18691. }
  18692. }
  18693. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18694. }
  18695. // Clear
  18696. if (this.autoClearDepthAndStencil || this.autoClear) {
  18697. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18698. }
  18699. // Shadows
  18700. if (this.shadowsEnabled) {
  18701. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18702. var light = this.lights[lightIndex];
  18703. var shadowGenerator = light.getShadowGenerator();
  18704. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18705. var shadowMap = shadowGenerator.getShadowMap();
  18706. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18707. this._renderTargets.push(shadowMap);
  18708. }
  18709. }
  18710. }
  18711. }
  18712. // Depth renderer
  18713. if (this._depthRenderer) {
  18714. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18715. }
  18716. // Geometry renderer
  18717. if (this._geometryBufferRenderer) {
  18718. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18719. }
  18720. // RenderPipeline
  18721. if (this._postProcessRenderPipelineManager) {
  18722. this._postProcessRenderPipelineManager.update();
  18723. }
  18724. // Multi-cameras?
  18725. if (this.activeCameras.length > 0) {
  18726. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18727. if (cameraIndex > 0) {
  18728. this._engine.clear(null, false, true, true);
  18729. }
  18730. this._processSubCameras(this.activeCameras[cameraIndex]);
  18731. }
  18732. }
  18733. else {
  18734. if (!this.activeCamera) {
  18735. throw new Error("No camera defined");
  18736. }
  18737. this._processSubCameras(this.activeCamera);
  18738. }
  18739. // Intersection checks
  18740. this._checkIntersections();
  18741. // Update the audio listener attached to the camera
  18742. if (BABYLON.AudioEngine) {
  18743. this._updateAudioParameters();
  18744. }
  18745. // After render
  18746. if (this.afterRender) {
  18747. this.afterRender();
  18748. }
  18749. this.onAfterRenderObservable.notifyObservers(this);
  18750. // Cleaning
  18751. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18752. this._toBeDisposed.data[index].dispose();
  18753. this._toBeDisposed[index] = null;
  18754. }
  18755. this._toBeDisposed.reset();
  18756. if (this.dumpNextRenderTargets) {
  18757. this.dumpNextRenderTargets = false;
  18758. }
  18759. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18760. this._lastFrameDuration.endMonitoring();
  18761. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18762. this._totalLightsCounter.addCount(this.lights.length, true);
  18763. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18764. this._totalTexturesCounter.addCount(this.textures.length, true);
  18765. this._activeBones.addCount(0, true);
  18766. this._activeIndices.addCount(0, true);
  18767. this._activeParticles.addCount(0, true);
  18768. };
  18769. Scene.prototype._updateAudioParameters = function () {
  18770. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18771. return;
  18772. }
  18773. var listeningCamera;
  18774. var audioEngine = BABYLON.Engine.audioEngine;
  18775. if (this.activeCameras.length > 0) {
  18776. listeningCamera = this.activeCameras[0];
  18777. }
  18778. else {
  18779. listeningCamera = this.activeCamera;
  18780. }
  18781. if (listeningCamera && audioEngine.canUseWebAudio) {
  18782. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18783. // for VR cameras
  18784. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18785. listeningCamera = listeningCamera.rigCameras[0];
  18786. }
  18787. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18788. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18789. cameraDirection.normalize();
  18790. // To avoid some errors on GearVR
  18791. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18792. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18793. }
  18794. var i;
  18795. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18796. var sound = this.mainSoundTrack.soundCollection[i];
  18797. if (sound.useCustomAttenuation) {
  18798. sound.updateDistanceFromListener();
  18799. }
  18800. }
  18801. for (i = 0; i < this.soundTracks.length; i++) {
  18802. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18803. sound = this.soundTracks[i].soundCollection[j];
  18804. if (sound.useCustomAttenuation) {
  18805. sound.updateDistanceFromListener();
  18806. }
  18807. }
  18808. }
  18809. }
  18810. };
  18811. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18812. // Audio
  18813. get: function () {
  18814. return this._audioEnabled;
  18815. },
  18816. set: function (value) {
  18817. this._audioEnabled = value;
  18818. if (BABYLON.AudioEngine) {
  18819. if (this._audioEnabled) {
  18820. this._enableAudio();
  18821. }
  18822. else {
  18823. this._disableAudio();
  18824. }
  18825. }
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. Scene.prototype._disableAudio = function () {
  18831. var i;
  18832. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18833. this.mainSoundTrack.soundCollection[i].pause();
  18834. }
  18835. for (i = 0; i < this.soundTracks.length; i++) {
  18836. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18837. this.soundTracks[i].soundCollection[j].pause();
  18838. }
  18839. }
  18840. };
  18841. Scene.prototype._enableAudio = function () {
  18842. var i;
  18843. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18844. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18845. this.mainSoundTrack.soundCollection[i].play();
  18846. }
  18847. }
  18848. for (i = 0; i < this.soundTracks.length; i++) {
  18849. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18850. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18851. this.soundTracks[i].soundCollection[j].play();
  18852. }
  18853. }
  18854. }
  18855. };
  18856. Object.defineProperty(Scene.prototype, "headphone", {
  18857. get: function () {
  18858. return this._headphone;
  18859. },
  18860. set: function (value) {
  18861. this._headphone = value;
  18862. if (BABYLON.AudioEngine) {
  18863. if (this._headphone) {
  18864. this._switchAudioModeForHeadphones();
  18865. }
  18866. else {
  18867. this._switchAudioModeForNormalSpeakers();
  18868. }
  18869. }
  18870. },
  18871. enumerable: true,
  18872. configurable: true
  18873. });
  18874. Scene.prototype._switchAudioModeForHeadphones = function () {
  18875. this.mainSoundTrack.switchPanningModelToHRTF();
  18876. for (var i = 0; i < this.soundTracks.length; i++) {
  18877. this.soundTracks[i].switchPanningModelToHRTF();
  18878. }
  18879. };
  18880. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18881. this.mainSoundTrack.switchPanningModelToEqualPower();
  18882. for (var i = 0; i < this.soundTracks.length; i++) {
  18883. this.soundTracks[i].switchPanningModelToEqualPower();
  18884. }
  18885. };
  18886. Scene.prototype.enableDepthRenderer = function () {
  18887. if (this._depthRenderer) {
  18888. return this._depthRenderer;
  18889. }
  18890. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18891. return this._depthRenderer;
  18892. };
  18893. Scene.prototype.disableDepthRenderer = function () {
  18894. if (!this._depthRenderer) {
  18895. return;
  18896. }
  18897. this._depthRenderer.dispose();
  18898. this._depthRenderer = null;
  18899. };
  18900. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18901. if (ratio === void 0) { ratio = 1; }
  18902. if (this._geometryBufferRenderer) {
  18903. return this._geometryBufferRenderer;
  18904. }
  18905. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18906. if (!this._geometryBufferRenderer.isSupported) {
  18907. this._geometryBufferRenderer = null;
  18908. }
  18909. return this._geometryBufferRenderer;
  18910. };
  18911. Scene.prototype.disableGeometryBufferRenderer = function () {
  18912. if (!this._geometryBufferRenderer) {
  18913. return;
  18914. }
  18915. this._geometryBufferRenderer.dispose();
  18916. this._geometryBufferRenderer = null;
  18917. };
  18918. Scene.prototype.freezeMaterials = function () {
  18919. for (var i = 0; i < this.materials.length; i++) {
  18920. this.materials[i].freeze();
  18921. }
  18922. };
  18923. Scene.prototype.unfreezeMaterials = function () {
  18924. for (var i = 0; i < this.materials.length; i++) {
  18925. this.materials[i].unfreeze();
  18926. }
  18927. };
  18928. Scene.prototype.dispose = function () {
  18929. this.beforeRender = null;
  18930. this.afterRender = null;
  18931. this.skeletons = [];
  18932. this.morphTargetManagers = [];
  18933. this.importedMeshesFiles = new Array();
  18934. this.resetCachedMaterial();
  18935. if (this._depthRenderer) {
  18936. this._depthRenderer.dispose();
  18937. }
  18938. if (this._gamepadManager) {
  18939. this._gamepadManager.dispose();
  18940. this._gamepadManager = null;
  18941. }
  18942. // Smart arrays
  18943. if (this.activeCamera) {
  18944. this.activeCamera._activeMeshes.dispose();
  18945. this.activeCamera = null;
  18946. }
  18947. this._activeMeshes.dispose();
  18948. this._renderingManager.dispose();
  18949. this._processedMaterials.dispose();
  18950. this._activeParticleSystems.dispose();
  18951. this._activeSkeletons.dispose();
  18952. this._softwareSkinnedMeshes.dispose();
  18953. this._renderTargets.dispose();
  18954. if (this._boundingBoxRenderer) {
  18955. this._boundingBoxRenderer.dispose();
  18956. }
  18957. this._meshesForIntersections.dispose();
  18958. this._toBeDisposed.dispose();
  18959. // Debug layer
  18960. if (this._debugLayer) {
  18961. this._debugLayer.hide();
  18962. }
  18963. // Events
  18964. this.onDisposeObservable.notifyObservers(this);
  18965. this.onDisposeObservable.clear();
  18966. this.onBeforeRenderObservable.clear();
  18967. this.onAfterRenderObservable.clear();
  18968. this.detachControl();
  18969. // Release sounds & sounds tracks
  18970. if (BABYLON.AudioEngine) {
  18971. this.disposeSounds();
  18972. }
  18973. // VR Helper
  18974. if (this.VRHelper) {
  18975. this.VRHelper.dispose();
  18976. }
  18977. // Detach cameras
  18978. var canvas = this._engine.getRenderingCanvas();
  18979. var index;
  18980. for (index = 0; index < this.cameras.length; index++) {
  18981. this.cameras[index].detachControl(canvas);
  18982. }
  18983. // Release lights
  18984. while (this.lights.length) {
  18985. this.lights[0].dispose();
  18986. }
  18987. // Release meshes
  18988. while (this.meshes.length) {
  18989. this.meshes[0].dispose(true);
  18990. }
  18991. // Release cameras
  18992. while (this.cameras.length) {
  18993. this.cameras[0].dispose();
  18994. }
  18995. // Release materials
  18996. if (this.defaultMaterial) {
  18997. this.defaultMaterial.dispose();
  18998. }
  18999. while (this.multiMaterials.length) {
  19000. this.multiMaterials[0].dispose();
  19001. }
  19002. while (this.materials.length) {
  19003. this.materials[0].dispose();
  19004. }
  19005. // Release particles
  19006. while (this.particleSystems.length) {
  19007. this.particleSystems[0].dispose();
  19008. }
  19009. // Release sprites
  19010. while (this.spriteManagers.length) {
  19011. this.spriteManagers[0].dispose();
  19012. }
  19013. // Release postProcesses
  19014. while (this.postProcesses.length) {
  19015. this.postProcesses[0].dispose();
  19016. }
  19017. // Release layers
  19018. while (this.layers.length) {
  19019. this.layers[0].dispose();
  19020. }
  19021. while (this.highlightLayers.length) {
  19022. this.highlightLayers[0].dispose();
  19023. }
  19024. // Release textures
  19025. while (this.textures.length) {
  19026. this.textures[0].dispose();
  19027. }
  19028. // Release UBO
  19029. this._sceneUbo.dispose();
  19030. // Post-processes
  19031. this.postProcessManager.dispose();
  19032. // Physics
  19033. if (this._physicsEngine) {
  19034. this.disablePhysicsEngine();
  19035. }
  19036. // Remove from engine
  19037. index = this._engine.scenes.indexOf(this);
  19038. if (index > -1) {
  19039. this._engine.scenes.splice(index, 1);
  19040. }
  19041. this._engine.wipeCaches();
  19042. this._engine = null;
  19043. this.defaultMaterial = null;
  19044. this.multiMaterials = null;
  19045. this.materials = null;
  19046. };
  19047. Object.defineProperty(Scene.prototype, "isDisposed", {
  19048. get: function () {
  19049. return !this._engine;
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. // Release sounds & sounds tracks
  19055. Scene.prototype.disposeSounds = function () {
  19056. this.mainSoundTrack.dispose();
  19057. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19058. this.soundTracks[scIndex].dispose();
  19059. }
  19060. };
  19061. // Octrees
  19062. Scene.prototype.getWorldExtends = function () {
  19063. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19064. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19065. for (var index = 0; index < this.meshes.length; index++) {
  19066. var mesh = this.meshes[index];
  19067. mesh.computeWorldMatrix(true);
  19068. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19069. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19070. BABYLON.Tools.CheckExtends(minBox, min, max);
  19071. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19072. }
  19073. return {
  19074. min: min,
  19075. max: max
  19076. };
  19077. };
  19078. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19079. if (maxCapacity === void 0) { maxCapacity = 64; }
  19080. if (maxDepth === void 0) { maxDepth = 2; }
  19081. if (!this._selectionOctree) {
  19082. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19083. }
  19084. var worldExtends = this.getWorldExtends();
  19085. // Update octree
  19086. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19087. return this._selectionOctree;
  19088. };
  19089. // Picking
  19090. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19091. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19092. var engine = this._engine;
  19093. if (!camera) {
  19094. if (!this.activeCamera)
  19095. throw new Error("Active camera not set");
  19096. camera = this.activeCamera;
  19097. }
  19098. var cameraViewport = camera.viewport;
  19099. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19100. // Moving coordinates to local viewport world
  19101. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19102. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19103. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19104. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19105. };
  19106. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19107. if (!BABYLON.PickingInfo) {
  19108. return null;
  19109. }
  19110. var engine = this._engine;
  19111. if (!camera) {
  19112. if (!this.activeCamera)
  19113. throw new Error("Active camera not set");
  19114. camera = this.activeCamera;
  19115. }
  19116. var cameraViewport = camera.viewport;
  19117. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19118. var identity = BABYLON.Matrix.Identity();
  19119. // Moving coordinates to local viewport world
  19120. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19121. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19122. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19123. };
  19124. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19125. if (!BABYLON.PickingInfo) {
  19126. return null;
  19127. }
  19128. var pickingInfo = null;
  19129. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19130. var mesh = this.meshes[meshIndex];
  19131. if (predicate) {
  19132. if (!predicate(mesh)) {
  19133. continue;
  19134. }
  19135. }
  19136. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19137. continue;
  19138. }
  19139. var world = mesh.getWorldMatrix();
  19140. var ray = rayFunction(world);
  19141. var result = mesh.intersects(ray, fastCheck);
  19142. if (!result || !result.hit)
  19143. continue;
  19144. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19145. continue;
  19146. pickingInfo = result;
  19147. if (fastCheck) {
  19148. break;
  19149. }
  19150. }
  19151. return pickingInfo || new BABYLON.PickingInfo();
  19152. };
  19153. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19154. if (!BABYLON.PickingInfo) {
  19155. return null;
  19156. }
  19157. var pickingInfos = new Array();
  19158. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19159. var mesh = this.meshes[meshIndex];
  19160. if (predicate) {
  19161. if (!predicate(mesh)) {
  19162. continue;
  19163. }
  19164. }
  19165. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19166. continue;
  19167. }
  19168. var world = mesh.getWorldMatrix();
  19169. var ray = rayFunction(world);
  19170. var result = mesh.intersects(ray, false);
  19171. if (!result || !result.hit)
  19172. continue;
  19173. pickingInfos.push(result);
  19174. }
  19175. return pickingInfos;
  19176. };
  19177. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19178. if (!BABYLON.PickingInfo) {
  19179. return null;
  19180. }
  19181. var pickingInfo = null;
  19182. camera = camera || this.activeCamera;
  19183. if (this.spriteManagers.length > 0) {
  19184. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19185. var spriteManager = this.spriteManagers[spriteIndex];
  19186. if (!spriteManager.isPickable) {
  19187. continue;
  19188. }
  19189. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19190. if (!result || !result.hit)
  19191. continue;
  19192. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19193. continue;
  19194. pickingInfo = result;
  19195. if (fastCheck) {
  19196. break;
  19197. }
  19198. }
  19199. }
  19200. return pickingInfo || new BABYLON.PickingInfo();
  19201. };
  19202. /** Launch a ray to try to pick a mesh in the scene
  19203. * @param x position on screen
  19204. * @param y position on screen
  19205. * @param 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
  19206. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19207. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19208. */
  19209. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19210. var _this = this;
  19211. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19212. };
  19213. /** Launch a ray to try to pick a sprite in the scene
  19214. * @param x position on screen
  19215. * @param y position on screen
  19216. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  19217. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19218. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19219. */
  19220. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19221. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19222. };
  19223. /** Use the given ray to pick a mesh in the scene
  19224. * @param ray The ray to use to pick meshes
  19225. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  19226. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19227. */
  19228. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19229. var _this = this;
  19230. return this._internalPick(function (world) {
  19231. if (!_this._pickWithRayInverseMatrix) {
  19232. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19233. }
  19234. world.invertToRef(_this._pickWithRayInverseMatrix);
  19235. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19236. }, predicate, fastCheck);
  19237. };
  19238. /**
  19239. * Launch a ray to try to pick a mesh in the scene
  19240. * @param x X position on screen
  19241. * @param y Y position on screen
  19242. * @param 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
  19243. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19244. */
  19245. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19246. var _this = this;
  19247. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19248. };
  19249. /**
  19250. * Launch a ray to try to pick a mesh in the scene
  19251. * @param ray Ray to use
  19252. * @param 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
  19253. */
  19254. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19255. var _this = this;
  19256. return this._internalMultiPick(function (world) {
  19257. if (!_this._pickWithRayInverseMatrix) {
  19258. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19259. }
  19260. world.invertToRef(_this._pickWithRayInverseMatrix);
  19261. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19262. }, predicate);
  19263. };
  19264. Scene.prototype.setPointerOverMesh = function (mesh) {
  19265. if (this._pointerOverMesh === mesh) {
  19266. return;
  19267. }
  19268. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19269. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19270. }
  19271. this._pointerOverMesh = mesh;
  19272. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19273. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19274. }
  19275. };
  19276. Scene.prototype.getPointerOverMesh = function () {
  19277. return this._pointerOverMesh;
  19278. };
  19279. Scene.prototype.setPointerOverSprite = function (sprite) {
  19280. if (this._pointerOverSprite === sprite) {
  19281. return;
  19282. }
  19283. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19284. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19285. }
  19286. this._pointerOverSprite = sprite;
  19287. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19288. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19289. }
  19290. };
  19291. Scene.prototype.getPointerOverSprite = function () {
  19292. return this._pointerOverSprite;
  19293. };
  19294. // Physics
  19295. Scene.prototype.getPhysicsEngine = function () {
  19296. return this._physicsEngine;
  19297. };
  19298. /**
  19299. * Enables physics to the current scene
  19300. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19301. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19302. * @return {boolean} was the physics engine initialized
  19303. */
  19304. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19305. if (this._physicsEngine) {
  19306. return true;
  19307. }
  19308. try {
  19309. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19310. return true;
  19311. }
  19312. catch (e) {
  19313. BABYLON.Tools.Error(e.message);
  19314. return false;
  19315. }
  19316. };
  19317. Scene.prototype.disablePhysicsEngine = function () {
  19318. if (!this._physicsEngine) {
  19319. return;
  19320. }
  19321. this._physicsEngine.dispose();
  19322. this._physicsEngine = undefined;
  19323. };
  19324. Scene.prototype.isPhysicsEnabled = function () {
  19325. return this._physicsEngine !== undefined;
  19326. };
  19327. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19328. var mesh = compound.parts[0].mesh;
  19329. mesh.physicsImpostor.dispose();
  19330. mesh.physicsImpostor = null;
  19331. };
  19332. // Misc.
  19333. Scene.prototype._rebuildGeometries = function () {
  19334. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19335. var geometry = _a[_i];
  19336. geometry._rebuild();
  19337. }
  19338. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19339. var mesh = _c[_b];
  19340. mesh._rebuild();
  19341. }
  19342. if (this.postProcessManager) {
  19343. this.postProcessManager._rebuild();
  19344. }
  19345. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19346. var layer = _e[_d];
  19347. layer._rebuild();
  19348. }
  19349. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19350. var highlightLayer = _g[_f];
  19351. highlightLayer._rebuild();
  19352. }
  19353. };
  19354. Scene.prototype._rebuildTextures = function () {
  19355. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19356. var texture = _a[_i];
  19357. texture._rebuild();
  19358. }
  19359. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19360. };
  19361. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19362. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19363. if (replace === void 0) { replace = false; }
  19364. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19365. // Dispose existing camera or light in replace mode.
  19366. if (replace) {
  19367. if (this.activeCamera) {
  19368. this.activeCamera.dispose();
  19369. this.activeCamera = null;
  19370. }
  19371. if (this.lights) {
  19372. for (var i = 0; i < this.lights.length; i++) {
  19373. this.lights[i].dispose();
  19374. }
  19375. }
  19376. }
  19377. // Light
  19378. if (this.lights.length === 0) {
  19379. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19380. }
  19381. // Camera
  19382. if (!this.activeCamera) {
  19383. var worldExtends = this.getWorldExtends();
  19384. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19385. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19386. var camera;
  19387. var radius = worldSize.length() * 1.5;
  19388. if (createArcRotateCamera) {
  19389. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19390. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19391. arcRotateCamera.wheelPrecision = 100 / radius;
  19392. camera = arcRotateCamera;
  19393. }
  19394. else {
  19395. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19396. freeCamera.setTarget(worldCenter);
  19397. camera = freeCamera;
  19398. }
  19399. camera.minZ = radius * 0.01;
  19400. camera.maxZ = radius * 100;
  19401. camera.speed = radius * 0.2;
  19402. this.activeCamera = camera;
  19403. if (attachCameraControls) {
  19404. camera.attachControl(this.getEngine().getRenderingCanvas());
  19405. }
  19406. }
  19407. };
  19408. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19409. if (pbr === void 0) { pbr = false; }
  19410. if (scale === void 0) { scale = 1000; }
  19411. if (blur === void 0) { blur = 0; }
  19412. if (environmentTexture) {
  19413. this.environmentTexture = environmentTexture;
  19414. }
  19415. if (!this.environmentTexture) {
  19416. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19417. return;
  19418. }
  19419. // Skybox
  19420. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19421. if (pbr) {
  19422. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19423. hdrSkyboxMaterial.backFaceCulling = false;
  19424. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19425. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19426. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19427. hdrSkyboxMaterial.disableLighting = true;
  19428. hdrSkyboxMaterial.twoSidedLighting = true;
  19429. hdrSkybox.infiniteDistance = true;
  19430. hdrSkybox.material = hdrSkyboxMaterial;
  19431. }
  19432. else {
  19433. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19434. skyboxMaterial.backFaceCulling = false;
  19435. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19436. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19437. skyboxMaterial.disableLighting = true;
  19438. hdrSkybox.infiniteDistance = true;
  19439. hdrSkybox.material = skyboxMaterial;
  19440. }
  19441. return hdrSkybox;
  19442. };
  19443. Scene.prototype.createDefaultVRExperience = function () {
  19444. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19445. };
  19446. // Tags
  19447. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19448. if (tagsQuery === undefined) {
  19449. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19450. return list;
  19451. }
  19452. var listByTags = [];
  19453. forEach = forEach || (function (item) { return; });
  19454. for (var i in list) {
  19455. var item = list[i];
  19456. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19457. listByTags.push(item);
  19458. forEach(item);
  19459. }
  19460. }
  19461. return listByTags;
  19462. };
  19463. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19464. return this._getByTags(this.meshes, tagsQuery, forEach);
  19465. };
  19466. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19467. return this._getByTags(this.cameras, tagsQuery, forEach);
  19468. };
  19469. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19470. return this._getByTags(this.lights, tagsQuery, forEach);
  19471. };
  19472. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19473. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19474. };
  19475. /**
  19476. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19477. * This allowed control for front to back rendering or reversly depending of the special needs.
  19478. *
  19479. * @param renderingGroupId The rendering group id corresponding to its index
  19480. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19481. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19482. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19483. */
  19484. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19485. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19486. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19487. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19488. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19489. };
  19490. /**
  19491. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19492. *
  19493. * @param renderingGroupId The rendering group id corresponding to its index
  19494. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19495. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19496. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19497. */
  19498. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19499. if (depth === void 0) { depth = true; }
  19500. if (stencil === void 0) { stencil = true; }
  19501. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19502. };
  19503. /**
  19504. * Will flag all materials as dirty to trigger new shader compilation
  19505. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19506. */
  19507. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19508. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19509. var material = _a[_i];
  19510. if (predicate && !predicate(material)) {
  19511. continue;
  19512. }
  19513. material.markAsDirty(flag);
  19514. }
  19515. };
  19516. // Statics
  19517. Scene._FOGMODE_NONE = 0;
  19518. Scene._FOGMODE_EXP = 1;
  19519. Scene._FOGMODE_EXP2 = 2;
  19520. Scene._FOGMODE_LINEAR = 3;
  19521. Scene.MinDeltaTime = 1.0;
  19522. Scene.MaxDeltaTime = 1000.0;
  19523. /** The distance in pixel that you have to move to prevent some events */
  19524. Scene.DragMovementThreshold = 10; // in pixels
  19525. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19526. Scene.LongPressDelay = 500; // in milliseconds
  19527. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19528. Scene.DoubleClickDelay = 300; // in milliseconds
  19529. /** If you need to check double click without raising a single click at first click, enable this flag */
  19530. Scene.ExclusiveDoubleClickMode = false;
  19531. return Scene;
  19532. }());
  19533. BABYLON.Scene = Scene;
  19534. })(BABYLON || (BABYLON = {}));
  19535. //# sourceMappingURL=babylon.scene.js.map
  19536. var BABYLON;
  19537. (function (BABYLON) {
  19538. var Buffer = (function () {
  19539. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19540. if (engine instanceof BABYLON.Mesh) {
  19541. this._engine = engine.getScene().getEngine();
  19542. }
  19543. else {
  19544. this._engine = engine;
  19545. }
  19546. this._updatable = updatable;
  19547. this._data = data;
  19548. this._strideSize = stride;
  19549. if (!postponeInternalCreation) {
  19550. this.create();
  19551. }
  19552. this._instanced = instanced;
  19553. this._instanceDivisor = instanced ? 1 : 0;
  19554. }
  19555. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19556. // a lot of these parameters are ignored as they are overriden by the buffer
  19557. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19558. };
  19559. // Properties
  19560. Buffer.prototype.isUpdatable = function () {
  19561. return this._updatable;
  19562. };
  19563. Buffer.prototype.getData = function () {
  19564. return this._data;
  19565. };
  19566. Buffer.prototype.getBuffer = function () {
  19567. return this._buffer;
  19568. };
  19569. Buffer.prototype.getStrideSize = function () {
  19570. return this._strideSize;
  19571. };
  19572. Buffer.prototype.getIsInstanced = function () {
  19573. return this._instanced;
  19574. };
  19575. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19576. get: function () {
  19577. return this._instanceDivisor;
  19578. },
  19579. set: function (value) {
  19580. this._instanceDivisor = value;
  19581. if (value == 0) {
  19582. this._instanced = false;
  19583. }
  19584. else {
  19585. this._instanced = true;
  19586. }
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. // Methods
  19592. Buffer.prototype.create = function (data) {
  19593. if (!data && this._buffer) {
  19594. return; // nothing to do
  19595. }
  19596. data = data || this._data;
  19597. if (!this._buffer) {
  19598. if (this._updatable) {
  19599. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19600. this._data = data;
  19601. }
  19602. else {
  19603. this._buffer = this._engine.createVertexBuffer(data);
  19604. }
  19605. }
  19606. else if (this._updatable) {
  19607. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19608. this._data = data;
  19609. }
  19610. };
  19611. Buffer.prototype._rebuild = function () {
  19612. this._buffer = null;
  19613. this.create(this._data);
  19614. };
  19615. Buffer.prototype.update = function (data) {
  19616. this.create(data);
  19617. };
  19618. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19619. if (!this._buffer) {
  19620. return;
  19621. }
  19622. if (this._updatable) {
  19623. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19624. this._data = null;
  19625. }
  19626. };
  19627. Buffer.prototype.dispose = function () {
  19628. if (!this._buffer) {
  19629. return;
  19630. }
  19631. if (this._engine._releaseBuffer(this._buffer)) {
  19632. this._buffer = null;
  19633. }
  19634. };
  19635. return Buffer;
  19636. }());
  19637. BABYLON.Buffer = Buffer;
  19638. })(BABYLON || (BABYLON = {}));
  19639. //# sourceMappingURL=babylon.buffer.js.map
  19640. var BABYLON;
  19641. (function (BABYLON) {
  19642. var VertexBuffer = (function () {
  19643. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19644. if (!stride) {
  19645. // Deduce stride from kind
  19646. switch (kind) {
  19647. case VertexBuffer.PositionKind:
  19648. stride = 3;
  19649. break;
  19650. case VertexBuffer.NormalKind:
  19651. stride = 3;
  19652. break;
  19653. case VertexBuffer.UVKind:
  19654. case VertexBuffer.UV2Kind:
  19655. case VertexBuffer.UV3Kind:
  19656. case VertexBuffer.UV4Kind:
  19657. case VertexBuffer.UV5Kind:
  19658. case VertexBuffer.UV6Kind:
  19659. stride = 2;
  19660. break;
  19661. case VertexBuffer.TangentKind:
  19662. case VertexBuffer.ColorKind:
  19663. stride = 4;
  19664. break;
  19665. case VertexBuffer.MatricesIndicesKind:
  19666. case VertexBuffer.MatricesIndicesExtraKind:
  19667. stride = 4;
  19668. break;
  19669. case VertexBuffer.MatricesWeightsKind:
  19670. case VertexBuffer.MatricesWeightsExtraKind:
  19671. stride = 4;
  19672. break;
  19673. }
  19674. }
  19675. if (data instanceof BABYLON.Buffer) {
  19676. if (!stride) {
  19677. stride = data.getStrideSize();
  19678. }
  19679. this._buffer = data;
  19680. this._ownsBuffer = false;
  19681. }
  19682. else {
  19683. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19684. this._ownsBuffer = true;
  19685. }
  19686. this._stride = stride;
  19687. this._offset = offset ? offset : 0;
  19688. this._size = size ? size : stride;
  19689. this._kind = kind;
  19690. }
  19691. VertexBuffer.prototype._rebuild = function () {
  19692. if (!this._buffer) {
  19693. return;
  19694. }
  19695. this._buffer._rebuild();
  19696. };
  19697. /**
  19698. * Returns the kind of the VertexBuffer (string).
  19699. */
  19700. VertexBuffer.prototype.getKind = function () {
  19701. return this._kind;
  19702. };
  19703. // Properties
  19704. /**
  19705. * Boolean : is the VertexBuffer updatable ?
  19706. */
  19707. VertexBuffer.prototype.isUpdatable = function () {
  19708. return this._buffer.isUpdatable();
  19709. };
  19710. /**
  19711. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19712. */
  19713. VertexBuffer.prototype.getData = function () {
  19714. return this._buffer.getData();
  19715. };
  19716. /**
  19717. * Returns the WebGLBuffer associated to the VertexBuffer.
  19718. */
  19719. VertexBuffer.prototype.getBuffer = function () {
  19720. return this._buffer.getBuffer();
  19721. };
  19722. /**
  19723. * Returns the stride of the VertexBuffer (integer).
  19724. */
  19725. VertexBuffer.prototype.getStrideSize = function () {
  19726. return this._stride;
  19727. };
  19728. /**
  19729. * Returns the offset (integer).
  19730. */
  19731. VertexBuffer.prototype.getOffset = function () {
  19732. return this._offset;
  19733. };
  19734. /**
  19735. * Returns the VertexBuffer total size (integer).
  19736. */
  19737. VertexBuffer.prototype.getSize = function () {
  19738. return this._size;
  19739. };
  19740. /**
  19741. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19742. */
  19743. VertexBuffer.prototype.getIsInstanced = function () {
  19744. return this._buffer.getIsInstanced();
  19745. };
  19746. /**
  19747. * Returns the instancing divisor, zero for non-instanced (integer).
  19748. */
  19749. VertexBuffer.prototype.getInstanceDivisor = function () {
  19750. return this._buffer.instanceDivisor;
  19751. };
  19752. // Methods
  19753. /**
  19754. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19755. * Returns the created WebGLBuffer.
  19756. */
  19757. VertexBuffer.prototype.create = function (data) {
  19758. return this._buffer.create(data);
  19759. };
  19760. /**
  19761. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19762. * Returns the updated WebGLBuffer.
  19763. */
  19764. VertexBuffer.prototype.update = function (data) {
  19765. return this._buffer.update(data);
  19766. };
  19767. /**
  19768. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19769. * Returns the directly updated WebGLBuffer.
  19770. */
  19771. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19772. return this._buffer.updateDirectly(data, offset);
  19773. };
  19774. /**
  19775. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19776. */
  19777. VertexBuffer.prototype.dispose = function () {
  19778. if (this._ownsBuffer) {
  19779. this._buffer.dispose();
  19780. }
  19781. };
  19782. Object.defineProperty(VertexBuffer, "PositionKind", {
  19783. get: function () {
  19784. return VertexBuffer._PositionKind;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(VertexBuffer, "NormalKind", {
  19790. get: function () {
  19791. return VertexBuffer._NormalKind;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. Object.defineProperty(VertexBuffer, "TangentKind", {
  19797. get: function () {
  19798. return VertexBuffer._TangentKind;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(VertexBuffer, "UVKind", {
  19804. get: function () {
  19805. return VertexBuffer._UVKind;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19811. get: function () {
  19812. return VertexBuffer._UV2Kind;
  19813. },
  19814. enumerable: true,
  19815. configurable: true
  19816. });
  19817. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19818. get: function () {
  19819. return VertexBuffer._UV3Kind;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19825. get: function () {
  19826. return VertexBuffer._UV4Kind;
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19832. get: function () {
  19833. return VertexBuffer._UV5Kind;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19839. get: function () {
  19840. return VertexBuffer._UV6Kind;
  19841. },
  19842. enumerable: true,
  19843. configurable: true
  19844. });
  19845. Object.defineProperty(VertexBuffer, "ColorKind", {
  19846. get: function () {
  19847. return VertexBuffer._ColorKind;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19853. get: function () {
  19854. return VertexBuffer._MatricesIndicesKind;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19860. get: function () {
  19861. return VertexBuffer._MatricesWeightsKind;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19867. get: function () {
  19868. return VertexBuffer._MatricesIndicesExtraKind;
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19874. get: function () {
  19875. return VertexBuffer._MatricesWeightsExtraKind;
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. // Enums
  19881. VertexBuffer._PositionKind = "position";
  19882. VertexBuffer._NormalKind = "normal";
  19883. VertexBuffer._TangentKind = "tangent";
  19884. VertexBuffer._UVKind = "uv";
  19885. VertexBuffer._UV2Kind = "uv2";
  19886. VertexBuffer._UV3Kind = "uv3";
  19887. VertexBuffer._UV4Kind = "uv4";
  19888. VertexBuffer._UV5Kind = "uv5";
  19889. VertexBuffer._UV6Kind = "uv6";
  19890. VertexBuffer._ColorKind = "color";
  19891. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19892. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19893. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19894. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19895. return VertexBuffer;
  19896. }());
  19897. BABYLON.VertexBuffer = VertexBuffer;
  19898. })(BABYLON || (BABYLON = {}));
  19899. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19900. var BABYLON;
  19901. (function (BABYLON) {
  19902. var InternalTexture = (function () {
  19903. function InternalTexture(engine, dataSource) {
  19904. this.onLoadedObservable = new BABYLON.Observable();
  19905. // Private
  19906. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  19907. this._references = 1;
  19908. this._engine = engine;
  19909. this._dataSource = dataSource;
  19910. this._webGLTexture = engine._createTexture();
  19911. }
  19912. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  19913. get: function () {
  19914. return this._dataSource;
  19915. },
  19916. enumerable: true,
  19917. configurable: true
  19918. });
  19919. InternalTexture.prototype.incrementReferences = function () {
  19920. this._references++;
  19921. };
  19922. InternalTexture.prototype.updateSize = function (width, height) {
  19923. this.width = width;
  19924. this.height = height;
  19925. this._size = width * height;
  19926. this.baseWidth = width;
  19927. this.baseHeight = height;
  19928. };
  19929. InternalTexture.prototype._rebuild = function () {
  19930. var _this = this;
  19931. var proxy;
  19932. this.isReady = false;
  19933. this._cachedCoordinatesMode = null;
  19934. this._cachedWrapU = null;
  19935. this._cachedWrapV = null;
  19936. this._cachedAnisotropicFilteringLevel = null;
  19937. switch (this._dataSource) {
  19938. case InternalTexture.DATASOURCE_TEMP:
  19939. return;
  19940. case InternalTexture.DATASOURCE_URL:
  19941. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  19942. _this.isReady = true;
  19943. }, null, this._buffer, null, this.format);
  19944. proxy._swapAndDie(this);
  19945. return;
  19946. case InternalTexture.DATASOURCE_RAW:
  19947. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  19948. proxy._swapAndDie(this);
  19949. this.isReady = true;
  19950. return;
  19951. case InternalTexture.DATASOURCE_DYNAMIC:
  19952. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  19953. proxy._swapAndDie(this);
  19954. // The engine will make sure to update content so no need to flag it as isReady = true
  19955. return;
  19956. case InternalTexture.DATASOURCE_RENDERTARGET:
  19957. var options = new BABYLON.RenderTargetCreationOptions();
  19958. options.generateDepthBuffer = this._generateDepthBuffer;
  19959. options.generateMipMaps = this.generateMipMaps;
  19960. options.generateStencilBuffer = this._generateStencilBuffer;
  19961. options.samplingMode = this.samplingMode;
  19962. options.type = this.type;
  19963. if (this.isCube) {
  19964. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  19965. }
  19966. else {
  19967. var size = {
  19968. width: this.width,
  19969. height: this.height
  19970. };
  19971. proxy = this._engine.createRenderTargetTexture(size, options);
  19972. }
  19973. proxy._swapAndDie(this);
  19974. this.isReady = true;
  19975. return;
  19976. case InternalTexture.DATASOURCE_CUBE:
  19977. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  19978. _this.isReady = true;
  19979. }, null, this.format, this._extension);
  19980. proxy._swapAndDie(this);
  19981. return;
  19982. case InternalTexture.DATASOURCE_CUBERAW:
  19983. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  19984. proxy._swapAndDie(this);
  19985. this.isReady = true;
  19986. return;
  19987. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  19988. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  19989. proxy._swapAndDie(_this);
  19990. _this.isReady = true;
  19991. }, null, this.format, this._extension);
  19992. return;
  19993. }
  19994. };
  19995. InternalTexture.prototype._swapAndDie = function (target) {
  19996. target._webGLTexture = this._webGLTexture;
  19997. if (this._framebuffer) {
  19998. target._framebuffer = this._framebuffer;
  19999. }
  20000. if (this._depthStencilBuffer) {
  20001. target._depthStencilBuffer = this._depthStencilBuffer;
  20002. }
  20003. if (this._lodTextureHigh) {
  20004. if (target._lodTextureHigh) {
  20005. target._lodTextureHigh.dispose();
  20006. }
  20007. target._lodTextureHigh = this._lodTextureHigh;
  20008. }
  20009. if (this._lodTextureMid) {
  20010. if (target._lodTextureMid) {
  20011. target._lodTextureMid.dispose();
  20012. }
  20013. target._lodTextureMid = this._lodTextureMid;
  20014. }
  20015. if (this._lodTextureLow) {
  20016. if (target._lodTextureLow) {
  20017. target._lodTextureLow.dispose();
  20018. }
  20019. target._lodTextureLow = this._lodTextureLow;
  20020. }
  20021. var cache = this._engine.getLoadedTexturesCache();
  20022. var index = cache.indexOf(this);
  20023. if (index !== -1) {
  20024. cache.splice(index, 1);
  20025. }
  20026. };
  20027. InternalTexture.prototype.dispose = function () {
  20028. if (!this._webGLTexture) {
  20029. return;
  20030. }
  20031. this._references--;
  20032. if (this._references === 0) {
  20033. this._engine._releaseTexture(this);
  20034. this._webGLTexture = null;
  20035. }
  20036. };
  20037. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20038. InternalTexture.DATASOURCE_URL = 1;
  20039. InternalTexture.DATASOURCE_TEMP = 2;
  20040. InternalTexture.DATASOURCE_RAW = 3;
  20041. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20042. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20043. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20044. InternalTexture.DATASOURCE_CUBE = 7;
  20045. InternalTexture.DATASOURCE_CUBERAW = 8;
  20046. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20047. return InternalTexture;
  20048. }());
  20049. BABYLON.InternalTexture = InternalTexture;
  20050. })(BABYLON || (BABYLON = {}));
  20051. //# sourceMappingURL=babylon.internalTexture.js.map
  20052. var BABYLON;
  20053. (function (BABYLON) {
  20054. var BaseTexture = (function () {
  20055. function BaseTexture(scene) {
  20056. this._hasAlpha = false;
  20057. this.getAlphaFromRGB = false;
  20058. this.level = 1;
  20059. this.coordinatesIndex = 0;
  20060. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20061. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20062. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20063. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20064. this.isCube = false;
  20065. this.gammaSpace = true;
  20066. this.invertZ = false;
  20067. this.lodLevelInAlpha = false;
  20068. this.lodGenerationOffset = 0.0;
  20069. this.lodGenerationScale = 0.8;
  20070. this.isRenderTarget = false;
  20071. this.animations = new Array();
  20072. /**
  20073. * An event triggered when the texture is disposed.
  20074. * @type {BABYLON.Observable}
  20075. */
  20076. this.onDisposeObservable = new BABYLON.Observable();
  20077. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20078. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20079. this._scene.textures.push(this);
  20080. this._uid = null;
  20081. }
  20082. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20083. get: function () {
  20084. return this._hasAlpha;
  20085. },
  20086. set: function (value) {
  20087. if (this._hasAlpha === value) {
  20088. return;
  20089. }
  20090. this._hasAlpha = value;
  20091. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20097. get: function () {
  20098. return this._coordinatesMode;
  20099. },
  20100. set: function (value) {
  20101. if (this._coordinatesMode === value) {
  20102. return;
  20103. }
  20104. this._coordinatesMode = value;
  20105. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20106. },
  20107. enumerable: true,
  20108. configurable: true
  20109. });
  20110. Object.defineProperty(BaseTexture.prototype, "uid", {
  20111. get: function () {
  20112. if (!this._uid) {
  20113. this._uid = BABYLON.Tools.RandomId();
  20114. }
  20115. return this._uid;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. BaseTexture.prototype.toString = function () {
  20121. return this.name;
  20122. };
  20123. BaseTexture.prototype.getClassName = function () {
  20124. return "BaseTexture";
  20125. };
  20126. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20127. set: function (callback) {
  20128. if (this._onDisposeObserver) {
  20129. this.onDisposeObservable.remove(this._onDisposeObserver);
  20130. }
  20131. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20137. get: function () {
  20138. return true;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. BaseTexture.prototype.getScene = function () {
  20144. return this._scene;
  20145. };
  20146. BaseTexture.prototype.getTextureMatrix = function () {
  20147. return null;
  20148. };
  20149. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20150. return null;
  20151. };
  20152. BaseTexture.prototype.getInternalTexture = function () {
  20153. return this._texture;
  20154. };
  20155. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20156. return !this.isBlocking || this.isReady();
  20157. };
  20158. BaseTexture.prototype.isReady = function () {
  20159. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20160. this.delayLoad();
  20161. return false;
  20162. }
  20163. if (this._texture) {
  20164. return this._texture.isReady;
  20165. }
  20166. return false;
  20167. };
  20168. BaseTexture.prototype.getSize = function () {
  20169. if (this._texture.width) {
  20170. return new BABYLON.Size(this._texture.width, this._texture.height);
  20171. }
  20172. if (this._texture._size) {
  20173. return new BABYLON.Size(this._texture._size, this._texture._size);
  20174. }
  20175. return BABYLON.Size.Zero();
  20176. };
  20177. BaseTexture.prototype.getBaseSize = function () {
  20178. if (!this.isReady() || !this._texture)
  20179. return BABYLON.Size.Zero();
  20180. if (this._texture._size) {
  20181. return new BABYLON.Size(this._texture._size, this._texture._size);
  20182. }
  20183. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20184. };
  20185. BaseTexture.prototype.scale = function (ratio) {
  20186. };
  20187. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20188. get: function () {
  20189. return false;
  20190. },
  20191. enumerable: true,
  20192. configurable: true
  20193. });
  20194. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20195. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20196. for (var index = 0; index < texturesCache.length; index++) {
  20197. var texturesCacheEntry = texturesCache[index];
  20198. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20199. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20200. texturesCacheEntry.incrementReferences();
  20201. return texturesCacheEntry;
  20202. }
  20203. }
  20204. }
  20205. return null;
  20206. };
  20207. BaseTexture.prototype._rebuild = function () {
  20208. };
  20209. BaseTexture.prototype.delayLoad = function () {
  20210. };
  20211. BaseTexture.prototype.clone = function () {
  20212. return null;
  20213. };
  20214. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20215. get: function () {
  20216. if (!this._texture) {
  20217. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20218. }
  20219. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20220. },
  20221. enumerable: true,
  20222. configurable: true
  20223. });
  20224. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20225. get: function () {
  20226. if (!this._texture) {
  20227. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20228. }
  20229. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20230. },
  20231. enumerable: true,
  20232. configurable: true
  20233. });
  20234. BaseTexture.prototype.readPixels = function (faceIndex) {
  20235. if (faceIndex === void 0) { faceIndex = 0; }
  20236. if (!this._texture) {
  20237. return null;
  20238. }
  20239. var size = this.getSize();
  20240. var engine = this.getScene().getEngine();
  20241. if (this._texture.isCube) {
  20242. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20243. }
  20244. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20245. };
  20246. BaseTexture.prototype.releaseInternalTexture = function () {
  20247. if (this._texture) {
  20248. this._texture.dispose();
  20249. this._texture = null;
  20250. }
  20251. };
  20252. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20253. get: function () {
  20254. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20255. return null;
  20256. }
  20257. if (!this._texture._sphericalPolynomial) {
  20258. this._texture._sphericalPolynomial =
  20259. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20260. }
  20261. return this._texture._sphericalPolynomial;
  20262. },
  20263. set: function (value) {
  20264. if (this._texture) {
  20265. this._texture._sphericalPolynomial = value;
  20266. }
  20267. },
  20268. enumerable: true,
  20269. configurable: true
  20270. });
  20271. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20272. get: function () {
  20273. if (this._texture) {
  20274. return this._texture._lodTextureHigh;
  20275. }
  20276. return null;
  20277. },
  20278. enumerable: true,
  20279. configurable: true
  20280. });
  20281. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20282. get: function () {
  20283. if (this._texture) {
  20284. return this._texture._lodTextureMid;
  20285. }
  20286. return null;
  20287. },
  20288. enumerable: true,
  20289. configurable: true
  20290. });
  20291. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20292. get: function () {
  20293. if (this._texture) {
  20294. return this._texture._lodTextureLow;
  20295. }
  20296. return null;
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. BaseTexture.prototype.dispose = function () {
  20302. // Animations
  20303. this.getScene().stopAnimation(this);
  20304. // Remove from scene
  20305. this._scene._removePendingData(this);
  20306. var index = this._scene.textures.indexOf(this);
  20307. if (index >= 0) {
  20308. this._scene.textures.splice(index, 1);
  20309. }
  20310. if (this._texture === undefined) {
  20311. return;
  20312. }
  20313. // Release
  20314. this.releaseInternalTexture();
  20315. // Callback
  20316. this.onDisposeObservable.notifyObservers(this);
  20317. this.onDisposeObservable.clear();
  20318. };
  20319. BaseTexture.prototype.serialize = function () {
  20320. if (!this.name) {
  20321. return null;
  20322. }
  20323. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20324. // Animations
  20325. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20326. return serializationObject;
  20327. };
  20328. BaseTexture.WhenAllReady = function (textures, callback) {
  20329. var numRemaining = textures.length;
  20330. if (numRemaining === 0) {
  20331. callback();
  20332. return;
  20333. }
  20334. var _loop_1 = function () {
  20335. texture = textures[i];
  20336. if (texture.isReady()) {
  20337. if (--numRemaining === 0) {
  20338. callback();
  20339. }
  20340. }
  20341. else {
  20342. onLoadObservable = texture.onLoadObservable;
  20343. var onLoadCallback_1 = function () {
  20344. onLoadObservable.removeCallback(onLoadCallback_1);
  20345. if (--numRemaining === 0) {
  20346. callback();
  20347. }
  20348. };
  20349. onLoadObservable.add(onLoadCallback_1);
  20350. }
  20351. };
  20352. var texture, onLoadObservable;
  20353. for (var i = 0; i < textures.length; i++) {
  20354. _loop_1();
  20355. }
  20356. };
  20357. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20358. __decorate([
  20359. BABYLON.serialize()
  20360. ], BaseTexture.prototype, "name", void 0);
  20361. __decorate([
  20362. BABYLON.serialize("hasAlpha")
  20363. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20364. __decorate([
  20365. BABYLON.serialize()
  20366. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20367. __decorate([
  20368. BABYLON.serialize()
  20369. ], BaseTexture.prototype, "level", void 0);
  20370. __decorate([
  20371. BABYLON.serialize()
  20372. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20373. __decorate([
  20374. BABYLON.serialize("coordinatesMode")
  20375. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20376. __decorate([
  20377. BABYLON.serialize()
  20378. ], BaseTexture.prototype, "wrapU", void 0);
  20379. __decorate([
  20380. BABYLON.serialize()
  20381. ], BaseTexture.prototype, "wrapV", void 0);
  20382. __decorate([
  20383. BABYLON.serialize()
  20384. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20385. __decorate([
  20386. BABYLON.serialize()
  20387. ], BaseTexture.prototype, "isCube", void 0);
  20388. __decorate([
  20389. BABYLON.serialize()
  20390. ], BaseTexture.prototype, "gammaSpace", void 0);
  20391. __decorate([
  20392. BABYLON.serialize()
  20393. ], BaseTexture.prototype, "invertZ", void 0);
  20394. __decorate([
  20395. BABYLON.serialize()
  20396. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20397. __decorate([
  20398. BABYLON.serialize()
  20399. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20400. __decorate([
  20401. BABYLON.serialize()
  20402. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20403. __decorate([
  20404. BABYLON.serialize()
  20405. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20406. return BaseTexture;
  20407. }());
  20408. BABYLON.BaseTexture = BaseTexture;
  20409. })(BABYLON || (BABYLON = {}));
  20410. //# sourceMappingURL=babylon.baseTexture.js.map
  20411. var BABYLON;
  20412. (function (BABYLON) {
  20413. var Texture = (function (_super) {
  20414. __extends(Texture, _super);
  20415. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20416. if (noMipmap === void 0) { noMipmap = false; }
  20417. if (invertY === void 0) { invertY = true; }
  20418. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20419. if (onLoad === void 0) { onLoad = null; }
  20420. if (onError === void 0) { onError = null; }
  20421. if (buffer === void 0) { buffer = null; }
  20422. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20423. var _this = _super.call(this, scene) || this;
  20424. _this.uOffset = 0;
  20425. _this.vOffset = 0;
  20426. _this.uScale = 1.0;
  20427. _this.vScale = 1.0;
  20428. _this.uAng = 0;
  20429. _this.vAng = 0;
  20430. _this.wAng = 0;
  20431. _this._isBlocking = true;
  20432. _this.name = url;
  20433. _this.url = url;
  20434. _this._noMipmap = noMipmap;
  20435. _this._invertY = invertY;
  20436. _this._samplingMode = samplingMode;
  20437. _this._buffer = buffer;
  20438. _this._deleteBuffer = deleteBuffer;
  20439. _this._format = format;
  20440. scene = _this.getScene();
  20441. var load = function () {
  20442. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20443. _this.onLoadObservable.notifyObservers(_this);
  20444. }
  20445. if (onLoad) {
  20446. onLoad();
  20447. }
  20448. if (!_this.isBlocking) {
  20449. scene.resetCachedMaterial();
  20450. }
  20451. };
  20452. if (!url) {
  20453. _this._delayedOnLoad = load;
  20454. _this._delayedOnError = onError;
  20455. return _this;
  20456. }
  20457. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20458. if (!_this._texture) {
  20459. if (!scene.useDelayedTextureLoading) {
  20460. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20461. if (deleteBuffer) {
  20462. delete _this._buffer;
  20463. }
  20464. }
  20465. else {
  20466. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20467. _this._delayedOnLoad = load;
  20468. _this._delayedOnError = onError;
  20469. }
  20470. }
  20471. else {
  20472. if (_this._texture.isReady) {
  20473. BABYLON.Tools.SetImmediate(function () { return load(); });
  20474. }
  20475. else {
  20476. _this._texture.onLoadedObservable.add(load);
  20477. }
  20478. }
  20479. return _this;
  20480. }
  20481. Object.defineProperty(Texture.prototype, "noMipmap", {
  20482. get: function () {
  20483. return this._noMipmap;
  20484. },
  20485. enumerable: true,
  20486. configurable: true
  20487. });
  20488. Object.defineProperty(Texture.prototype, "isBlocking", {
  20489. get: function () {
  20490. return this._isBlocking;
  20491. },
  20492. set: function (value) {
  20493. this._isBlocking = value;
  20494. },
  20495. enumerable: true,
  20496. configurable: true
  20497. });
  20498. Object.defineProperty(Texture.prototype, "samplingMode", {
  20499. get: function () {
  20500. return this._samplingMode;
  20501. },
  20502. enumerable: true,
  20503. configurable: true
  20504. });
  20505. Texture.prototype.updateURL = function (url) {
  20506. this.url = url;
  20507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20508. this.delayLoad();
  20509. };
  20510. Texture.prototype.delayLoad = function () {
  20511. var _this = this;
  20512. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20513. return;
  20514. }
  20515. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20516. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20517. if (!this._texture) {
  20518. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  20519. if (this._deleteBuffer) {
  20520. delete this._buffer;
  20521. }
  20522. }
  20523. else {
  20524. if (this._texture.isReady) {
  20525. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20526. }
  20527. else {
  20528. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20529. }
  20530. }
  20531. };
  20532. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20533. if (!this._texture) {
  20534. return;
  20535. }
  20536. this._samplingMode = samplingMode;
  20537. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20538. };
  20539. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20540. x *= this.uScale;
  20541. y *= this.vScale;
  20542. x -= 0.5 * this.uScale;
  20543. y -= 0.5 * this.vScale;
  20544. z -= 0.5;
  20545. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20546. t.x += 0.5 * this.uScale + this.uOffset;
  20547. t.y += 0.5 * this.vScale + this.vOffset;
  20548. t.z += 0.5;
  20549. };
  20550. Texture.prototype.getTextureMatrix = function () {
  20551. var _this = this;
  20552. if (this.uOffset === this._cachedUOffset &&
  20553. this.vOffset === this._cachedVOffset &&
  20554. this.uScale === this._cachedUScale &&
  20555. this.vScale === this._cachedVScale &&
  20556. this.uAng === this._cachedUAng &&
  20557. this.vAng === this._cachedVAng &&
  20558. this.wAng === this._cachedWAng) {
  20559. return this._cachedTextureMatrix;
  20560. }
  20561. this._cachedUOffset = this.uOffset;
  20562. this._cachedVOffset = this.vOffset;
  20563. this._cachedUScale = this.uScale;
  20564. this._cachedVScale = this.vScale;
  20565. this._cachedUAng = this.uAng;
  20566. this._cachedVAng = this.vAng;
  20567. this._cachedWAng = this.wAng;
  20568. if (!this._cachedTextureMatrix) {
  20569. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20570. this._rowGenerationMatrix = new BABYLON.Matrix();
  20571. this._t0 = BABYLON.Vector3.Zero();
  20572. this._t1 = BABYLON.Vector3.Zero();
  20573. this._t2 = BABYLON.Vector3.Zero();
  20574. }
  20575. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20576. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20577. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20578. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20579. this._t1.subtractInPlace(this._t0);
  20580. this._t2.subtractInPlace(this._t0);
  20581. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20582. this._cachedTextureMatrix.m[0] = this._t1.x;
  20583. this._cachedTextureMatrix.m[1] = this._t1.y;
  20584. this._cachedTextureMatrix.m[2] = this._t1.z;
  20585. this._cachedTextureMatrix.m[4] = this._t2.x;
  20586. this._cachedTextureMatrix.m[5] = this._t2.y;
  20587. this._cachedTextureMatrix.m[6] = this._t2.z;
  20588. this._cachedTextureMatrix.m[8] = this._t0.x;
  20589. this._cachedTextureMatrix.m[9] = this._t0.y;
  20590. this._cachedTextureMatrix.m[10] = this._t0.z;
  20591. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20592. return mat.hasTexture(_this);
  20593. });
  20594. return this._cachedTextureMatrix;
  20595. };
  20596. Texture.prototype.getReflectionTextureMatrix = function () {
  20597. var _this = this;
  20598. var scene = this.getScene();
  20599. if (this.uOffset === this._cachedUOffset &&
  20600. this.vOffset === this._cachedVOffset &&
  20601. this.uScale === this._cachedUScale &&
  20602. this.vScale === this._cachedVScale &&
  20603. this.coordinatesMode === this._cachedCoordinatesMode) {
  20604. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20605. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20606. return this._cachedTextureMatrix;
  20607. }
  20608. }
  20609. else {
  20610. return this._cachedTextureMatrix;
  20611. }
  20612. }
  20613. if (!this._cachedTextureMatrix) {
  20614. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20615. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20616. }
  20617. this._cachedUOffset = this.uOffset;
  20618. this._cachedVOffset = this.vOffset;
  20619. this._cachedUScale = this.uScale;
  20620. this._cachedVScale = this.vScale;
  20621. this._cachedCoordinatesMode = this.coordinatesMode;
  20622. switch (this.coordinatesMode) {
  20623. case Texture.PLANAR_MODE:
  20624. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20625. this._cachedTextureMatrix[0] = this.uScale;
  20626. this._cachedTextureMatrix[5] = this.vScale;
  20627. this._cachedTextureMatrix[12] = this.uOffset;
  20628. this._cachedTextureMatrix[13] = this.vOffset;
  20629. break;
  20630. case Texture.PROJECTION_MODE:
  20631. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20632. this._projectionModeMatrix.m[0] = 0.5;
  20633. this._projectionModeMatrix.m[5] = -0.5;
  20634. this._projectionModeMatrix.m[10] = 0.0;
  20635. this._projectionModeMatrix.m[12] = 0.5;
  20636. this._projectionModeMatrix.m[13] = 0.5;
  20637. this._projectionModeMatrix.m[14] = 1.0;
  20638. this._projectionModeMatrix.m[15] = 1.0;
  20639. var projectionMatrix = scene.getProjectionMatrix();
  20640. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20641. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20642. break;
  20643. default:
  20644. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20645. break;
  20646. }
  20647. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20648. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20649. });
  20650. return this._cachedTextureMatrix;
  20651. };
  20652. Texture.prototype.clone = function () {
  20653. var _this = this;
  20654. return BABYLON.SerializationHelper.Clone(function () {
  20655. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20656. }, this);
  20657. };
  20658. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20659. get: function () {
  20660. if (!this._onLoadObservable) {
  20661. this._onLoadObservable = new BABYLON.Observable();
  20662. }
  20663. return this._onLoadObservable;
  20664. },
  20665. enumerable: true,
  20666. configurable: true
  20667. });
  20668. Texture.prototype.serialize = function () {
  20669. var serializationObject = _super.prototype.serialize.call(this);
  20670. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20671. serializationObject.base64String = this._buffer;
  20672. serializationObject.name = serializationObject.name.replace("data:", "");
  20673. }
  20674. return serializationObject;
  20675. };
  20676. Texture.prototype.getClassName = function () {
  20677. return "Texture";
  20678. };
  20679. Texture.prototype.dispose = function () {
  20680. _super.prototype.dispose.call(this);
  20681. if (this.onLoadObservable) {
  20682. this.onLoadObservable.clear();
  20683. this._onLoadObservable = null;
  20684. }
  20685. this._delayedOnLoad = null;
  20686. this._delayedOnError = null;
  20687. };
  20688. // Statics
  20689. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20690. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20691. if (onLoad === void 0) { onLoad = null; }
  20692. if (onError === void 0) { onError = null; }
  20693. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20694. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20695. };
  20696. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20697. if (parsedTexture.customType) {
  20698. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20699. // Update Sampling Mode
  20700. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20701. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20702. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20703. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20704. }
  20705. }
  20706. return parsedCustomTexture;
  20707. }
  20708. if (parsedTexture.isCube) {
  20709. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20710. }
  20711. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20712. return null;
  20713. }
  20714. var texture = BABYLON.SerializationHelper.Parse(function () {
  20715. if (parsedTexture.mirrorPlane) {
  20716. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20717. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20718. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20719. return mirrorTexture;
  20720. }
  20721. else if (parsedTexture.isRenderTarget) {
  20722. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20723. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20724. return renderTargetTexture;
  20725. }
  20726. else {
  20727. var texture;
  20728. if (parsedTexture.base64String) {
  20729. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20730. }
  20731. else {
  20732. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20733. }
  20734. return texture;
  20735. }
  20736. }, parsedTexture, scene);
  20737. // Update Sampling Mode
  20738. if (parsedTexture.samplingMode) {
  20739. var sampling = parsedTexture.samplingMode;
  20740. if (texture._samplingMode !== sampling) {
  20741. texture.updateSamplingMode(sampling);
  20742. }
  20743. }
  20744. // Animations
  20745. if (parsedTexture.animations) {
  20746. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20747. var parsedAnimation = parsedTexture.animations[animationIndex];
  20748. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20749. }
  20750. }
  20751. return texture;
  20752. };
  20753. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20754. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20755. if (noMipmap === void 0) { noMipmap = false; }
  20756. if (invertY === void 0) { invertY = true; }
  20757. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20758. if (onLoad === void 0) { onLoad = null; }
  20759. if (onError === void 0) { onError = null; }
  20760. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20761. if (name.substr(0, 5) !== "data:") {
  20762. name = "data:" + name;
  20763. }
  20764. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20765. };
  20766. // Constants
  20767. Texture.NEAREST_SAMPLINGMODE = 1;
  20768. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20769. Texture.BILINEAR_SAMPLINGMODE = 2;
  20770. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20771. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20772. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20773. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20774. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20775. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20776. Texture.NEAREST_LINEAR = 7;
  20777. Texture.NEAREST_NEAREST = 8;
  20778. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20779. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20780. Texture.LINEAR_LINEAR = 11;
  20781. Texture.LINEAR_NEAREST = 12;
  20782. Texture.EXPLICIT_MODE = 0;
  20783. Texture.SPHERICAL_MODE = 1;
  20784. Texture.PLANAR_MODE = 2;
  20785. Texture.CUBIC_MODE = 3;
  20786. Texture.PROJECTION_MODE = 4;
  20787. Texture.SKYBOX_MODE = 5;
  20788. Texture.INVCUBIC_MODE = 6;
  20789. Texture.EQUIRECTANGULAR_MODE = 7;
  20790. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20791. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20792. Texture.CLAMP_ADDRESSMODE = 0;
  20793. Texture.WRAP_ADDRESSMODE = 1;
  20794. Texture.MIRROR_ADDRESSMODE = 2;
  20795. __decorate([
  20796. BABYLON.serialize()
  20797. ], Texture.prototype, "url", void 0);
  20798. __decorate([
  20799. BABYLON.serialize()
  20800. ], Texture.prototype, "uOffset", void 0);
  20801. __decorate([
  20802. BABYLON.serialize()
  20803. ], Texture.prototype, "vOffset", void 0);
  20804. __decorate([
  20805. BABYLON.serialize()
  20806. ], Texture.prototype, "uScale", void 0);
  20807. __decorate([
  20808. BABYLON.serialize()
  20809. ], Texture.prototype, "vScale", void 0);
  20810. __decorate([
  20811. BABYLON.serialize()
  20812. ], Texture.prototype, "uAng", void 0);
  20813. __decorate([
  20814. BABYLON.serialize()
  20815. ], Texture.prototype, "vAng", void 0);
  20816. __decorate([
  20817. BABYLON.serialize()
  20818. ], Texture.prototype, "wAng", void 0);
  20819. __decorate([
  20820. BABYLON.serialize()
  20821. ], Texture.prototype, "isBlocking", null);
  20822. return Texture;
  20823. }(BABYLON.BaseTexture));
  20824. BABYLON.Texture = Texture;
  20825. })(BABYLON || (BABYLON = {}));
  20826. //# sourceMappingURL=babylon.texture.js.map
  20827. var BABYLON;
  20828. (function (BABYLON) {
  20829. var _InstancesBatch = (function () {
  20830. function _InstancesBatch() {
  20831. this.mustReturn = false;
  20832. this.visibleInstances = new Array();
  20833. this.renderSelf = new Array();
  20834. }
  20835. return _InstancesBatch;
  20836. }());
  20837. BABYLON._InstancesBatch = _InstancesBatch;
  20838. var Mesh = (function (_super) {
  20839. __extends(Mesh, _super);
  20840. /**
  20841. * @constructor
  20842. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20843. * @param {Scene} scene The scene to add this mesh to.
  20844. * @param {Node} parent The parent of this mesh, if it has one
  20845. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20846. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20847. * When false, achieved by calling a clone(), also passing False.
  20848. * This will make creation of children, recursive.
  20849. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20850. */
  20851. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20852. if (parent === void 0) { parent = null; }
  20853. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20854. var _this = _super.call(this, name, scene) || this;
  20855. // Events
  20856. /**
  20857. * An event triggered before rendering the mesh
  20858. * @type {BABYLON.Observable}
  20859. */
  20860. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20861. /**
  20862. * An event triggered after rendering the mesh
  20863. * @type {BABYLON.Observable}
  20864. */
  20865. _this.onAfterRenderObservable = new BABYLON.Observable();
  20866. /**
  20867. * An event triggered before drawing the mesh
  20868. * @type {BABYLON.Observable}
  20869. */
  20870. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20871. // Members
  20872. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20873. _this.instances = new Array();
  20874. _this._LODLevels = new Array();
  20875. _this._visibleInstances = {};
  20876. _this._renderIdForInstances = new Array();
  20877. _this._batchCache = new _InstancesBatch();
  20878. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20879. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20880. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20881. // Will be used to save a source mesh reference, If any
  20882. _this._source = null;
  20883. if (source) {
  20884. // Source mesh
  20885. _this._source = source;
  20886. // Geometry
  20887. if (source._geometry) {
  20888. source._geometry.applyToMesh(_this);
  20889. }
  20890. // Deep copy
  20891. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20892. // Parent
  20893. _this.parent = source.parent;
  20894. // Pivot
  20895. _this.setPivotMatrix(source.getPivotMatrix());
  20896. _this.id = name + "." + source.id;
  20897. // Material
  20898. _this.material = source.material;
  20899. var index;
  20900. if (!doNotCloneChildren) {
  20901. // Children
  20902. for (index = 0; index < scene.meshes.length; index++) {
  20903. var mesh = scene.meshes[index];
  20904. if (mesh.parent === source) {
  20905. // doNotCloneChildren is always going to be False
  20906. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20907. }
  20908. }
  20909. }
  20910. // Physics clone
  20911. var physicsEngine = _this.getScene().getPhysicsEngine();
  20912. if (clonePhysicsImpostor && physicsEngine) {
  20913. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20914. if (impostor) {
  20915. _this.physicsImpostor = impostor.clone(_this);
  20916. }
  20917. }
  20918. // Particles
  20919. for (index = 0; index < scene.particleSystems.length; index++) {
  20920. var system = scene.particleSystems[index];
  20921. if (system.emitter === source) {
  20922. system.clone(system.name, _this);
  20923. }
  20924. }
  20925. _this.computeWorldMatrix(true);
  20926. }
  20927. // Parent
  20928. if (parent !== null) {
  20929. _this.parent = parent;
  20930. }
  20931. return _this;
  20932. }
  20933. Object.defineProperty(Mesh, "FRONTSIDE", {
  20934. /**
  20935. * Mesh side orientation : usually the external or front surface
  20936. */
  20937. get: function () {
  20938. return Mesh._FRONTSIDE;
  20939. },
  20940. enumerable: true,
  20941. configurable: true
  20942. });
  20943. Object.defineProperty(Mesh, "BACKSIDE", {
  20944. /**
  20945. * Mesh side orientation : usually the internal or back surface
  20946. */
  20947. get: function () {
  20948. return Mesh._BACKSIDE;
  20949. },
  20950. enumerable: true,
  20951. configurable: true
  20952. });
  20953. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20954. /**
  20955. * Mesh side orientation : both internal and external or front and back surfaces
  20956. */
  20957. get: function () {
  20958. return Mesh._DOUBLESIDE;
  20959. },
  20960. enumerable: true,
  20961. configurable: true
  20962. });
  20963. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20964. /**
  20965. * Mesh side orientation : by default, `FRONTSIDE`
  20966. */
  20967. get: function () {
  20968. return Mesh._DEFAULTSIDE;
  20969. },
  20970. enumerable: true,
  20971. configurable: true
  20972. });
  20973. Object.defineProperty(Mesh, "NO_CAP", {
  20974. /**
  20975. * Mesh cap setting : no cap
  20976. */
  20977. get: function () {
  20978. return Mesh._NO_CAP;
  20979. },
  20980. enumerable: true,
  20981. configurable: true
  20982. });
  20983. Object.defineProperty(Mesh, "CAP_START", {
  20984. /**
  20985. * Mesh cap setting : one cap at the beginning of the mesh
  20986. */
  20987. get: function () {
  20988. return Mesh._CAP_START;
  20989. },
  20990. enumerable: true,
  20991. configurable: true
  20992. });
  20993. Object.defineProperty(Mesh, "CAP_END", {
  20994. /**
  20995. * Mesh cap setting : one cap at the end of the mesh
  20996. */
  20997. get: function () {
  20998. return Mesh._CAP_END;
  20999. },
  21000. enumerable: true,
  21001. configurable: true
  21002. });
  21003. Object.defineProperty(Mesh, "CAP_ALL", {
  21004. /**
  21005. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21006. */
  21007. get: function () {
  21008. return Mesh._CAP_ALL;
  21009. },
  21010. enumerable: true,
  21011. configurable: true
  21012. });
  21013. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21014. set: function (callback) {
  21015. if (this._onBeforeDrawObserver) {
  21016. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21017. }
  21018. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21019. },
  21020. enumerable: true,
  21021. configurable: true
  21022. });
  21023. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21024. get: function () {
  21025. return this._morphTargetManager;
  21026. },
  21027. set: function (value) {
  21028. if (this._morphTargetManager === value) {
  21029. return;
  21030. }
  21031. this._morphTargetManager = value;
  21032. this._syncGeometryWithMorphTargetManager();
  21033. },
  21034. enumerable: true,
  21035. configurable: true
  21036. });
  21037. Object.defineProperty(Mesh.prototype, "source", {
  21038. get: function () {
  21039. return this._source;
  21040. },
  21041. enumerable: true,
  21042. configurable: true
  21043. });
  21044. // Methods
  21045. /**
  21046. * Returns the string "Mesh".
  21047. */
  21048. Mesh.prototype.getClassName = function () {
  21049. return "Mesh";
  21050. };
  21051. /**
  21052. * Returns a string.
  21053. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21054. */
  21055. Mesh.prototype.toString = function (fullDetails) {
  21056. var ret = _super.prototype.toString.call(this, fullDetails);
  21057. ret += ", n vertices: " + this.getTotalVertices();
  21058. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21059. if (this.animations) {
  21060. for (var i = 0; i < this.animations.length; i++) {
  21061. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21062. }
  21063. }
  21064. if (fullDetails) {
  21065. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21066. }
  21067. return ret;
  21068. };
  21069. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21070. /**
  21071. * True if the mesh has some Levels Of Details (LOD).
  21072. * Returns a boolean.
  21073. */
  21074. get: function () {
  21075. return this._LODLevels.length > 0;
  21076. },
  21077. enumerable: true,
  21078. configurable: true
  21079. });
  21080. Mesh.prototype._sortLODLevels = function () {
  21081. this._LODLevels.sort(function (a, b) {
  21082. if (a.distance < b.distance) {
  21083. return 1;
  21084. }
  21085. if (a.distance > b.distance) {
  21086. return -1;
  21087. }
  21088. return 0;
  21089. });
  21090. };
  21091. /**
  21092. * Add a mesh as LOD level triggered at the given distance.
  21093. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21094. * @param {number} distance The distance from the center of the object to show this level
  21095. * @param {Mesh} mesh The mesh to be added as LOD level
  21096. * @return {Mesh} This mesh (for chaining)
  21097. */
  21098. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21099. if (mesh && mesh._masterMesh) {
  21100. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21101. return this;
  21102. }
  21103. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21104. this._LODLevels.push(level);
  21105. if (mesh) {
  21106. mesh._masterMesh = this;
  21107. }
  21108. this._sortLODLevels();
  21109. return this;
  21110. };
  21111. /**
  21112. * Returns the LOD level mesh at the passed distance or null if not found.
  21113. * It is related to the method `addLODLevel(distance, mesh)`.
  21114. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21115. * Returns an object Mesh or `null`.
  21116. */
  21117. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21118. for (var index = 0; index < this._LODLevels.length; index++) {
  21119. var level = this._LODLevels[index];
  21120. if (level.distance === distance) {
  21121. return level.mesh;
  21122. }
  21123. }
  21124. return null;
  21125. };
  21126. /**
  21127. * Remove a mesh from the LOD array
  21128. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21129. * @param {Mesh} mesh The mesh to be removed.
  21130. * @return {Mesh} This mesh (for chaining)
  21131. */
  21132. Mesh.prototype.removeLODLevel = function (mesh) {
  21133. for (var index = 0; index < this._LODLevels.length; index++) {
  21134. if (this._LODLevels[index].mesh === mesh) {
  21135. this._LODLevels.splice(index, 1);
  21136. if (mesh) {
  21137. mesh._masterMesh = null;
  21138. }
  21139. }
  21140. }
  21141. this._sortLODLevels();
  21142. return this;
  21143. };
  21144. /**
  21145. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21146. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21147. */
  21148. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21149. if (!this._LODLevels || this._LODLevels.length === 0) {
  21150. return this;
  21151. }
  21152. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21153. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21154. if (this.onLODLevelSelection) {
  21155. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21156. }
  21157. return this;
  21158. }
  21159. for (var index = 0; index < this._LODLevels.length; index++) {
  21160. var level = this._LODLevels[index];
  21161. if (level.distance < distanceToCamera) {
  21162. if (level.mesh) {
  21163. level.mesh._preActivate();
  21164. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21165. }
  21166. if (this.onLODLevelSelection) {
  21167. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21168. }
  21169. return level.mesh;
  21170. }
  21171. }
  21172. if (this.onLODLevelSelection) {
  21173. this.onLODLevelSelection(distanceToCamera, this, this);
  21174. }
  21175. return this;
  21176. };
  21177. Object.defineProperty(Mesh.prototype, "geometry", {
  21178. /**
  21179. * Returns the mesh internal Geometry object.
  21180. */
  21181. get: function () {
  21182. return this._geometry;
  21183. },
  21184. enumerable: true,
  21185. configurable: true
  21186. });
  21187. /**
  21188. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21189. */
  21190. Mesh.prototype.getTotalVertices = function () {
  21191. if (!this._geometry) {
  21192. return 0;
  21193. }
  21194. return this._geometry.getTotalVertices();
  21195. };
  21196. /**
  21197. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21198. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  21199. * You can force the copy with forceCopy === true
  21200. * Returns null if the mesh has no geometry or no vertex buffer.
  21201. * Possible `kind` values :
  21202. * - BABYLON.VertexBuffer.PositionKind
  21203. * - BABYLON.VertexBuffer.UVKind
  21204. * - BABYLON.VertexBuffer.UV2Kind
  21205. * - BABYLON.VertexBuffer.UV3Kind
  21206. * - BABYLON.VertexBuffer.UV4Kind
  21207. * - BABYLON.VertexBuffer.UV5Kind
  21208. * - BABYLON.VertexBuffer.UV6Kind
  21209. * - BABYLON.VertexBuffer.ColorKind
  21210. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21211. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21212. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21213. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21214. */
  21215. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21216. if (!this._geometry) {
  21217. return null;
  21218. }
  21219. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21220. };
  21221. /**
  21222. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21223. * Returns `undefined` if the mesh has no geometry.
  21224. * Possible `kind` values :
  21225. * - BABYLON.VertexBuffer.PositionKind
  21226. * - BABYLON.VertexBuffer.UVKind
  21227. * - BABYLON.VertexBuffer.UV2Kind
  21228. * - BABYLON.VertexBuffer.UV3Kind
  21229. * - BABYLON.VertexBuffer.UV4Kind
  21230. * - BABYLON.VertexBuffer.UV5Kind
  21231. * - BABYLON.VertexBuffer.UV6Kind
  21232. * - BABYLON.VertexBuffer.ColorKind
  21233. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21234. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21235. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21236. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21237. */
  21238. Mesh.prototype.getVertexBuffer = function (kind) {
  21239. if (!this._geometry) {
  21240. return undefined;
  21241. }
  21242. return this._geometry.getVertexBuffer(kind);
  21243. };
  21244. /**
  21245. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21246. * Possible `kind` values :
  21247. * - BABYLON.VertexBuffer.PositionKind
  21248. * - BABYLON.VertexBuffer.UVKind
  21249. * - BABYLON.VertexBuffer.UV2Kind
  21250. * - BABYLON.VertexBuffer.UV3Kind
  21251. * - BABYLON.VertexBuffer.UV4Kind
  21252. * - BABYLON.VertexBuffer.UV5Kind
  21253. * - BABYLON.VertexBuffer.UV6Kind
  21254. * - BABYLON.VertexBuffer.ColorKind
  21255. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21256. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21257. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21258. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21259. */
  21260. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21261. if (!this._geometry) {
  21262. if (this._delayInfo) {
  21263. return this._delayInfo.indexOf(kind) !== -1;
  21264. }
  21265. return false;
  21266. }
  21267. return this._geometry.isVerticesDataPresent(kind);
  21268. };
  21269. /**
  21270. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21271. * Possible `kind` values :
  21272. * - BABYLON.VertexBuffer.PositionKind
  21273. * - BABYLON.VertexBuffer.UVKind
  21274. * - BABYLON.VertexBuffer.UV2Kind
  21275. * - BABYLON.VertexBuffer.UV3Kind
  21276. * - BABYLON.VertexBuffer.UV4Kind
  21277. * - BABYLON.VertexBuffer.UV5Kind
  21278. * - BABYLON.VertexBuffer.UV6Kind
  21279. * - BABYLON.VertexBuffer.ColorKind
  21280. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21281. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21282. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21283. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21284. */
  21285. Mesh.prototype.getVerticesDataKinds = function () {
  21286. if (!this._geometry) {
  21287. var result = [];
  21288. if (this._delayInfo) {
  21289. this._delayInfo.forEach(function (kind, index, array) {
  21290. result.push(kind);
  21291. });
  21292. }
  21293. return result;
  21294. }
  21295. return this._geometry.getVerticesDataKinds();
  21296. };
  21297. /**
  21298. * Returns a positive integer : the total number of indices in this mesh geometry.
  21299. * Returns zero if the mesh has no geometry.
  21300. */
  21301. Mesh.prototype.getTotalIndices = function () {
  21302. if (!this._geometry) {
  21303. return 0;
  21304. }
  21305. return this._geometry.getTotalIndices();
  21306. };
  21307. /**
  21308. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21309. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  21310. * Returns an empty array if the mesh has no geometry.
  21311. */
  21312. Mesh.prototype.getIndices = function (copyWhenShared) {
  21313. if (!this._geometry) {
  21314. return [];
  21315. }
  21316. return this._geometry.getIndices(copyWhenShared);
  21317. };
  21318. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21319. get: function () {
  21320. return this._masterMesh !== null && this._masterMesh !== undefined;
  21321. },
  21322. enumerable: true,
  21323. configurable: true
  21324. });
  21325. /**
  21326. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21327. */
  21328. Mesh.prototype.isReady = function () {
  21329. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21330. return false;
  21331. }
  21332. return _super.prototype.isReady.call(this);
  21333. };
  21334. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21335. get: function () {
  21336. return this._sideOrientation;
  21337. },
  21338. /**
  21339. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21340. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21341. */
  21342. set: function (sideO) {
  21343. this._sideOrientation = sideO;
  21344. },
  21345. enumerable: true,
  21346. configurable: true
  21347. });
  21348. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21349. /**
  21350. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21351. * This property is pertinent only for updatable parametric shapes.
  21352. */
  21353. get: function () {
  21354. return this._areNormalsFrozen;
  21355. },
  21356. enumerable: true,
  21357. configurable: true
  21358. });
  21359. /**
  21360. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21361. * It has no effect at all on other shapes.
  21362. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21363. * Returns the Mesh.
  21364. */
  21365. Mesh.prototype.freezeNormals = function () {
  21366. this._areNormalsFrozen = true;
  21367. return this;
  21368. };
  21369. /**
  21370. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21371. * It has no effect at all on other shapes.
  21372. * It reactivates the mesh normals computation if it was previously frozen.
  21373. * Returns the Mesh.
  21374. */
  21375. Mesh.prototype.unfreezeNormals = function () {
  21376. this._areNormalsFrozen = false;
  21377. return this;
  21378. };
  21379. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21380. /**
  21381. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21382. */
  21383. set: function (count) {
  21384. this._overridenInstanceCount = count;
  21385. },
  21386. enumerable: true,
  21387. configurable: true
  21388. });
  21389. // Methods
  21390. Mesh.prototype._preActivate = function () {
  21391. var sceneRenderId = this.getScene().getRenderId();
  21392. if (this._preActivateId === sceneRenderId) {
  21393. return this;
  21394. }
  21395. this._preActivateId = sceneRenderId;
  21396. this._visibleInstances = null;
  21397. return this;
  21398. };
  21399. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21400. if (this._visibleInstances) {
  21401. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21402. }
  21403. return this;
  21404. };
  21405. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21406. if (!this._visibleInstances) {
  21407. this._visibleInstances = {};
  21408. this._visibleInstances.defaultRenderId = renderId;
  21409. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21410. }
  21411. if (!this._visibleInstances[renderId]) {
  21412. this._visibleInstances[renderId] = new Array();
  21413. }
  21414. this._visibleInstances[renderId].push(instance);
  21415. return this;
  21416. };
  21417. /**
  21418. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21419. * This means the mesh underlying bounding box and sphere are recomputed.
  21420. * Returns the Mesh.
  21421. */
  21422. Mesh.prototype.refreshBoundingInfo = function () {
  21423. if (this._boundingInfo.isLocked) {
  21424. return;
  21425. }
  21426. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21427. if (data) {
  21428. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21429. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21430. }
  21431. if (this.subMeshes) {
  21432. for (var index = 0; index < this.subMeshes.length; index++) {
  21433. this.subMeshes[index].refreshBoundingInfo();
  21434. }
  21435. }
  21436. this._updateBoundingInfo();
  21437. return this;
  21438. };
  21439. Mesh.prototype._createGlobalSubMesh = function (force) {
  21440. var totalVertices = this.getTotalVertices();
  21441. if (!totalVertices || !this.getIndices()) {
  21442. return null;
  21443. }
  21444. // Check if we need to recreate the submeshes
  21445. if (this.subMeshes && this.subMeshes.length > 0) {
  21446. var totalIndices = this.getIndices().length;
  21447. var needToRecreate = false;
  21448. if (force) {
  21449. needToRecreate = true;
  21450. }
  21451. else {
  21452. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21453. var submesh = _a[_i];
  21454. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21455. needToRecreate = true;
  21456. break;
  21457. }
  21458. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21459. needToRecreate = true;
  21460. break;
  21461. }
  21462. }
  21463. }
  21464. if (!needToRecreate) {
  21465. return;
  21466. }
  21467. }
  21468. this.releaseSubMeshes();
  21469. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21470. };
  21471. Mesh.prototype.subdivide = function (count) {
  21472. if (count < 1) {
  21473. return;
  21474. }
  21475. var totalIndices = this.getTotalIndices();
  21476. var subdivisionSize = (totalIndices / count) | 0;
  21477. var offset = 0;
  21478. // Ensure that subdivisionSize is a multiple of 3
  21479. while (subdivisionSize % 3 !== 0) {
  21480. subdivisionSize++;
  21481. }
  21482. this.releaseSubMeshes();
  21483. for (var index = 0; index < count; index++) {
  21484. if (offset >= totalIndices) {
  21485. break;
  21486. }
  21487. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21488. offset += subdivisionSize;
  21489. }
  21490. this.synchronizeInstances();
  21491. };
  21492. /**
  21493. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21494. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21495. * The `data` are either a numeric array either a Float32Array.
  21496. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21497. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  21498. * Note that a new underlying VertexBuffer object is created each call.
  21499. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21500. *
  21501. * Possible `kind` values :
  21502. * - BABYLON.VertexBuffer.PositionKind
  21503. * - BABYLON.VertexBuffer.UVKind
  21504. * - BABYLON.VertexBuffer.UV2Kind
  21505. * - BABYLON.VertexBuffer.UV3Kind
  21506. * - BABYLON.VertexBuffer.UV4Kind
  21507. * - BABYLON.VertexBuffer.UV5Kind
  21508. * - BABYLON.VertexBuffer.UV6Kind
  21509. * - BABYLON.VertexBuffer.ColorKind
  21510. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21511. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21512. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21513. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21514. *
  21515. * Returns the Mesh.
  21516. */
  21517. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21518. if (!this._geometry) {
  21519. var vertexData = new BABYLON.VertexData();
  21520. vertexData.set(data, kind);
  21521. var scene = this.getScene();
  21522. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21523. }
  21524. else {
  21525. this._geometry.setVerticesData(kind, data, updatable, stride);
  21526. }
  21527. return this;
  21528. };
  21529. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21530. if (updatable === void 0) { updatable = true; }
  21531. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21532. return;
  21533. }
  21534. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21535. };
  21536. /**
  21537. * Sets the mesh VertexBuffer.
  21538. * Returns the Mesh.
  21539. */
  21540. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21541. if (!this._geometry) {
  21542. var scene = this.getScene();
  21543. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21544. }
  21545. this._geometry.setVerticesBuffer(buffer);
  21546. return this;
  21547. };
  21548. /**
  21549. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21550. * If the mesh has no geometry, it is simply returned as it is.
  21551. * The `data` are either a numeric array either a Float32Array.
  21552. * No new underlying VertexBuffer object is created.
  21553. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21554. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21555. *
  21556. * Possible `kind` values :
  21557. * - BABYLON.VertexBuffer.PositionKind
  21558. * - BABYLON.VertexBuffer.UVKind
  21559. * - BABYLON.VertexBuffer.UV2Kind
  21560. * - BABYLON.VertexBuffer.UV3Kind
  21561. * - BABYLON.VertexBuffer.UV4Kind
  21562. * - BABYLON.VertexBuffer.UV5Kind
  21563. * - BABYLON.VertexBuffer.UV6Kind
  21564. * - BABYLON.VertexBuffer.ColorKind
  21565. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21566. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21567. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21568. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21569. *
  21570. * Returns the Mesh.
  21571. */
  21572. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21573. if (!this._geometry) {
  21574. return;
  21575. }
  21576. if (!makeItUnique) {
  21577. this._geometry.updateVerticesData(kind, data, updateExtends);
  21578. }
  21579. else {
  21580. this.makeGeometryUnique();
  21581. this.updateVerticesData(kind, data, updateExtends, false);
  21582. }
  21583. return this;
  21584. };
  21585. /**
  21586. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21587. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21588. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21589. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21590. * Returns the Mesh.
  21591. */
  21592. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21593. if (computeNormals === void 0) { computeNormals = true; }
  21594. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21595. positionFunction(positions);
  21596. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21597. if (computeNormals) {
  21598. var indices = this.getIndices();
  21599. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21600. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21601. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21602. }
  21603. return this;
  21604. };
  21605. /**
  21606. * Creates a un-shared specific occurence of the geometry for the mesh.
  21607. * Returns the Mesh.
  21608. */
  21609. Mesh.prototype.makeGeometryUnique = function () {
  21610. if (!this._geometry) {
  21611. return;
  21612. }
  21613. var oldGeometry = this._geometry;
  21614. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21615. oldGeometry.releaseForMesh(this, true);
  21616. geometry.applyToMesh(this);
  21617. return this;
  21618. };
  21619. /**
  21620. * Sets the mesh indices.
  21621. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21622. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21623. * This method creates a new index buffer each call.
  21624. * Returns the Mesh.
  21625. */
  21626. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21627. if (!this._geometry) {
  21628. var vertexData = new BABYLON.VertexData();
  21629. vertexData.indices = indices;
  21630. var scene = this.getScene();
  21631. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21632. }
  21633. else {
  21634. this._geometry.setIndices(indices, totalVertices);
  21635. }
  21636. return this;
  21637. };
  21638. /**
  21639. * Invert the geometry to move from a right handed system to a left handed one.
  21640. * Returns the Mesh.
  21641. */
  21642. Mesh.prototype.toLeftHanded = function () {
  21643. if (!this._geometry) {
  21644. return;
  21645. }
  21646. this._geometry.toLeftHanded();
  21647. return this;
  21648. };
  21649. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21650. var engine = this.getScene().getEngine();
  21651. // Wireframe
  21652. var indexToBind;
  21653. if (this._unIndexed) {
  21654. indexToBind = null;
  21655. }
  21656. else {
  21657. switch (fillMode) {
  21658. case BABYLON.Material.PointFillMode:
  21659. indexToBind = null;
  21660. break;
  21661. case BABYLON.Material.WireFrameFillMode:
  21662. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21663. break;
  21664. default:
  21665. case BABYLON.Material.TriangleFillMode:
  21666. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21667. break;
  21668. }
  21669. }
  21670. // VBOs
  21671. this._geometry._bind(effect, indexToBind);
  21672. return this;
  21673. };
  21674. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21675. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21676. return this;
  21677. }
  21678. this.onBeforeDrawObservable.notifyObservers(this);
  21679. var engine = this.getScene().getEngine();
  21680. // Draw order
  21681. switch (fillMode) {
  21682. case BABYLON.Material.PointFillMode:
  21683. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21684. break;
  21685. case BABYLON.Material.WireFrameFillMode:
  21686. if (this._unIndexed) {
  21687. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21688. }
  21689. else {
  21690. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21691. }
  21692. break;
  21693. default:
  21694. if (this._unIndexed) {
  21695. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21696. }
  21697. else {
  21698. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21699. }
  21700. }
  21701. return this;
  21702. };
  21703. /**
  21704. * Registers for this mesh a javascript function called just before the rendering process.
  21705. * This function is passed the current mesh.
  21706. * Return the Mesh.
  21707. */
  21708. Mesh.prototype.registerBeforeRender = function (func) {
  21709. this.onBeforeRenderObservable.add(func);
  21710. return this;
  21711. };
  21712. /**
  21713. * Disposes a previously registered javascript function called before the rendering.
  21714. * This function is passed the current mesh.
  21715. * Returns the Mesh.
  21716. */
  21717. Mesh.prototype.unregisterBeforeRender = function (func) {
  21718. this.onBeforeRenderObservable.removeCallback(func);
  21719. return this;
  21720. };
  21721. /**
  21722. * Registers for this mesh a javascript function called just after the rendering is complete.
  21723. * This function is passed the current mesh.
  21724. * Returns the Mesh.
  21725. */
  21726. Mesh.prototype.registerAfterRender = function (func) {
  21727. this.onAfterRenderObservable.add(func);
  21728. return this;
  21729. };
  21730. /**
  21731. * Disposes a previously registered javascript function called after the rendering.
  21732. * This function is passed the current mesh.
  21733. * Return the Mesh.
  21734. */
  21735. Mesh.prototype.unregisterAfterRender = function (func) {
  21736. this.onAfterRenderObservable.removeCallback(func);
  21737. return this;
  21738. };
  21739. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21740. var scene = this.getScene();
  21741. this._batchCache.mustReturn = false;
  21742. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21743. this._batchCache.visibleInstances[subMeshId] = null;
  21744. if (this._visibleInstances) {
  21745. var currentRenderId = scene.getRenderId();
  21746. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21747. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21748. var selfRenderId = this._renderId;
  21749. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21750. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21751. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21752. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21753. }
  21754. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21755. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21756. this._batchCache.mustReturn = true;
  21757. return this._batchCache;
  21758. }
  21759. if (currentRenderId !== selfRenderId) {
  21760. this._batchCache.renderSelf[subMeshId] = false;
  21761. }
  21762. }
  21763. this._renderIdForInstances[subMeshId] = currentRenderId;
  21764. }
  21765. return this._batchCache;
  21766. };
  21767. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21768. var visibleInstances = batch.visibleInstances[subMesh._id];
  21769. var matricesCount = visibleInstances.length + 1;
  21770. var bufferSize = matricesCount * 16 * 4;
  21771. var currentInstancesBufferSize = this._instancesBufferSize;
  21772. var instancesBuffer = this._instancesBuffer;
  21773. while (this._instancesBufferSize < bufferSize) {
  21774. this._instancesBufferSize *= 2;
  21775. }
  21776. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21777. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21778. }
  21779. var offset = 0;
  21780. var instancesCount = 0;
  21781. var world = this.getWorldMatrix();
  21782. if (batch.renderSelf[subMesh._id]) {
  21783. world.copyToArray(this._instancesData, offset);
  21784. offset += 16;
  21785. instancesCount++;
  21786. }
  21787. if (visibleInstances) {
  21788. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21789. var instance = visibleInstances[instanceIndex];
  21790. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21791. offset += 16;
  21792. instancesCount++;
  21793. }
  21794. }
  21795. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21796. if (instancesBuffer) {
  21797. instancesBuffer.dispose();
  21798. }
  21799. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21800. this._instancesBuffer = instancesBuffer;
  21801. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21802. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21803. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21804. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21805. }
  21806. else {
  21807. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21808. }
  21809. this._bind(subMesh, effect, fillMode);
  21810. this._draw(subMesh, fillMode, instancesCount);
  21811. engine.unbindInstanceAttributes();
  21812. return this;
  21813. };
  21814. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21815. var scene = this.getScene();
  21816. var engine = scene.getEngine();
  21817. if (hardwareInstancedRendering) {
  21818. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21819. }
  21820. else {
  21821. if (batch.renderSelf[subMesh._id]) {
  21822. // Draw
  21823. if (onBeforeDraw) {
  21824. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21825. }
  21826. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21827. }
  21828. if (batch.visibleInstances[subMesh._id]) {
  21829. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21830. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21831. // World
  21832. var world = instance.getWorldMatrix();
  21833. if (onBeforeDraw) {
  21834. onBeforeDraw(true, world, effectiveMaterial);
  21835. }
  21836. // Draw
  21837. this._draw(subMesh, fillMode);
  21838. }
  21839. }
  21840. }
  21841. return this;
  21842. };
  21843. /**
  21844. * Triggers the draw call for the mesh.
  21845. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21846. * Returns the Mesh.
  21847. */
  21848. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21849. this.checkOcclusionQuery();
  21850. if (this._isOccluded) {
  21851. return;
  21852. }
  21853. var scene = this.getScene();
  21854. // Managing instances
  21855. var batch = this._getInstancesRenderList(subMesh._id);
  21856. if (batch.mustReturn) {
  21857. return this;
  21858. }
  21859. // Checking geometry state
  21860. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21861. return this;
  21862. }
  21863. var callbackIndex;
  21864. this.onBeforeRenderObservable.notifyObservers(this);
  21865. var engine = scene.getEngine();
  21866. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21867. // Material
  21868. var effectiveMaterial = subMesh.getMaterial();
  21869. if (!effectiveMaterial) {
  21870. return this;
  21871. }
  21872. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21873. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21874. return this;
  21875. }
  21876. }
  21877. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21878. return this;
  21879. }
  21880. // Alpha mode
  21881. if (enableAlphaMode) {
  21882. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21883. }
  21884. // Outline - step 1
  21885. var savedDepthWrite = engine.getDepthWrite();
  21886. if (this.renderOutline) {
  21887. engine.setDepthWrite(false);
  21888. scene.getOutlineRenderer().render(subMesh, batch);
  21889. engine.setDepthWrite(savedDepthWrite);
  21890. }
  21891. var effect;
  21892. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21893. effect = subMesh.effect;
  21894. }
  21895. else {
  21896. effect = effectiveMaterial.getEffect();
  21897. }
  21898. effectiveMaterial._preBind(effect);
  21899. // Bind
  21900. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21901. if (!hardwareInstancedRendering) {
  21902. this._bind(subMesh, effect, fillMode);
  21903. }
  21904. var world = this.getWorldMatrix();
  21905. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21906. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21907. }
  21908. else {
  21909. effectiveMaterial.bind(world, this);
  21910. }
  21911. // Draw
  21912. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21913. // Unbind
  21914. effectiveMaterial.unbind();
  21915. // Outline - step 2
  21916. if (this.renderOutline && savedDepthWrite) {
  21917. engine.setDepthWrite(true);
  21918. engine.setColorWrite(false);
  21919. scene.getOutlineRenderer().render(subMesh, batch);
  21920. engine.setColorWrite(true);
  21921. }
  21922. // Overlay
  21923. if (this.renderOverlay) {
  21924. var currentMode = engine.getAlphaMode();
  21925. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21926. scene.getOutlineRenderer().render(subMesh, batch, true);
  21927. engine.setAlphaMode(currentMode);
  21928. }
  21929. this.onAfterRenderObservable.notifyObservers(this);
  21930. return this;
  21931. };
  21932. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21933. if (isInstance) {
  21934. effectiveMaterial.bindOnlyWorldMatrix(world);
  21935. }
  21936. return this;
  21937. };
  21938. /**
  21939. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21940. */
  21941. Mesh.prototype.getEmittedParticleSystems = function () {
  21942. var results = new Array();
  21943. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21944. var particleSystem = this.getScene().particleSystems[index];
  21945. if (particleSystem.emitter === this) {
  21946. results.push(particleSystem);
  21947. }
  21948. }
  21949. return results;
  21950. };
  21951. /**
  21952. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21953. */
  21954. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21955. var results = new Array();
  21956. var descendants = this.getDescendants();
  21957. descendants.push(this);
  21958. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21959. var particleSystem = this.getScene().particleSystems[index];
  21960. var emitter = particleSystem.emitter;
  21961. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21962. results.push(particleSystem);
  21963. }
  21964. }
  21965. return results;
  21966. };
  21967. Mesh.prototype._checkDelayState = function () {
  21968. var scene = this.getScene();
  21969. if (this._geometry) {
  21970. this._geometry.load(scene);
  21971. }
  21972. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21973. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21974. this._queueLoad(this, scene);
  21975. }
  21976. return this;
  21977. };
  21978. Mesh.prototype._queueLoad = function (mesh, scene) {
  21979. var _this = this;
  21980. scene._addPendingData(mesh);
  21981. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21982. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21983. if (data instanceof ArrayBuffer) {
  21984. _this._delayLoadingFunction(data, _this);
  21985. }
  21986. else {
  21987. _this._delayLoadingFunction(JSON.parse(data), _this);
  21988. }
  21989. _this.instances.forEach(function (instance) {
  21990. instance._syncSubMeshes();
  21991. });
  21992. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21993. scene._removePendingData(_this);
  21994. }, function () { }, scene.database, getBinaryData);
  21995. return this;
  21996. };
  21997. /**
  21998. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21999. */
  22000. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22001. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22002. return false;
  22003. }
  22004. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22005. return false;
  22006. }
  22007. this._checkDelayState();
  22008. return true;
  22009. };
  22010. /**
  22011. * Sets the mesh material by the material or multiMaterial `id` property.
  22012. * The material `id` is a string identifying the material or the multiMaterial.
  22013. * This method returns the Mesh.
  22014. */
  22015. Mesh.prototype.setMaterialByID = function (id) {
  22016. var materials = this.getScene().materials;
  22017. var index;
  22018. for (index = materials.length - 1; index > -1; index--) {
  22019. if (materials[index].id === id) {
  22020. this.material = materials[index];
  22021. return this;
  22022. }
  22023. }
  22024. // Multi
  22025. var multiMaterials = this.getScene().multiMaterials;
  22026. for (index = multiMaterials.length - 1; index > -1; index--) {
  22027. if (multiMaterials[index].id === id) {
  22028. this.material = multiMaterials[index];
  22029. return this;
  22030. }
  22031. }
  22032. return this;
  22033. };
  22034. /**
  22035. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22036. */
  22037. Mesh.prototype.getAnimatables = function () {
  22038. var results = [];
  22039. if (this.material) {
  22040. results.push(this.material);
  22041. }
  22042. if (this.skeleton) {
  22043. results.push(this.skeleton);
  22044. }
  22045. return results;
  22046. };
  22047. /**
  22048. * Modifies the mesh geometry according to the passed transformation matrix.
  22049. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22050. * The mesh normals are modified accordingly the same transformation.
  22051. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22052. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22053. * Returns the Mesh.
  22054. */
  22055. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22056. // Position
  22057. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22058. return this;
  22059. }
  22060. var submeshes = this.subMeshes.splice(0);
  22061. this._resetPointsArrayCache();
  22062. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22063. var temp = [];
  22064. var index;
  22065. for (index = 0; index < data.length; index += 3) {
  22066. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22067. }
  22068. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22069. // Normals
  22070. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22071. return this;
  22072. }
  22073. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22074. temp = [];
  22075. for (index = 0; index < data.length; index += 3) {
  22076. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22077. }
  22078. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22079. // flip faces?
  22080. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22081. this.flipFaces();
  22082. }
  22083. // Restore submeshes
  22084. this.releaseSubMeshes();
  22085. this.subMeshes = submeshes;
  22086. return this;
  22087. };
  22088. /**
  22089. * Modifies the mesh geometry according to its own current World Matrix.
  22090. * The mesh World Matrix is then reset.
  22091. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22092. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22093. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22094. * Returns the Mesh.
  22095. */
  22096. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22097. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22098. this.scaling.copyFromFloats(1, 1, 1);
  22099. this.position.copyFromFloats(0, 0, 0);
  22100. this.rotation.copyFromFloats(0, 0, 0);
  22101. //only if quaternion is already set
  22102. if (this.rotationQuaternion) {
  22103. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22104. }
  22105. this._worldMatrix = BABYLON.Matrix.Identity();
  22106. return this;
  22107. };
  22108. Object.defineProperty(Mesh.prototype, "_positions", {
  22109. // Cache
  22110. get: function () {
  22111. if (this._geometry) {
  22112. return this._geometry._positions;
  22113. }
  22114. return null;
  22115. },
  22116. enumerable: true,
  22117. configurable: true
  22118. });
  22119. Mesh.prototype._resetPointsArrayCache = function () {
  22120. if (this._geometry) {
  22121. this._geometry._resetPointsArrayCache();
  22122. }
  22123. return this;
  22124. };
  22125. Mesh.prototype._generatePointsArray = function () {
  22126. if (this._geometry) {
  22127. return this._geometry._generatePointsArray();
  22128. }
  22129. return false;
  22130. };
  22131. /**
  22132. * Returns a new Mesh object generated from the current mesh properties.
  22133. * This method must not get confused with createInstance().
  22134. * The parameter `name` is a string, the name given to the new mesh.
  22135. * The optional parameter `newParent` can be any Node object (default `null`).
  22136. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22137. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  22138. */
  22139. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22140. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22141. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22142. };
  22143. /**
  22144. * Disposes the mesh.
  22145. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22146. */
  22147. Mesh.prototype.dispose = function (doNotRecurse) {
  22148. var _this = this;
  22149. this.morphTargetManager = undefined;
  22150. if (this._geometry) {
  22151. this._geometry.releaseForMesh(this, true);
  22152. }
  22153. // Sources
  22154. var meshes = this.getScene().meshes;
  22155. meshes.forEach(function (mesh) {
  22156. if (mesh._source && mesh._source === _this) {
  22157. mesh._source = null;
  22158. }
  22159. });
  22160. this._source = null;
  22161. // Instances
  22162. if (this._instancesBuffer) {
  22163. this._instancesBuffer.dispose();
  22164. this._instancesBuffer = null;
  22165. }
  22166. while (this.instances.length) {
  22167. this.instances[0].dispose();
  22168. }
  22169. // Highlight layers.
  22170. var highlightLayers = this.getScene().highlightLayers;
  22171. for (var i = 0; i < highlightLayers.length; i++) {
  22172. var highlightLayer = highlightLayers[i];
  22173. if (highlightLayer) {
  22174. highlightLayer.removeMesh(this);
  22175. highlightLayer.removeExcludedMesh(this);
  22176. }
  22177. }
  22178. _super.prototype.dispose.call(this, doNotRecurse);
  22179. };
  22180. /**
  22181. * Modifies the mesh geometry according to a displacement map.
  22182. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  22183. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22184. * This method returns nothing.
  22185. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22186. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22187. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  22188. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22189. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22190. *
  22191. * Returns the Mesh.
  22192. */
  22193. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22194. var _this = this;
  22195. var scene = this.getScene();
  22196. var onload = function (img) {
  22197. // Getting height map data
  22198. var canvas = document.createElement("canvas");
  22199. var context = canvas.getContext("2d");
  22200. var heightMapWidth = img.width;
  22201. var heightMapHeight = img.height;
  22202. canvas.width = heightMapWidth;
  22203. canvas.height = heightMapHeight;
  22204. context.drawImage(img, 0, 0);
  22205. // Create VertexData from map data
  22206. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22207. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22208. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22209. //execute success callback, if set
  22210. if (onSuccess) {
  22211. onSuccess(_this);
  22212. }
  22213. };
  22214. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22215. return this;
  22216. };
  22217. /**
  22218. * Modifies the mesh geometry according to a displacementMap buffer.
  22219. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  22220. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22221. * This method returns nothing.
  22222. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  22223. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22224. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22225. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22226. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22227. *
  22228. * Returns the Mesh.
  22229. */
  22230. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22231. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22232. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22233. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22234. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22235. return this;
  22236. }
  22237. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22238. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22239. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22240. var position = BABYLON.Vector3.Zero();
  22241. var normal = BABYLON.Vector3.Zero();
  22242. var uv = BABYLON.Vector2.Zero();
  22243. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22244. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22245. for (var index = 0; index < positions.length; index += 3) {
  22246. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22247. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22248. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22249. // Compute height
  22250. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22251. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22252. var pos = (u + v * heightMapWidth) * 4;
  22253. var r = buffer[pos] / 255.0;
  22254. var g = buffer[pos + 1] / 255.0;
  22255. var b = buffer[pos + 2] / 255.0;
  22256. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22257. normal.normalize();
  22258. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22259. position = position.add(normal);
  22260. position.toArray(positions, index);
  22261. }
  22262. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22263. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22264. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22265. return this;
  22266. };
  22267. /**
  22268. * Modify the mesh to get a flat shading rendering.
  22269. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22270. * This method returns the Mesh.
  22271. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22272. */
  22273. Mesh.prototype.convertToFlatShadedMesh = function () {
  22274. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22275. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22276. var kinds = this.getVerticesDataKinds();
  22277. var vbs = [];
  22278. var data = [];
  22279. var newdata = [];
  22280. var updatableNormals = false;
  22281. var kindIndex;
  22282. var kind;
  22283. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22284. kind = kinds[kindIndex];
  22285. var vertexBuffer = this.getVertexBuffer(kind);
  22286. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22287. updatableNormals = vertexBuffer.isUpdatable();
  22288. kinds.splice(kindIndex, 1);
  22289. kindIndex--;
  22290. continue;
  22291. }
  22292. vbs[kind] = vertexBuffer;
  22293. data[kind] = vbs[kind].getData();
  22294. newdata[kind] = [];
  22295. }
  22296. // Save previous submeshes
  22297. var previousSubmeshes = this.subMeshes.slice(0);
  22298. var indices = this.getIndices();
  22299. var totalIndices = this.getTotalIndices();
  22300. // Generating unique vertices per face
  22301. var index;
  22302. for (index = 0; index < totalIndices; index++) {
  22303. var vertexIndex = indices[index];
  22304. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22305. kind = kinds[kindIndex];
  22306. var stride = vbs[kind].getStrideSize();
  22307. for (var offset = 0; offset < stride; offset++) {
  22308. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22309. }
  22310. }
  22311. }
  22312. // Updating faces & normal
  22313. var normals = [];
  22314. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22315. for (index = 0; index < totalIndices; index += 3) {
  22316. indices[index] = index;
  22317. indices[index + 1] = index + 1;
  22318. indices[index + 2] = index + 2;
  22319. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22320. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22321. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22322. var p1p2 = p1.subtract(p2);
  22323. var p3p2 = p3.subtract(p2);
  22324. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22325. // Store same normals for every vertex
  22326. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22327. normals.push(normal.x);
  22328. normals.push(normal.y);
  22329. normals.push(normal.z);
  22330. }
  22331. }
  22332. this.setIndices(indices);
  22333. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22334. // Updating vertex buffers
  22335. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22336. kind = kinds[kindIndex];
  22337. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22338. }
  22339. // Updating submeshes
  22340. this.releaseSubMeshes();
  22341. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22342. var previousOne = previousSubmeshes[submeshIndex];
  22343. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22344. }
  22345. this.synchronizeInstances();
  22346. return this;
  22347. };
  22348. /**
  22349. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22350. * In other words, more vertices, no more indices and a single bigger VBO.
  22351. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22352. * Returns the Mesh.
  22353. */
  22354. Mesh.prototype.convertToUnIndexedMesh = function () {
  22355. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22356. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22357. var kinds = this.getVerticesDataKinds();
  22358. var vbs = [];
  22359. var data = [];
  22360. var newdata = [];
  22361. var updatableNormals = false;
  22362. var kindIndex;
  22363. var kind;
  22364. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22365. kind = kinds[kindIndex];
  22366. var vertexBuffer = this.getVertexBuffer(kind);
  22367. vbs[kind] = vertexBuffer;
  22368. data[kind] = vbs[kind].getData();
  22369. newdata[kind] = [];
  22370. }
  22371. // Save previous submeshes
  22372. var previousSubmeshes = this.subMeshes.slice(0);
  22373. var indices = this.getIndices();
  22374. var totalIndices = this.getTotalIndices();
  22375. // Generating unique vertices per face
  22376. var index;
  22377. for (index = 0; index < totalIndices; index++) {
  22378. var vertexIndex = indices[index];
  22379. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22380. kind = kinds[kindIndex];
  22381. var stride = vbs[kind].getStrideSize();
  22382. for (var offset = 0; offset < stride; offset++) {
  22383. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22384. }
  22385. }
  22386. }
  22387. // Updating indices
  22388. for (index = 0; index < totalIndices; index += 3) {
  22389. indices[index] = index;
  22390. indices[index + 1] = index + 1;
  22391. indices[index + 2] = index + 2;
  22392. }
  22393. this.setIndices(indices);
  22394. // Updating vertex buffers
  22395. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22396. kind = kinds[kindIndex];
  22397. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22398. }
  22399. // Updating submeshes
  22400. this.releaseSubMeshes();
  22401. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22402. var previousOne = previousSubmeshes[submeshIndex];
  22403. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22404. }
  22405. this._unIndexed = true;
  22406. this.synchronizeInstances();
  22407. return this;
  22408. };
  22409. /**
  22410. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22411. * This method returns the Mesh.
  22412. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22413. */
  22414. Mesh.prototype.flipFaces = function (flipNormals) {
  22415. if (flipNormals === void 0) { flipNormals = false; }
  22416. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22417. var i;
  22418. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22419. for (i = 0; i < vertex_data.normals.length; i++) {
  22420. vertex_data.normals[i] *= -1;
  22421. }
  22422. }
  22423. var temp;
  22424. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22425. // reassign indices
  22426. temp = vertex_data.indices[i + 1];
  22427. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22428. vertex_data.indices[i + 2] = temp;
  22429. }
  22430. vertex_data.applyToMesh(this);
  22431. return this;
  22432. };
  22433. // Instances
  22434. /**
  22435. * Creates a new InstancedMesh object from the mesh model.
  22436. * An instance shares the same properties and the same material than its model.
  22437. * Only these properties of each instance can then be set individually :
  22438. * - position
  22439. * - rotation
  22440. * - rotationQuaternion
  22441. * - setPivotMatrix
  22442. * - scaling
  22443. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22444. * Warning : this method is not supported for Line mesh and LineSystem
  22445. */
  22446. Mesh.prototype.createInstance = function (name) {
  22447. return new BABYLON.InstancedMesh(name, this);
  22448. };
  22449. /**
  22450. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22451. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22452. * This method returns the Mesh.
  22453. */
  22454. Mesh.prototype.synchronizeInstances = function () {
  22455. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22456. var instance = this.instances[instanceIndex];
  22457. instance._syncSubMeshes();
  22458. }
  22459. return this;
  22460. };
  22461. /**
  22462. * Simplify the mesh according to the given array of settings.
  22463. * Function will return immediately and will simplify async. It returns the Mesh.
  22464. * @param settings a collection of simplification settings.
  22465. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22466. * @param type the type of simplification to run.
  22467. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22468. */
  22469. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22470. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22471. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22472. this.getScene().simplificationQueue.addTask({
  22473. settings: settings,
  22474. parallelProcessing: parallelProcessing,
  22475. mesh: this,
  22476. simplificationType: simplificationType,
  22477. successCallback: successCallback
  22478. });
  22479. return this;
  22480. };
  22481. /**
  22482. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22483. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22484. * This should be used together with the simplification to avoid disappearing triangles.
  22485. * Returns the Mesh.
  22486. * @param successCallback an optional success callback to be called after the optimization finished.
  22487. */
  22488. Mesh.prototype.optimizeIndices = function (successCallback) {
  22489. var _this = this;
  22490. var indices = this.getIndices();
  22491. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22492. var vectorPositions = [];
  22493. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22494. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22495. }
  22496. var dupes = [];
  22497. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22498. var realPos = vectorPositions.length - 1 - iteration;
  22499. var testedPosition = vectorPositions[realPos];
  22500. for (var j = 0; j < realPos; ++j) {
  22501. var againstPosition = vectorPositions[j];
  22502. if (testedPosition.equals(againstPosition)) {
  22503. dupes[realPos] = j;
  22504. break;
  22505. }
  22506. }
  22507. }, function () {
  22508. for (var i = 0; i < indices.length; ++i) {
  22509. indices[i] = dupes[indices[i]] || indices[i];
  22510. }
  22511. //indices are now reordered
  22512. var originalSubMeshes = _this.subMeshes.slice(0);
  22513. _this.setIndices(indices);
  22514. _this.subMeshes = originalSubMeshes;
  22515. if (successCallback) {
  22516. successCallback(_this);
  22517. }
  22518. });
  22519. return this;
  22520. };
  22521. Mesh.prototype.serialize = function (serializationObject) {
  22522. serializationObject.name = this.name;
  22523. serializationObject.id = this.id;
  22524. serializationObject.type = this.getClassName();
  22525. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22526. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22527. }
  22528. serializationObject.position = this.position.asArray();
  22529. if (this.rotationQuaternion) {
  22530. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22531. }
  22532. else if (this.rotation) {
  22533. serializationObject.rotation = this.rotation.asArray();
  22534. }
  22535. serializationObject.scaling = this.scaling.asArray();
  22536. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22537. serializationObject.isEnabled = this.isEnabled();
  22538. serializationObject.isVisible = this.isVisible;
  22539. serializationObject.infiniteDistance = this.infiniteDistance;
  22540. serializationObject.pickable = this.isPickable;
  22541. serializationObject.receiveShadows = this.receiveShadows;
  22542. serializationObject.billboardMode = this.billboardMode;
  22543. serializationObject.visibility = this.visibility;
  22544. serializationObject.checkCollisions = this.checkCollisions;
  22545. serializationObject.isBlocker = this.isBlocker;
  22546. // Parent
  22547. if (this.parent) {
  22548. serializationObject.parentId = this.parent.id;
  22549. }
  22550. // Geometry
  22551. var geometry = this._geometry;
  22552. if (geometry) {
  22553. var geometryId = geometry.id;
  22554. serializationObject.geometryId = geometryId;
  22555. // SubMeshes
  22556. serializationObject.subMeshes = [];
  22557. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22558. var subMesh = this.subMeshes[subIndex];
  22559. serializationObject.subMeshes.push({
  22560. materialIndex: subMesh.materialIndex,
  22561. verticesStart: subMesh.verticesStart,
  22562. verticesCount: subMesh.verticesCount,
  22563. indexStart: subMesh.indexStart,
  22564. indexCount: subMesh.indexCount
  22565. });
  22566. }
  22567. }
  22568. // Material
  22569. if (this.material) {
  22570. serializationObject.materialId = this.material.id;
  22571. }
  22572. else {
  22573. this.material = null;
  22574. }
  22575. // Morph targets
  22576. if (this.morphTargetManager) {
  22577. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22578. }
  22579. // Skeleton
  22580. if (this.skeleton) {
  22581. serializationObject.skeletonId = this.skeleton.id;
  22582. }
  22583. // Physics
  22584. //TODO implement correct serialization for physics impostors.
  22585. if (this.getPhysicsImpostor()) {
  22586. var impostor = this.getPhysicsImpostor();
  22587. serializationObject.physicsMass = impostor.getParam("mass");
  22588. serializationObject.physicsFriction = impostor.getParam("friction");
  22589. serializationObject.physicsRestitution = impostor.getParam("mass");
  22590. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22591. }
  22592. // Metadata
  22593. if (this.metadata) {
  22594. serializationObject.metadata = this.metadata;
  22595. }
  22596. // Instances
  22597. serializationObject.instances = [];
  22598. for (var index = 0; index < this.instances.length; index++) {
  22599. var instance = this.instances[index];
  22600. var serializationInstance = {
  22601. name: instance.name,
  22602. position: instance.position.asArray(),
  22603. scaling: instance.scaling.asArray()
  22604. };
  22605. if (instance.rotationQuaternion) {
  22606. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22607. }
  22608. else if (instance.rotation) {
  22609. serializationInstance.rotation = instance.rotation.asArray();
  22610. }
  22611. serializationObject.instances.push(serializationInstance);
  22612. // Animations
  22613. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22614. serializationInstance.ranges = instance.serializeAnimationRanges();
  22615. }
  22616. //
  22617. // Animations
  22618. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22619. serializationObject.ranges = this.serializeAnimationRanges();
  22620. // Layer mask
  22621. serializationObject.layerMask = this.layerMask;
  22622. // Alpha
  22623. serializationObject.alphaIndex = this.alphaIndex;
  22624. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22625. // Overlay
  22626. serializationObject.overlayAlpha = this.overlayAlpha;
  22627. serializationObject.overlayColor = this.overlayColor.asArray();
  22628. serializationObject.renderOverlay = this.renderOverlay;
  22629. // Fog
  22630. serializationObject.applyFog = this.applyFog;
  22631. // Action Manager
  22632. if (this.actionManager) {
  22633. serializationObject.actions = this.actionManager.serialize(this.name);
  22634. }
  22635. };
  22636. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22637. if (!this.geometry) {
  22638. return;
  22639. }
  22640. this._markSubMeshesAsAttributesDirty();
  22641. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22642. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22643. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22644. this.morphTargetManager = undefined;
  22645. return;
  22646. }
  22647. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22648. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22649. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22650. if (morphTarget.hasNormals) {
  22651. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22652. }
  22653. if (morphTarget.hasTangents) {
  22654. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22655. }
  22656. }
  22657. }
  22658. else {
  22659. var index = 0;
  22660. // Positions
  22661. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22662. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22663. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22664. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22665. }
  22666. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22667. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22668. }
  22669. index++;
  22670. }
  22671. }
  22672. };
  22673. // Statics
  22674. /**
  22675. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22676. * The parameter `parsedMesh` is the mesh to be copied.
  22677. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22678. */
  22679. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22680. var mesh;
  22681. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22682. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22683. }
  22684. else {
  22685. mesh = new Mesh(parsedMesh.name, scene);
  22686. }
  22687. mesh.id = parsedMesh.id;
  22688. if (BABYLON.Tags) {
  22689. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22690. }
  22691. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22692. if (parsedMesh.metadata !== undefined) {
  22693. mesh.metadata = parsedMesh.metadata;
  22694. }
  22695. if (parsedMesh.rotationQuaternion) {
  22696. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22697. }
  22698. else if (parsedMesh.rotation) {
  22699. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22700. }
  22701. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22702. if (parsedMesh.localMatrix) {
  22703. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22704. }
  22705. else if (parsedMesh.pivotMatrix) {
  22706. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22707. }
  22708. mesh.setEnabled(parsedMesh.isEnabled);
  22709. mesh.isVisible = parsedMesh.isVisible;
  22710. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22711. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22712. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22713. if (parsedMesh.applyFog !== undefined) {
  22714. mesh.applyFog = parsedMesh.applyFog;
  22715. }
  22716. if (parsedMesh.pickable !== undefined) {
  22717. mesh.isPickable = parsedMesh.pickable;
  22718. }
  22719. if (parsedMesh.alphaIndex !== undefined) {
  22720. mesh.alphaIndex = parsedMesh.alphaIndex;
  22721. }
  22722. mesh.receiveShadows = parsedMesh.receiveShadows;
  22723. mesh.billboardMode = parsedMesh.billboardMode;
  22724. if (parsedMesh.visibility !== undefined) {
  22725. mesh.visibility = parsedMesh.visibility;
  22726. }
  22727. mesh.checkCollisions = parsedMesh.checkCollisions;
  22728. if (parsedMesh.isBlocker !== undefined) {
  22729. mesh.isBlocker = parsedMesh.isBlocker;
  22730. }
  22731. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22732. // freezeWorldMatrix
  22733. if (parsedMesh.freezeWorldMatrix) {
  22734. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22735. }
  22736. // Parent
  22737. if (parsedMesh.parentId) {
  22738. mesh._waitingParentId = parsedMesh.parentId;
  22739. }
  22740. // Actions
  22741. if (parsedMesh.actions !== undefined) {
  22742. mesh._waitingActions = parsedMesh.actions;
  22743. }
  22744. // Overlay
  22745. if (parsedMesh.overlayAlpha !== undefined) {
  22746. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22747. }
  22748. if (parsedMesh.overlayColor !== undefined) {
  22749. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22750. }
  22751. if (parsedMesh.renderOverlay !== undefined) {
  22752. mesh.renderOverlay = parsedMesh.renderOverlay;
  22753. }
  22754. // Geometry
  22755. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22756. if (parsedMesh.delayLoadingFile) {
  22757. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22758. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22759. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22760. if (parsedMesh._binaryInfo) {
  22761. mesh._binaryInfo = parsedMesh._binaryInfo;
  22762. }
  22763. mesh._delayInfo = [];
  22764. if (parsedMesh.hasUVs) {
  22765. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22766. }
  22767. if (parsedMesh.hasUVs2) {
  22768. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22769. }
  22770. if (parsedMesh.hasUVs3) {
  22771. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22772. }
  22773. if (parsedMesh.hasUVs4) {
  22774. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22775. }
  22776. if (parsedMesh.hasUVs5) {
  22777. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22778. }
  22779. if (parsedMesh.hasUVs6) {
  22780. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22781. }
  22782. if (parsedMesh.hasColors) {
  22783. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22784. }
  22785. if (parsedMesh.hasMatricesIndices) {
  22786. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22787. }
  22788. if (parsedMesh.hasMatricesWeights) {
  22789. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22790. }
  22791. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22792. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22793. mesh._checkDelayState();
  22794. }
  22795. }
  22796. else {
  22797. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22798. }
  22799. // Material
  22800. if (parsedMesh.materialId) {
  22801. mesh.setMaterialByID(parsedMesh.materialId);
  22802. }
  22803. else {
  22804. mesh.material = null;
  22805. }
  22806. // Morph targets
  22807. if (parsedMesh.morphTargetManagerId > -1) {
  22808. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22809. }
  22810. // Skeleton
  22811. if (parsedMesh.skeletonId > -1) {
  22812. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22813. if (parsedMesh.numBoneInfluencers) {
  22814. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22815. }
  22816. }
  22817. // Animations
  22818. if (parsedMesh.animations) {
  22819. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22820. var parsedAnimation = parsedMesh.animations[animationIndex];
  22821. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22822. }
  22823. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22824. }
  22825. if (parsedMesh.autoAnimate) {
  22826. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22827. }
  22828. // Layer Mask
  22829. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22830. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22831. }
  22832. else {
  22833. mesh.layerMask = 0x0FFFFFFF;
  22834. }
  22835. // Physics
  22836. if (parsedMesh.physicsImpostor) {
  22837. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22838. mass: parsedMesh.physicsMass,
  22839. friction: parsedMesh.physicsFriction,
  22840. restitution: parsedMesh.physicsRestitution
  22841. }, scene);
  22842. }
  22843. // Instances
  22844. if (parsedMesh.instances) {
  22845. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22846. var parsedInstance = parsedMesh.instances[index];
  22847. var instance = mesh.createInstance(parsedInstance.name);
  22848. if (BABYLON.Tags) {
  22849. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22850. }
  22851. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22852. if (parsedInstance.parentId) {
  22853. instance._waitingParentId = parsedInstance.parentId;
  22854. }
  22855. if (parsedInstance.rotationQuaternion) {
  22856. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22857. }
  22858. else if (parsedInstance.rotation) {
  22859. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22860. }
  22861. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22862. instance.checkCollisions = mesh.checkCollisions;
  22863. if (parsedMesh.animations) {
  22864. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22865. parsedAnimation = parsedMesh.animations[animationIndex];
  22866. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22867. }
  22868. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22869. }
  22870. }
  22871. }
  22872. return mesh;
  22873. };
  22874. /**
  22875. * Creates a ribbon mesh.
  22876. * Please consider using the same method from the MeshBuilder class instead.
  22877. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  22878. *
  22879. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22880. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22881. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22882. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22883. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  22884. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  22885. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  22886. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22887. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22888. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22889. */
  22890. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22891. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22892. pathArray: pathArray,
  22893. closeArray: closeArray,
  22894. closePath: closePath,
  22895. offset: offset,
  22896. updatable: updatable,
  22897. sideOrientation: sideOrientation,
  22898. instance: instance
  22899. }, scene);
  22900. };
  22901. /**
  22902. * Creates a plane polygonal mesh. By default, this is a disc.
  22903. * Please consider using the same method from the MeshBuilder class instead.
  22904. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22905. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  22906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22907. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22909. */
  22910. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22911. var options = {
  22912. radius: radius,
  22913. tessellation: tessellation,
  22914. sideOrientation: sideOrientation,
  22915. updatable: updatable
  22916. };
  22917. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22918. };
  22919. /**
  22920. * Creates a box mesh.
  22921. * Please consider using the same method from the MeshBuilder class instead.
  22922. * The parameter `size` sets the size (float) of each box side (default 1).
  22923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22926. */
  22927. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22928. var options = {
  22929. size: size,
  22930. sideOrientation: sideOrientation,
  22931. updatable: updatable
  22932. };
  22933. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22934. };
  22935. /**
  22936. * Creates a sphere mesh.
  22937. * Please consider using the same method from the MeshBuilder class instead.
  22938. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22939. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22943. */
  22944. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22945. var options = {
  22946. segments: segments,
  22947. diameterX: diameter,
  22948. diameterY: diameter,
  22949. diameterZ: diameter,
  22950. sideOrientation: sideOrientation,
  22951. updatable: updatable
  22952. };
  22953. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22954. };
  22955. /**
  22956. * Creates a cylinder or a cone mesh.
  22957. * Please consider using the same method from the MeshBuilder class instead.
  22958. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22959. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22960. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  22961. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22962. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22963. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22964. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22965. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22966. */
  22967. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22968. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22969. if (scene !== undefined) {
  22970. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22971. updatable = scene;
  22972. }
  22973. scene = subdivisions;
  22974. subdivisions = 1;
  22975. }
  22976. var options = {
  22977. height: height,
  22978. diameterTop: diameterTop,
  22979. diameterBottom: diameterBottom,
  22980. tessellation: tessellation,
  22981. subdivisions: subdivisions,
  22982. sideOrientation: sideOrientation,
  22983. updatable: updatable
  22984. };
  22985. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22986. };
  22987. // Torus (Code from SharpDX.org)
  22988. /**
  22989. * Creates a torus mesh.
  22990. * Please consider using the same method from the MeshBuilder class instead.
  22991. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22992. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22993. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22997. */
  22998. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22999. var options = {
  23000. diameter: diameter,
  23001. thickness: thickness,
  23002. tessellation: tessellation,
  23003. sideOrientation: sideOrientation,
  23004. updatable: updatable
  23005. };
  23006. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23007. };
  23008. /**
  23009. * Creates a torus knot mesh.
  23010. * Please consider using the same method from the MeshBuilder class instead.
  23011. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23012. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23013. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23014. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23018. */
  23019. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23020. var options = {
  23021. radius: radius,
  23022. tube: tube,
  23023. radialSegments: radialSegments,
  23024. tubularSegments: tubularSegments,
  23025. p: p,
  23026. q: q,
  23027. sideOrientation: sideOrientation,
  23028. updatable: updatable
  23029. };
  23030. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23031. };
  23032. /**
  23033. * Creates a line mesh.
  23034. * Please consider using the same method from the MeshBuilder class instead.
  23035. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  23036. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23037. * The parameter `points` is an array successive Vector3.
  23038. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  23039. * When updating an instance, remember that only point positions can change, not the number of points.
  23040. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23041. */
  23042. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23043. var options = {
  23044. points: points,
  23045. updatable: updatable,
  23046. instance: instance
  23047. };
  23048. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23049. };
  23050. /**
  23051. * Creates a dashed line mesh.
  23052. * Please consider using the same method from the MeshBuilder class instead.
  23053. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  23054. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23055. * The parameter `points` is an array successive Vector3.
  23056. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23057. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23058. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23059. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  23060. * When updating an instance, remember that only point positions can change, not the number of points.
  23061. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23062. */
  23063. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23064. var options = {
  23065. points: points,
  23066. dashSize: dashSize,
  23067. gapSize: gapSize,
  23068. dashNb: dashNb,
  23069. updatable: updatable,
  23070. instance: instance
  23071. };
  23072. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23073. };
  23074. /**
  23075. * Creates a polygon mesh.
  23076. * Please consider using the same method from the MeshBuilder class instead.
  23077. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23078. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  23079. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23081. * Remember you can only change the shape positions, not their number when updating a polygon.
  23082. */
  23083. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23084. var options = {
  23085. shape: shape,
  23086. holes: holes,
  23087. updatable: updatable,
  23088. sideOrientation: sideOrientation
  23089. };
  23090. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23091. };
  23092. /**
  23093. * Creates an extruded polygon mesh, with depth in the Y direction.
  23094. * Please consider using the same method from the MeshBuilder class instead.
  23095. */
  23096. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23097. var options = {
  23098. shape: shape,
  23099. holes: holes,
  23100. depth: depth,
  23101. updatable: updatable,
  23102. sideOrientation: sideOrientation
  23103. };
  23104. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23105. };
  23106. /**
  23107. * Creates an extruded shape mesh.
  23108. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  23109. * Please consider using the same method from the MeshBuilder class instead.
  23110. *
  23111. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23112. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  23113. * extruded along the Z axis.
  23114. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23115. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  23116. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23117. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  23118. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  23119. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23123. */
  23124. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23125. var options = {
  23126. shape: shape,
  23127. path: path,
  23128. scale: scale,
  23129. rotation: rotation,
  23130. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23131. sideOrientation: sideOrientation,
  23132. instance: instance,
  23133. updatable: updatable
  23134. };
  23135. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23136. };
  23137. /**
  23138. * Creates an custom extruded shape mesh.
  23139. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  23140. * Please consider using the same method from the MeshBuilder class instead.
  23141. *
  23142. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23143. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  23144. * extruded along the Z axis.
  23145. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23146. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  23147. * and the distance of this point from the begining of the path :
  23148. * ```javascript
  23149. * var rotationFunction = function(i, distance) {
  23150. * // do things
  23151. * return rotationValue; }
  23152. * ```
  23153. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23154. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  23155. * and the distance of this point from the begining of the path :
  23156. * ```javascript
  23157. * var scaleFunction = function(i, distance) {
  23158. * // do things
  23159. * return scaleValue;}
  23160. * ```
  23161. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23162. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23163. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23164. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  23165. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  23166. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23170. */
  23171. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23172. var options = {
  23173. shape: shape,
  23174. path: path,
  23175. scaleFunction: scaleFunction,
  23176. rotationFunction: rotationFunction,
  23177. ribbonCloseArray: ribbonCloseArray,
  23178. ribbonClosePath: ribbonClosePath,
  23179. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23180. sideOrientation: sideOrientation,
  23181. instance: instance,
  23182. updatable: updatable
  23183. };
  23184. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23185. };
  23186. /**
  23187. * Creates lathe mesh.
  23188. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23189. * Please consider using the same method from the MeshBuilder class instead.
  23190. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  23191. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23192. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23193. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23194. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23195. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23197. */
  23198. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23199. var options = {
  23200. shape: shape,
  23201. radius: radius,
  23202. tessellation: tessellation,
  23203. sideOrientation: sideOrientation,
  23204. updatable: updatable
  23205. };
  23206. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23207. };
  23208. /**
  23209. * Creates a plane mesh.
  23210. * Please consider using the same method from the MeshBuilder class instead.
  23211. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23213. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23215. */
  23216. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23217. var options = {
  23218. size: size,
  23219. width: size,
  23220. height: size,
  23221. sideOrientation: sideOrientation,
  23222. updatable: updatable
  23223. };
  23224. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23225. };
  23226. /**
  23227. * Creates a ground mesh.
  23228. * Please consider using the same method from the MeshBuilder class instead.
  23229. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23230. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23232. */
  23233. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23234. var options = {
  23235. width: width,
  23236. height: height,
  23237. subdivisions: subdivisions,
  23238. updatable: updatable
  23239. };
  23240. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23241. };
  23242. /**
  23243. * Creates a tiled ground mesh.
  23244. * Please consider using the same method from the MeshBuilder class instead.
  23245. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23246. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23247. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23248. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23249. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23250. * numbers of subdivisions on the ground width and height of each tile.
  23251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23252. */
  23253. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23254. var options = {
  23255. xmin: xmin,
  23256. zmin: zmin,
  23257. xmax: xmax,
  23258. zmax: zmax,
  23259. subdivisions: subdivisions,
  23260. precision: precision,
  23261. updatable: updatable
  23262. };
  23263. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23264. };
  23265. /**
  23266. * Creates a ground mesh from a height map.
  23267. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23268. * Please consider using the same method from the MeshBuilder class instead.
  23269. * The parameter `url` sets the URL of the height map image resource.
  23270. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23271. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23272. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23273. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23274. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  23275. * This function is passed the newly built mesh :
  23276. * ```javascript
  23277. * function(mesh) { // do things
  23278. * return; }
  23279. * ```
  23280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23281. */
  23282. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23283. var options = {
  23284. width: width,
  23285. height: height,
  23286. subdivisions: subdivisions,
  23287. minHeight: minHeight,
  23288. maxHeight: maxHeight,
  23289. updatable: updatable,
  23290. onReady: onReady
  23291. };
  23292. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23293. };
  23294. /**
  23295. * Creates a tube mesh.
  23296. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  23297. * Please consider using the same method from the MeshBuilder class instead.
  23298. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23299. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23300. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23301. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23302. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  23303. * It must return a radius value (positive float) :
  23304. * ```javascript
  23305. * var radiusFunction = function(i, distance) {
  23306. * // do things
  23307. * return radius; }
  23308. * ```
  23309. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  23310. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  23311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23314. */
  23315. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23316. var options = {
  23317. path: path,
  23318. radius: radius,
  23319. tessellation: tessellation,
  23320. radiusFunction: radiusFunction,
  23321. arc: 1,
  23322. cap: cap,
  23323. updatable: updatable,
  23324. sideOrientation: sideOrientation,
  23325. instance: instance
  23326. };
  23327. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23328. };
  23329. /**
  23330. * Creates a polyhedron mesh.
  23331. * Please consider using the same method from the MeshBuilder class instead.
  23332. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  23333. * to choose the wanted type.
  23334. * The parameter `size` (positive float, default 1) sets the polygon size.
  23335. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23336. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  23337. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  23338. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  23339. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  23340. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  23341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23344. */
  23345. Mesh.CreatePolyhedron = function (name, options, scene) {
  23346. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23347. };
  23348. /**
  23349. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23350. * Please consider using the same method from the MeshBuilder class instead.
  23351. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23352. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  23353. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23354. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  23355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23356. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23358. */
  23359. Mesh.CreateIcoSphere = function (name, options, scene) {
  23360. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23361. };
  23362. /**
  23363. * Creates a decal mesh.
  23364. * Please consider using the same method from the MeshBuilder class instead.
  23365. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  23366. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23367. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23368. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23369. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23370. */
  23371. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23372. var options = {
  23373. position: position,
  23374. normal: normal,
  23375. size: size,
  23376. angle: angle
  23377. };
  23378. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23379. };
  23380. // Skeletons
  23381. /**
  23382. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23383. */
  23384. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23385. var source;
  23386. if (!this._sourcePositions) {
  23387. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23388. this._sourcePositions = new Float32Array(source);
  23389. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23390. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23391. }
  23392. }
  23393. return this._sourcePositions;
  23394. };
  23395. /**
  23396. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23397. */
  23398. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23399. var source;
  23400. if (!this._sourceNormals) {
  23401. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23402. this._sourceNormals = new Float32Array(source);
  23403. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23404. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23405. }
  23406. }
  23407. return this._sourceNormals;
  23408. };
  23409. /**
  23410. * Updates the vertex buffer by applying transformation from the bones.
  23411. * Returns the Mesh.
  23412. *
  23413. * @param {skeleton} skeleton to apply
  23414. */
  23415. Mesh.prototype.applySkeleton = function (skeleton) {
  23416. if (!this.geometry) {
  23417. return this;
  23418. }
  23419. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23420. return this;
  23421. }
  23422. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23423. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23424. return this;
  23425. }
  23426. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23427. return this;
  23428. }
  23429. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23430. return this;
  23431. }
  23432. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23433. return this;
  23434. }
  23435. if (!this._sourcePositions) {
  23436. var submeshes = this.subMeshes.slice();
  23437. this.setPositionsForCPUSkinning();
  23438. this.subMeshes = submeshes;
  23439. }
  23440. if (!this._sourceNormals) {
  23441. this.setNormalsForCPUSkinning();
  23442. }
  23443. // positionsData checks for not being Float32Array will only pass at most once
  23444. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23445. if (!(positionsData instanceof Float32Array)) {
  23446. positionsData = new Float32Array(positionsData);
  23447. }
  23448. // normalsData checks for not being Float32Array will only pass at most once
  23449. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23450. if (!(normalsData instanceof Float32Array)) {
  23451. normalsData = new Float32Array(normalsData);
  23452. }
  23453. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23454. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23455. var needExtras = this.numBoneInfluencers > 4;
  23456. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23457. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23458. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23459. var tempVector3 = BABYLON.Vector3.Zero();
  23460. var finalMatrix = new BABYLON.Matrix();
  23461. var tempMatrix = new BABYLON.Matrix();
  23462. var matWeightIdx = 0;
  23463. var inf;
  23464. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23465. var weight;
  23466. for (inf = 0; inf < 4; inf++) {
  23467. weight = matricesWeightsData[matWeightIdx + inf];
  23468. if (weight > 0) {
  23469. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23470. finalMatrix.addToSelf(tempMatrix);
  23471. }
  23472. else
  23473. break;
  23474. }
  23475. if (needExtras) {
  23476. for (inf = 0; inf < 4; inf++) {
  23477. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23478. if (weight > 0) {
  23479. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23480. finalMatrix.addToSelf(tempMatrix);
  23481. }
  23482. else
  23483. break;
  23484. }
  23485. }
  23486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23487. tempVector3.toArray(positionsData, index);
  23488. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23489. tempVector3.toArray(normalsData, index);
  23490. finalMatrix.reset();
  23491. }
  23492. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23493. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23494. return this;
  23495. };
  23496. // Tools
  23497. /**
  23498. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23499. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23500. */
  23501. Mesh.MinMax = function (meshes) {
  23502. var minVector = null;
  23503. var maxVector = null;
  23504. meshes.forEach(function (mesh, index, array) {
  23505. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23506. if (!minVector) {
  23507. minVector = boundingBox.minimumWorld;
  23508. maxVector = boundingBox.maximumWorld;
  23509. }
  23510. else {
  23511. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23512. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23513. }
  23514. });
  23515. return {
  23516. min: minVector,
  23517. max: maxVector
  23518. };
  23519. };
  23520. /**
  23521. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23522. */
  23523. Mesh.Center = function (meshesOrMinMaxVector) {
  23524. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23525. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23526. };
  23527. /**
  23528. * Merge the array of meshes into a single mesh for performance reasons.
  23529. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23530. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23531. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23532. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23533. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23534. */
  23535. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23536. if (disposeSource === void 0) { disposeSource = true; }
  23537. var index;
  23538. if (!allow32BitsIndices) {
  23539. var totalVertices = 0;
  23540. // Counting vertices
  23541. for (index = 0; index < meshes.length; index++) {
  23542. if (meshes[index]) {
  23543. totalVertices += meshes[index].getTotalVertices();
  23544. if (totalVertices > 65536) {
  23545. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23546. return null;
  23547. }
  23548. }
  23549. }
  23550. }
  23551. // Merge
  23552. var vertexData;
  23553. var otherVertexData;
  23554. var indiceArray = new Array();
  23555. var source;
  23556. for (index = 0; index < meshes.length; index++) {
  23557. if (meshes[index]) {
  23558. meshes[index].computeWorldMatrix(true);
  23559. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23560. otherVertexData.transform(meshes[index].getWorldMatrix());
  23561. if (vertexData) {
  23562. vertexData.merge(otherVertexData);
  23563. }
  23564. else {
  23565. vertexData = otherVertexData;
  23566. source = meshes[index];
  23567. }
  23568. if (subdivideWithSubMeshes) {
  23569. indiceArray.push(meshes[index].getTotalIndices());
  23570. }
  23571. }
  23572. }
  23573. if (!meshSubclass) {
  23574. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23575. }
  23576. vertexData.applyToMesh(meshSubclass);
  23577. // Setting properties
  23578. meshSubclass.material = source.material;
  23579. meshSubclass.checkCollisions = source.checkCollisions;
  23580. // Cleaning
  23581. if (disposeSource) {
  23582. for (index = 0; index < meshes.length; index++) {
  23583. if (meshes[index]) {
  23584. meshes[index].dispose();
  23585. }
  23586. }
  23587. }
  23588. // Subdivide
  23589. if (subdivideWithSubMeshes) {
  23590. //-- Suppresions du submesh global
  23591. meshSubclass.releaseSubMeshes();
  23592. index = 0;
  23593. var offset = 0;
  23594. //-- aplique la subdivision en fonction du tableau d'indices
  23595. while (index < indiceArray.length) {
  23596. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23597. offset += indiceArray[index];
  23598. index++;
  23599. }
  23600. }
  23601. return meshSubclass;
  23602. };
  23603. // Consts
  23604. Mesh._FRONTSIDE = 0;
  23605. Mesh._BACKSIDE = 1;
  23606. Mesh._DOUBLESIDE = 2;
  23607. Mesh._DEFAULTSIDE = 0;
  23608. Mesh._NO_CAP = 0;
  23609. Mesh._CAP_START = 1;
  23610. Mesh._CAP_END = 2;
  23611. Mesh._CAP_ALL = 3;
  23612. return Mesh;
  23613. }(BABYLON.AbstractMesh));
  23614. BABYLON.Mesh = Mesh;
  23615. })(BABYLON || (BABYLON = {}));
  23616. //# sourceMappingURL=babylon.mesh.js.map
  23617. var BABYLON;
  23618. (function (BABYLON) {
  23619. var BaseSubMesh = (function () {
  23620. function BaseSubMesh() {
  23621. }
  23622. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23623. get: function () {
  23624. return this._materialEffect;
  23625. },
  23626. enumerable: true,
  23627. configurable: true
  23628. });
  23629. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23630. if (this._materialEffect === effect) {
  23631. if (!effect) {
  23632. this._materialDefines = undefined;
  23633. }
  23634. return;
  23635. }
  23636. this._materialDefines = defines;
  23637. this._materialEffect = effect;
  23638. };
  23639. return BaseSubMesh;
  23640. }());
  23641. BABYLON.BaseSubMesh = BaseSubMesh;
  23642. var SubMesh = (function (_super) {
  23643. __extends(SubMesh, _super);
  23644. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23645. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23646. var _this = _super.call(this) || this;
  23647. _this.materialIndex = materialIndex;
  23648. _this.verticesStart = verticesStart;
  23649. _this.verticesCount = verticesCount;
  23650. _this.indexStart = indexStart;
  23651. _this.indexCount = indexCount;
  23652. _this._renderId = 0;
  23653. _this._mesh = mesh;
  23654. _this._renderingMesh = renderingMesh || mesh;
  23655. mesh.subMeshes.push(_this);
  23656. _this._trianglePlanes = [];
  23657. _this._id = mesh.subMeshes.length - 1;
  23658. if (createBoundingBox) {
  23659. _this.refreshBoundingInfo();
  23660. mesh.computeWorldMatrix(true);
  23661. }
  23662. return _this;
  23663. }
  23664. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23665. get: function () {
  23666. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23667. },
  23668. enumerable: true,
  23669. configurable: true
  23670. });
  23671. /**
  23672. * Returns the submesh BoudingInfo object.
  23673. */
  23674. SubMesh.prototype.getBoundingInfo = function () {
  23675. if (this.IsGlobal) {
  23676. return this._mesh.getBoundingInfo();
  23677. }
  23678. return this._boundingInfo;
  23679. };
  23680. /**
  23681. * Sets the submesh BoundingInfo.
  23682. * Return the SubMesh.
  23683. */
  23684. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23685. this._boundingInfo = boundingInfo;
  23686. return this;
  23687. };
  23688. /**
  23689. * Returns the mesh of the current submesh.
  23690. */
  23691. SubMesh.prototype.getMesh = function () {
  23692. return this._mesh;
  23693. };
  23694. /**
  23695. * Returns the rendering mesh of the submesh.
  23696. */
  23697. SubMesh.prototype.getRenderingMesh = function () {
  23698. return this._renderingMesh;
  23699. };
  23700. /**
  23701. * Returns the submesh material.
  23702. */
  23703. SubMesh.prototype.getMaterial = function () {
  23704. var rootMaterial = this._renderingMesh.material;
  23705. if (rootMaterial && rootMaterial.getSubMaterial) {
  23706. var multiMaterial = rootMaterial;
  23707. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23708. if (this._currentMaterial !== effectiveMaterial) {
  23709. this._currentMaterial = effectiveMaterial;
  23710. this._materialDefines = undefined;
  23711. }
  23712. return effectiveMaterial;
  23713. }
  23714. if (!rootMaterial) {
  23715. return this._mesh.getScene().defaultMaterial;
  23716. }
  23717. return rootMaterial;
  23718. };
  23719. // Methods
  23720. /**
  23721. * Sets a new updated BoundingInfo object to the submesh.
  23722. * Returns the SubMesh.
  23723. */
  23724. SubMesh.prototype.refreshBoundingInfo = function () {
  23725. this._lastColliderWorldVertices = null;
  23726. if (this.IsGlobal) {
  23727. return;
  23728. }
  23729. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23730. if (!data) {
  23731. this._boundingInfo = this._mesh._boundingInfo;
  23732. return;
  23733. }
  23734. var indices = this._renderingMesh.getIndices();
  23735. var extend;
  23736. //is this the only submesh?
  23737. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23738. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23739. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23740. }
  23741. else {
  23742. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23743. }
  23744. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23745. return this;
  23746. };
  23747. SubMesh.prototype._checkCollision = function (collider) {
  23748. return this.getBoundingInfo()._checkCollision(collider);
  23749. };
  23750. /**
  23751. * Updates the submesh BoundingInfo.
  23752. * Returns the Submesh.
  23753. */
  23754. SubMesh.prototype.updateBoundingInfo = function (world) {
  23755. if (!this.getBoundingInfo()) {
  23756. this.refreshBoundingInfo();
  23757. }
  23758. this.getBoundingInfo().update(world);
  23759. return this;
  23760. };
  23761. /**
  23762. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23763. * Boolean returned.
  23764. */
  23765. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23766. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23767. };
  23768. /**
  23769. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23770. * Boolean returned.
  23771. */
  23772. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23773. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23774. };
  23775. /**
  23776. * Renders the submesh.
  23777. * Returns it.
  23778. */
  23779. SubMesh.prototype.render = function (enableAlphaMode) {
  23780. this._renderingMesh.render(this, enableAlphaMode);
  23781. return this;
  23782. };
  23783. /**
  23784. * Returns a new Index Buffer.
  23785. * Type returned : WebGLBuffer.
  23786. */
  23787. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23788. if (!this._linesIndexBuffer) {
  23789. var linesIndices = [];
  23790. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23791. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23792. }
  23793. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23794. this.linesIndexCount = linesIndices.length;
  23795. }
  23796. return this._linesIndexBuffer;
  23797. };
  23798. /**
  23799. * True is the passed Ray intersects the submesh bounding box.
  23800. * Boolean returned.
  23801. */
  23802. SubMesh.prototype.canIntersects = function (ray) {
  23803. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23804. };
  23805. /**
  23806. * Returns an object IntersectionInfo.
  23807. */
  23808. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23809. var intersectInfo = null;
  23810. // LineMesh first as it's also a Mesh...
  23811. if (this._mesh instanceof BABYLON.LinesMesh) {
  23812. var lineMesh = this._mesh;
  23813. // Line test
  23814. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23815. var p0 = positions[indices[index]];
  23816. var p1 = positions[indices[index + 1]];
  23817. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23818. if (length < 0) {
  23819. continue;
  23820. }
  23821. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23822. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23823. if (fastCheck) {
  23824. break;
  23825. }
  23826. }
  23827. }
  23828. }
  23829. else {
  23830. // Triangles test
  23831. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23832. var p0 = positions[indices[index]];
  23833. var p1 = positions[indices[index + 1]];
  23834. var p2 = positions[indices[index + 2]];
  23835. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23836. if (currentIntersectInfo) {
  23837. if (currentIntersectInfo.distance < 0) {
  23838. continue;
  23839. }
  23840. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23841. intersectInfo = currentIntersectInfo;
  23842. intersectInfo.faceId = index / 3;
  23843. if (fastCheck) {
  23844. break;
  23845. }
  23846. }
  23847. }
  23848. }
  23849. }
  23850. return intersectInfo;
  23851. };
  23852. SubMesh.prototype._rebuild = function () {
  23853. if (this._linesIndexBuffer) {
  23854. this._linesIndexBuffer = null;
  23855. }
  23856. };
  23857. // Clone
  23858. /**
  23859. * Creates a new Submesh from the passed Mesh.
  23860. */
  23861. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23862. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23863. if (!this.IsGlobal) {
  23864. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23865. }
  23866. return result;
  23867. };
  23868. // Dispose
  23869. /**
  23870. * Disposes the Submesh.
  23871. * Returns nothing.
  23872. */
  23873. SubMesh.prototype.dispose = function () {
  23874. if (this._linesIndexBuffer) {
  23875. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23876. this._linesIndexBuffer = null;
  23877. }
  23878. // Remove from mesh
  23879. var index = this._mesh.subMeshes.indexOf(this);
  23880. this._mesh.subMeshes.splice(index, 1);
  23881. };
  23882. // Statics
  23883. /**
  23884. * Creates a new Submesh from the passed parameters :
  23885. * - materialIndex (integer) : the index of the main mesh material.
  23886. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23887. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23888. * - mesh (Mesh) : the main mesh to create the submesh from.
  23889. * - renderingMesh (optional Mesh) : rendering mesh.
  23890. */
  23891. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23892. var minVertexIndex = Number.MAX_VALUE;
  23893. var maxVertexIndex = -Number.MAX_VALUE;
  23894. renderingMesh = renderingMesh || mesh;
  23895. var indices = renderingMesh.getIndices();
  23896. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23897. var vertexIndex = indices[index];
  23898. if (vertexIndex < minVertexIndex)
  23899. minVertexIndex = vertexIndex;
  23900. if (vertexIndex > maxVertexIndex)
  23901. maxVertexIndex = vertexIndex;
  23902. }
  23903. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23904. };
  23905. return SubMesh;
  23906. }(BaseSubMesh));
  23907. BABYLON.SubMesh = SubMesh;
  23908. })(BABYLON || (BABYLON = {}));
  23909. //# sourceMappingURL=babylon.subMesh.js.map
  23910. var BABYLON;
  23911. (function (BABYLON) {
  23912. var EffectFallbacks = (function () {
  23913. function EffectFallbacks() {
  23914. this._defines = {};
  23915. this._currentRank = 32;
  23916. this._maxRank = -1;
  23917. }
  23918. EffectFallbacks.prototype.unBindMesh = function () {
  23919. this._mesh = null;
  23920. };
  23921. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23922. if (!this._defines[rank]) {
  23923. if (rank < this._currentRank) {
  23924. this._currentRank = rank;
  23925. }
  23926. if (rank > this._maxRank) {
  23927. this._maxRank = rank;
  23928. }
  23929. this._defines[rank] = new Array();
  23930. }
  23931. this._defines[rank].push(define);
  23932. };
  23933. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23934. this._meshRank = rank;
  23935. this._mesh = mesh;
  23936. if (rank < this._currentRank) {
  23937. this._currentRank = rank;
  23938. }
  23939. if (rank > this._maxRank) {
  23940. this._maxRank = rank;
  23941. }
  23942. };
  23943. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23944. get: function () {
  23945. return this._currentRank <= this._maxRank;
  23946. },
  23947. enumerable: true,
  23948. configurable: true
  23949. });
  23950. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23951. // First we try to switch to CPU skinning
  23952. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23953. this._mesh.computeBonesUsingShaders = false;
  23954. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23955. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23956. var scene = this._mesh.getScene();
  23957. for (var index = 0; index < scene.meshes.length; index++) {
  23958. var otherMesh = scene.meshes[index];
  23959. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23960. otherMesh.computeBonesUsingShaders = false;
  23961. }
  23962. }
  23963. }
  23964. else {
  23965. var currentFallbacks = this._defines[this._currentRank];
  23966. if (currentFallbacks) {
  23967. for (var index = 0; index < currentFallbacks.length; index++) {
  23968. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23969. }
  23970. }
  23971. this._currentRank++;
  23972. }
  23973. return currentDefines;
  23974. };
  23975. return EffectFallbacks;
  23976. }());
  23977. BABYLON.EffectFallbacks = EffectFallbacks;
  23978. var EffectCreationOptions = (function () {
  23979. function EffectCreationOptions() {
  23980. }
  23981. return EffectCreationOptions;
  23982. }());
  23983. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23984. var Effect = (function () {
  23985. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23986. var _this = this;
  23987. this.uniqueId = 0;
  23988. this.onCompileObservable = new BABYLON.Observable();
  23989. this.onErrorObservable = new BABYLON.Observable();
  23990. this.onBindObservable = new BABYLON.Observable();
  23991. this._uniformBuffersNames = {};
  23992. this._isReady = false;
  23993. this._compilationError = "";
  23994. this.name = baseName;
  23995. if (attributesNamesOrOptions.attributes) {
  23996. var options = attributesNamesOrOptions;
  23997. this._engine = uniformsNamesOrEngine;
  23998. this._attributesNames = options.attributes;
  23999. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24000. this._samplers = options.samplers;
  24001. this.defines = options.defines;
  24002. this.onError = options.onError;
  24003. this.onCompiled = options.onCompiled;
  24004. this._fallbacks = options.fallbacks;
  24005. this._indexParameters = options.indexParameters;
  24006. if (options.uniformBuffersNames) {
  24007. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24008. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24009. }
  24010. }
  24011. }
  24012. else {
  24013. this._engine = engine;
  24014. this.defines = defines;
  24015. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24016. this._samplers = samplers;
  24017. this._attributesNames = attributesNamesOrOptions;
  24018. this.onError = onError;
  24019. this.onCompiled = onCompiled;
  24020. this._indexParameters = indexParameters;
  24021. this._fallbacks = fallbacks;
  24022. }
  24023. this.uniqueId = Effect._uniqueIdSeed++;
  24024. var vertexSource;
  24025. var fragmentSource;
  24026. if (baseName.vertexElement) {
  24027. vertexSource = document.getElementById(baseName.vertexElement);
  24028. if (!vertexSource) {
  24029. vertexSource = baseName.vertexElement;
  24030. }
  24031. }
  24032. else {
  24033. vertexSource = baseName.vertex || baseName;
  24034. }
  24035. if (baseName.fragmentElement) {
  24036. fragmentSource = document.getElementById(baseName.fragmentElement);
  24037. if (!fragmentSource) {
  24038. fragmentSource = baseName.fragmentElement;
  24039. }
  24040. }
  24041. else {
  24042. fragmentSource = baseName.fragment || baseName;
  24043. }
  24044. this._loadVertexShader(vertexSource, function (vertexCode) {
  24045. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24046. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24047. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24048. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24049. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24050. if (baseName) {
  24051. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24052. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24053. }
  24054. else {
  24055. _this._vertexSourceCode = migratedVertexCode;
  24056. _this._fragmentSourceCode = migratedFragmentCode;
  24057. }
  24058. _this._prepareEffect();
  24059. });
  24060. });
  24061. });
  24062. });
  24063. });
  24064. });
  24065. }
  24066. Object.defineProperty(Effect.prototype, "key", {
  24067. get: function () {
  24068. return this._key;
  24069. },
  24070. enumerable: true,
  24071. configurable: true
  24072. });
  24073. // Properties
  24074. Effect.prototype.isReady = function () {
  24075. return this._isReady;
  24076. };
  24077. Effect.prototype.getEngine = function () {
  24078. return this._engine;
  24079. };
  24080. Effect.prototype.getProgram = function () {
  24081. return this._program;
  24082. };
  24083. Effect.prototype.getAttributesNames = function () {
  24084. return this._attributesNames;
  24085. };
  24086. Effect.prototype.getAttributeLocation = function (index) {
  24087. return this._attributes[index];
  24088. };
  24089. Effect.prototype.getAttributeLocationByName = function (name) {
  24090. var index = this._attributesNames.indexOf(name);
  24091. return this._attributes[index];
  24092. };
  24093. Effect.prototype.getAttributesCount = function () {
  24094. return this._attributes.length;
  24095. };
  24096. Effect.prototype.getUniformIndex = function (uniformName) {
  24097. return this._uniformsNames.indexOf(uniformName);
  24098. };
  24099. Effect.prototype.getUniform = function (uniformName) {
  24100. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24101. };
  24102. Effect.prototype.getSamplers = function () {
  24103. return this._samplers;
  24104. };
  24105. Effect.prototype.getCompilationError = function () {
  24106. return this._compilationError;
  24107. };
  24108. // Methods
  24109. Effect.prototype.executeWhenCompiled = function (func) {
  24110. if (this.isReady()) {
  24111. func(this);
  24112. return;
  24113. }
  24114. this.onCompileObservable.add(function (effect) {
  24115. func(effect);
  24116. });
  24117. };
  24118. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24119. // DOM element ?
  24120. if (vertex instanceof HTMLElement) {
  24121. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24122. callback(vertexCode);
  24123. return;
  24124. }
  24125. // Base64 encoded ?
  24126. if (vertex.substr(0, 7) === "base64:") {
  24127. var vertexBinary = window.atob(vertex.substr(7));
  24128. callback(vertexBinary);
  24129. return;
  24130. }
  24131. // Is in local store ?
  24132. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24133. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24134. return;
  24135. }
  24136. var vertexShaderUrl;
  24137. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24138. vertexShaderUrl = vertex;
  24139. }
  24140. else {
  24141. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24142. }
  24143. // Vertex shader
  24144. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24145. };
  24146. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24147. // DOM element ?
  24148. if (fragment instanceof HTMLElement) {
  24149. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24150. callback(fragmentCode);
  24151. return;
  24152. }
  24153. // Base64 encoded ?
  24154. if (fragment.substr(0, 7) === "base64:") {
  24155. var fragmentBinary = window.atob(fragment.substr(7));
  24156. callback(fragmentBinary);
  24157. return;
  24158. }
  24159. // Is in local store ?
  24160. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24161. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24162. return;
  24163. }
  24164. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24165. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24166. return;
  24167. }
  24168. var fragmentShaderUrl;
  24169. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24170. fragmentShaderUrl = fragment;
  24171. }
  24172. else {
  24173. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24174. }
  24175. // Fragment shader
  24176. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24177. };
  24178. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24179. // Rebuild shaders source code
  24180. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24181. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24182. vertexCode = prefix + vertexCode;
  24183. fragmentCode = prefix + fragmentCode;
  24184. // Number lines of shaders source code
  24185. var i = 2;
  24186. var regex = /\n/gm;
  24187. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24188. i = 2;
  24189. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24190. // Dump shaders name and formatted source code
  24191. if (this.name.vertexElement) {
  24192. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24193. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24194. }
  24195. else if (this.name.vertex) {
  24196. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24197. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24198. }
  24199. else {
  24200. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24201. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24202. }
  24203. };
  24204. ;
  24205. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24206. var preparedSourceCode = this._processPrecision(sourceCode);
  24207. if (this._engine.webGLVersion == 1) {
  24208. callback(preparedSourceCode);
  24209. return;
  24210. }
  24211. // Already converted
  24212. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24213. callback(preparedSourceCode.replace("#version 300 es", ""));
  24214. return;
  24215. }
  24216. // Remove extensions
  24217. // #extension GL_OES_standard_derivatives : enable
  24218. // #extension GL_EXT_shader_texture_lod : enable
  24219. // #extension GL_EXT_frag_depth : enable
  24220. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24221. var result = preparedSourceCode.replace(regex, "");
  24222. // Migrate to GLSL v300
  24223. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24224. result = result.replace(/attribute[ \t]/g, "in ");
  24225. result = result.replace(/[ \t]attribute/g, " in");
  24226. if (isFragment) {
  24227. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24228. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24229. result = result.replace(/texture2D\(/g, "texture(");
  24230. result = result.replace(/textureCube\(/g, "texture(");
  24231. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24232. result = result.replace(/gl_FragColor/g, "glFragColor");
  24233. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24234. }
  24235. callback(result);
  24236. };
  24237. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24238. var _this = this;
  24239. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24240. var match = regex.exec(sourceCode);
  24241. var returnValue = new String(sourceCode);
  24242. while (match != null) {
  24243. var includeFile = match[1];
  24244. // Uniform declaration
  24245. if (includeFile.indexOf("__decl__") !== -1) {
  24246. includeFile = includeFile.replace(/__decl__/, "");
  24247. if (this._engine.webGLVersion != 1) {
  24248. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24249. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24250. }
  24251. includeFile = includeFile + "Declaration";
  24252. }
  24253. if (Effect.IncludesShadersStore[includeFile]) {
  24254. // Substitution
  24255. var includeContent = Effect.IncludesShadersStore[includeFile];
  24256. if (match[2]) {
  24257. var splits = match[3].split(",");
  24258. for (var index = 0; index < splits.length; index += 2) {
  24259. var source = new RegExp(splits[index], "g");
  24260. var dest = splits[index + 1];
  24261. includeContent = includeContent.replace(source, dest);
  24262. }
  24263. }
  24264. if (match[4]) {
  24265. var indexString = match[5];
  24266. if (indexString.indexOf("..") !== -1) {
  24267. var indexSplits = indexString.split("..");
  24268. var minIndex = parseInt(indexSplits[0]);
  24269. var maxIndex = parseInt(indexSplits[1]);
  24270. var sourceIncludeContent = includeContent.slice(0);
  24271. includeContent = "";
  24272. if (isNaN(maxIndex)) {
  24273. maxIndex = this._indexParameters[indexSplits[1]];
  24274. }
  24275. for (var i = minIndex; i < maxIndex; i++) {
  24276. if (this._engine.webGLVersion === 1) {
  24277. // Ubo replacement
  24278. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24279. return p1 + "{X}";
  24280. });
  24281. }
  24282. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24283. }
  24284. }
  24285. else {
  24286. if (this._engine.webGLVersion === 1) {
  24287. // Ubo replacement
  24288. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24289. return p1 + "{X}";
  24290. });
  24291. }
  24292. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24293. }
  24294. }
  24295. // Replace
  24296. returnValue = returnValue.replace(match[0], includeContent);
  24297. }
  24298. else {
  24299. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24300. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24301. Effect.IncludesShadersStore[includeFile] = fileContent;
  24302. _this._processIncludes(returnValue, callback);
  24303. });
  24304. return;
  24305. }
  24306. match = regex.exec(sourceCode);
  24307. }
  24308. callback(returnValue);
  24309. };
  24310. Effect.prototype._processPrecision = function (source) {
  24311. if (source.indexOf("precision highp float") === -1) {
  24312. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24313. source = "precision mediump float;\n" + source;
  24314. }
  24315. else {
  24316. source = "precision highp float;\n" + source;
  24317. }
  24318. }
  24319. else {
  24320. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24321. source = source.replace("precision highp float", "precision mediump float");
  24322. }
  24323. }
  24324. return source;
  24325. };
  24326. Effect.prototype._prepareEffect = function () {
  24327. var attributesNames = this._attributesNames;
  24328. var defines = this.defines;
  24329. var fallbacks = this._fallbacks;
  24330. this._valueCache = {};
  24331. try {
  24332. var engine = this._engine;
  24333. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24334. if (engine.webGLVersion > 1) {
  24335. for (var name in this._uniformBuffersNames) {
  24336. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24337. }
  24338. }
  24339. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24340. this._attributes = engine.getAttributes(this._program, attributesNames);
  24341. var index;
  24342. for (index = 0; index < this._samplers.length; index++) {
  24343. var sampler = this.getUniform(this._samplers[index]);
  24344. if (sampler == null) {
  24345. this._samplers.splice(index, 1);
  24346. index--;
  24347. }
  24348. }
  24349. engine.bindSamplers(this);
  24350. this._compilationError = "";
  24351. this._isReady = true;
  24352. if (this.onCompiled) {
  24353. this.onCompiled(this);
  24354. }
  24355. this.onCompileObservable.notifyObservers(this);
  24356. this.onCompileObservable.clear();
  24357. // Unbind mesh reference in fallbacks
  24358. if (this._fallbacks) {
  24359. this._fallbacks.unBindMesh();
  24360. }
  24361. }
  24362. catch (e) {
  24363. this._compilationError = e.message;
  24364. // Let's go through fallbacks then
  24365. BABYLON.Tools.Error("Unable to compile effect:");
  24366. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24367. return " " + uniform;
  24368. }));
  24369. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24370. return " " + attribute;
  24371. }));
  24372. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24373. BABYLON.Tools.Error("Error: " + this._compilationError);
  24374. if (fallbacks && fallbacks.isMoreFallbacks) {
  24375. BABYLON.Tools.Error("Trying next fallback.");
  24376. this.defines = fallbacks.reduce(this.defines);
  24377. this._prepareEffect();
  24378. }
  24379. else {
  24380. if (this.onError) {
  24381. this.onError(this, this._compilationError);
  24382. }
  24383. this.onErrorObservable.notifyObservers(this);
  24384. this.onErrorObservable.clear();
  24385. // Unbind mesh reference in fallbacks
  24386. if (this._fallbacks) {
  24387. this._fallbacks.unBindMesh();
  24388. }
  24389. }
  24390. }
  24391. };
  24392. Object.defineProperty(Effect.prototype, "isSupported", {
  24393. get: function () {
  24394. return this._compilationError === "";
  24395. },
  24396. enumerable: true,
  24397. configurable: true
  24398. });
  24399. Effect.prototype._bindTexture = function (channel, texture) {
  24400. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24401. };
  24402. Effect.prototype.setTexture = function (channel, texture) {
  24403. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24404. };
  24405. Effect.prototype.setTextureArray = function (channel, textures) {
  24406. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24407. var initialPos = this._samplers.indexOf(channel);
  24408. for (var index = 1; index < textures.length; index++) {
  24409. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24410. }
  24411. }
  24412. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24413. };
  24414. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24415. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24416. };
  24417. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24418. var cache = this._valueCache[uniformName];
  24419. var flag = matrix.updateFlag;
  24420. if (cache !== undefined && cache === flag) {
  24421. return false;
  24422. }
  24423. this._valueCache[uniformName] = flag;
  24424. return true;
  24425. };
  24426. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24427. var cache = this._valueCache[uniformName];
  24428. if (!cache) {
  24429. cache = [x, y];
  24430. this._valueCache[uniformName] = cache;
  24431. return true;
  24432. }
  24433. var changed = false;
  24434. if (cache[0] !== x) {
  24435. cache[0] = x;
  24436. changed = true;
  24437. }
  24438. if (cache[1] !== y) {
  24439. cache[1] = y;
  24440. changed = true;
  24441. }
  24442. return changed;
  24443. };
  24444. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24445. var cache = this._valueCache[uniformName];
  24446. if (!cache) {
  24447. cache = [x, y, z];
  24448. this._valueCache[uniformName] = cache;
  24449. return true;
  24450. }
  24451. var changed = false;
  24452. if (cache[0] !== x) {
  24453. cache[0] = x;
  24454. changed = true;
  24455. }
  24456. if (cache[1] !== y) {
  24457. cache[1] = y;
  24458. changed = true;
  24459. }
  24460. if (cache[2] !== z) {
  24461. cache[2] = z;
  24462. changed = true;
  24463. }
  24464. return changed;
  24465. };
  24466. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24467. var cache = this._valueCache[uniformName];
  24468. if (!cache) {
  24469. cache = [x, y, z, w];
  24470. this._valueCache[uniformName] = cache;
  24471. return true;
  24472. }
  24473. var changed = false;
  24474. if (cache[0] !== x) {
  24475. cache[0] = x;
  24476. changed = true;
  24477. }
  24478. if (cache[1] !== y) {
  24479. cache[1] = y;
  24480. changed = true;
  24481. }
  24482. if (cache[2] !== z) {
  24483. cache[2] = z;
  24484. changed = true;
  24485. }
  24486. if (cache[3] !== w) {
  24487. cache[3] = w;
  24488. changed = true;
  24489. }
  24490. return changed;
  24491. };
  24492. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24493. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24494. return;
  24495. }
  24496. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24497. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24498. };
  24499. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24500. this._engine.bindUniformBlock(this._program, blockName, index);
  24501. };
  24502. Effect.prototype.setIntArray = function (uniformName, array) {
  24503. this._valueCache[uniformName] = null;
  24504. this._engine.setIntArray(this.getUniform(uniformName), array);
  24505. return this;
  24506. };
  24507. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24508. this._valueCache[uniformName] = null;
  24509. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24510. return this;
  24511. };
  24512. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24513. this._valueCache[uniformName] = null;
  24514. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24515. return this;
  24516. };
  24517. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24518. this._valueCache[uniformName] = null;
  24519. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24520. return this;
  24521. };
  24522. Effect.prototype.setFloatArray = function (uniformName, array) {
  24523. this._valueCache[uniformName] = null;
  24524. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24525. return this;
  24526. };
  24527. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24528. this._valueCache[uniformName] = null;
  24529. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24530. return this;
  24531. };
  24532. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24533. this._valueCache[uniformName] = null;
  24534. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24535. return this;
  24536. };
  24537. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24538. this._valueCache[uniformName] = null;
  24539. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24540. return this;
  24541. };
  24542. Effect.prototype.setArray = function (uniformName, array) {
  24543. this._valueCache[uniformName] = null;
  24544. this._engine.setArray(this.getUniform(uniformName), array);
  24545. return this;
  24546. };
  24547. Effect.prototype.setArray2 = function (uniformName, array) {
  24548. this._valueCache[uniformName] = null;
  24549. this._engine.setArray2(this.getUniform(uniformName), array);
  24550. return this;
  24551. };
  24552. Effect.prototype.setArray3 = function (uniformName, array) {
  24553. this._valueCache[uniformName] = null;
  24554. this._engine.setArray3(this.getUniform(uniformName), array);
  24555. return this;
  24556. };
  24557. Effect.prototype.setArray4 = function (uniformName, array) {
  24558. this._valueCache[uniformName] = null;
  24559. this._engine.setArray4(this.getUniform(uniformName), array);
  24560. return this;
  24561. };
  24562. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24563. if (!matrices) {
  24564. return;
  24565. }
  24566. this._valueCache[uniformName] = null;
  24567. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24568. return this;
  24569. };
  24570. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24571. if (this._cacheMatrix(uniformName, matrix)) {
  24572. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24573. }
  24574. return this;
  24575. };
  24576. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24577. this._valueCache[uniformName] = null;
  24578. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24579. return this;
  24580. };
  24581. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24582. this._valueCache[uniformName] = null;
  24583. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24584. return this;
  24585. };
  24586. Effect.prototype.setFloat = function (uniformName, value) {
  24587. var cache = this._valueCache[uniformName];
  24588. if (cache !== undefined && cache === value)
  24589. return this;
  24590. this._valueCache[uniformName] = value;
  24591. this._engine.setFloat(this.getUniform(uniformName), value);
  24592. return this;
  24593. };
  24594. Effect.prototype.setBool = function (uniformName, bool) {
  24595. var cache = this._valueCache[uniformName];
  24596. if (cache !== undefined && cache === bool)
  24597. return this;
  24598. this._valueCache[uniformName] = bool;
  24599. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24600. return this;
  24601. };
  24602. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24603. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24604. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24605. }
  24606. return this;
  24607. };
  24608. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24609. if (this._cacheFloat2(uniformName, x, y)) {
  24610. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24611. }
  24612. return this;
  24613. };
  24614. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24615. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24616. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24617. }
  24618. return this;
  24619. };
  24620. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24621. if (this._cacheFloat3(uniformName, x, y, z)) {
  24622. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24623. }
  24624. return this;
  24625. };
  24626. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24627. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24628. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24629. }
  24630. return this;
  24631. };
  24632. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24633. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24634. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24635. }
  24636. return this;
  24637. };
  24638. Effect.prototype.setColor3 = function (uniformName, color3) {
  24639. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24640. this._engine.setColor3(this.getUniform(uniformName), color3);
  24641. }
  24642. return this;
  24643. };
  24644. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24645. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24646. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24647. }
  24648. return this;
  24649. };
  24650. Effect.ResetCache = function () {
  24651. Effect._baseCache = {};
  24652. };
  24653. Effect._uniqueIdSeed = 0;
  24654. Effect._baseCache = {};
  24655. // Statics
  24656. Effect.ShadersStore = {};
  24657. Effect.IncludesShadersStore = {};
  24658. return Effect;
  24659. }());
  24660. BABYLON.Effect = Effect;
  24661. })(BABYLON || (BABYLON = {}));
  24662. //# sourceMappingURL=babylon.effect.js.map
  24663. var BABYLON;
  24664. (function (BABYLON) {
  24665. var MaterialHelper = (function () {
  24666. function MaterialHelper() {
  24667. }
  24668. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24669. defines._needUVs = true;
  24670. defines[key] = true;
  24671. if (texture.getTextureMatrix().isIdentity(true)) {
  24672. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24673. if (texture.coordinatesIndex === 0) {
  24674. defines["MAINUV1"] = true;
  24675. }
  24676. else {
  24677. defines["MAINUV2"] = true;
  24678. }
  24679. }
  24680. else {
  24681. defines[key + "DIRECTUV"] = 0;
  24682. }
  24683. };
  24684. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24685. var matrix = texture.getTextureMatrix();
  24686. if (!matrix.isIdentity(true)) {
  24687. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24688. }
  24689. };
  24690. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24691. if (defines._areMiscDirty) {
  24692. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24693. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24694. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24695. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24696. }
  24697. };
  24698. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24699. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24700. var changed = false;
  24701. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24702. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24703. changed = true;
  24704. }
  24705. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24706. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24707. changed = true;
  24708. }
  24709. if (defines["INSTANCES"] !== useInstances) {
  24710. defines["INSTANCES"] = useInstances;
  24711. changed = true;
  24712. }
  24713. if (changed) {
  24714. defines.markAsUnprocessed();
  24715. }
  24716. };
  24717. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24718. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24719. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24720. return false;
  24721. }
  24722. defines._normals = defines._needNormals;
  24723. defines._uvs = defines._needUVs;
  24724. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24725. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24726. defines["TANGENT"] = true;
  24727. }
  24728. if (defines._needUVs) {
  24729. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24730. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24731. }
  24732. else {
  24733. defines["UV1"] = false;
  24734. defines["UV2"] = false;
  24735. }
  24736. if (useVertexColor) {
  24737. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24738. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24739. }
  24740. if (useBones) {
  24741. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24742. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24743. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24744. }
  24745. else {
  24746. defines["NUM_BONE_INFLUENCERS"] = 0;
  24747. defines["BonesPerMesh"] = 0;
  24748. }
  24749. }
  24750. if (useMorphTargets) {
  24751. if (mesh.morphTargetManager) {
  24752. var manager = mesh.morphTargetManager;
  24753. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24754. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24755. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24756. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24757. }
  24758. else {
  24759. defines["MORPHTARGETS_TANGENT"] = false;
  24760. defines["MORPHTARGETS_NORMAL"] = false;
  24761. defines["MORPHTARGETS"] = false;
  24762. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24763. }
  24764. }
  24765. return true;
  24766. };
  24767. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24768. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24769. if (disableLighting === void 0) { disableLighting = false; }
  24770. if (!defines._areLightsDirty) {
  24771. return defines._needNormals;
  24772. }
  24773. var lightIndex = 0;
  24774. var needNormals = false;
  24775. var needRebuild = false;
  24776. var lightmapMode = false;
  24777. var shadowEnabled = false;
  24778. var specularEnabled = false;
  24779. if (scene.lightsEnabled && !disableLighting) {
  24780. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24781. var light = _a[_i];
  24782. needNormals = true;
  24783. if (defines["LIGHT" + lightIndex] === undefined) {
  24784. needRebuild = true;
  24785. }
  24786. defines["LIGHT" + lightIndex] = true;
  24787. defines["SPOTLIGHT" + lightIndex] = false;
  24788. defines["HEMILIGHT" + lightIndex] = false;
  24789. defines["POINTLIGHT" + lightIndex] = false;
  24790. defines["DIRLIGHT" + lightIndex] = false;
  24791. var type;
  24792. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24793. type = "SPOTLIGHT" + lightIndex;
  24794. }
  24795. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24796. type = "HEMILIGHT" + lightIndex;
  24797. }
  24798. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24799. type = "POINTLIGHT" + lightIndex;
  24800. }
  24801. else {
  24802. type = "DIRLIGHT" + lightIndex;
  24803. }
  24804. defines[type] = true;
  24805. // Specular
  24806. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24807. specularEnabled = true;
  24808. }
  24809. // Shadows
  24810. defines["SHADOW" + lightIndex] = false;
  24811. defines["SHADOWPCF" + lightIndex] = false;
  24812. defines["SHADOWESM" + lightIndex] = false;
  24813. defines["SHADOWCUBE" + lightIndex] = false;
  24814. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24815. var shadowGenerator = light.getShadowGenerator();
  24816. if (shadowGenerator) {
  24817. shadowEnabled = true;
  24818. shadowGenerator.prepareDefines(defines, lightIndex);
  24819. }
  24820. }
  24821. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24822. lightmapMode = true;
  24823. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24824. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24825. }
  24826. else {
  24827. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24828. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24829. }
  24830. lightIndex++;
  24831. if (lightIndex === maxSimultaneousLights)
  24832. break;
  24833. }
  24834. }
  24835. defines["SPECULARTERM"] = specularEnabled;
  24836. defines["SHADOWS"] = shadowEnabled;
  24837. // Resetting all other lights if any
  24838. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24839. if (defines["LIGHT" + index] !== undefined) {
  24840. defines["LIGHT" + index] = false;
  24841. defines["HEMILIGHT" + lightIndex] = false;
  24842. defines["POINTLIGHT" + lightIndex] = false;
  24843. defines["DIRLIGHT" + lightIndex] = false;
  24844. defines["SPOTLIGHT" + lightIndex] = false;
  24845. defines["SHADOW" + lightIndex] = false;
  24846. }
  24847. }
  24848. var caps = scene.getEngine().getCaps();
  24849. if (defines["SHADOWFLOAT"] === undefined) {
  24850. needRebuild = true;
  24851. }
  24852. defines["SHADOWFLOAT"] = shadowEnabled &&
  24853. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24854. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24855. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24856. if (needRebuild) {
  24857. defines.rebuild();
  24858. }
  24859. return needNormals;
  24860. };
  24861. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24862. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24863. var uniformsList, uniformBuffersList, samplersList, defines;
  24864. if (uniformsListOrOptions.uniformsNames) {
  24865. var options = uniformsListOrOptions;
  24866. uniformsList = options.uniformsNames;
  24867. uniformBuffersList = options.uniformBuffersNames;
  24868. samplersList = options.samplers;
  24869. defines = options.defines;
  24870. maxSimultaneousLights = options.maxSimultaneousLights;
  24871. }
  24872. else {
  24873. uniformsList = uniformsListOrOptions;
  24874. }
  24875. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24876. if (!defines["LIGHT" + lightIndex]) {
  24877. break;
  24878. }
  24879. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24880. if (uniformBuffersList) {
  24881. uniformBuffersList.push("Light" + lightIndex);
  24882. }
  24883. samplersList.push("shadowSampler" + lightIndex);
  24884. }
  24885. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24886. uniformsList.push("morphTargetInfluences");
  24887. }
  24888. };
  24889. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24890. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24891. if (!defines["SHADOWS"]) {
  24892. return;
  24893. }
  24894. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24895. if (!defines["LIGHT" + lightIndex]) {
  24896. break;
  24897. }
  24898. if (lightIndex > 0) {
  24899. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24900. }
  24901. if (defines["SHADOW" + lightIndex]) {
  24902. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24903. }
  24904. if (defines["SHADOWPCF" + lightIndex]) {
  24905. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24906. }
  24907. if (defines["SHADOWESM" + lightIndex]) {
  24908. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24909. }
  24910. }
  24911. };
  24912. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24913. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24914. if (influencers > 0) {
  24915. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24916. var manager = mesh.morphTargetManager;
  24917. var normal = manager.supportsNormals && defines["NORMAL"];
  24918. var tangent = manager.supportsTangents && defines["TANGENT"];
  24919. for (var index = 0; index < influencers; index++) {
  24920. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24921. if (normal) {
  24922. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24923. }
  24924. if (tangent) {
  24925. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24926. }
  24927. if (attribs.length > maxAttributesCount) {
  24928. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24929. }
  24930. }
  24931. }
  24932. };
  24933. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24934. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24935. fallbacks.addCPUSkinningFallback(0, mesh);
  24936. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24937. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24938. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24939. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24940. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24941. }
  24942. }
  24943. };
  24944. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24945. if (defines["INSTANCES"]) {
  24946. attribs.push("world0");
  24947. attribs.push("world1");
  24948. attribs.push("world2");
  24949. attribs.push("world3");
  24950. }
  24951. };
  24952. // Bindings
  24953. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24954. if (light.shadowEnabled && mesh.receiveShadows) {
  24955. var shadowGenerator = light.getShadowGenerator();
  24956. if (shadowGenerator) {
  24957. shadowGenerator.bindShadowLight(lightIndex, effect);
  24958. }
  24959. }
  24960. };
  24961. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24962. light.transferToEffect(effect, lightIndex + "");
  24963. };
  24964. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24965. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24966. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24967. var lightIndex = 0;
  24968. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24969. var light = _a[_i];
  24970. var scaledIntensity = light.getScaledIntensity();
  24971. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24972. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24973. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24974. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24975. if (defines["SPECULARTERM"]) {
  24976. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24977. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24978. }
  24979. // Shadows
  24980. if (scene.shadowsEnabled) {
  24981. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24982. }
  24983. light._uniformBuffer.update();
  24984. lightIndex++;
  24985. if (lightIndex === maxSimultaneousLights)
  24986. break;
  24987. }
  24988. };
  24989. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24990. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24991. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24992. effect.setColor3("vFogColor", scene.fogColor);
  24993. }
  24994. };
  24995. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24996. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24997. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24998. if (matrices) {
  24999. effect.setMatrices("mBones", matrices);
  25000. }
  25001. }
  25002. };
  25003. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25004. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25005. return;
  25006. }
  25007. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25008. };
  25009. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25010. if (defines["LOGARITHMICDEPTH"]) {
  25011. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25012. }
  25013. };
  25014. MaterialHelper.BindClipPlane = function (effect, scene) {
  25015. if (scene.clipPlane) {
  25016. var clipPlane = scene.clipPlane;
  25017. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25018. }
  25019. };
  25020. return MaterialHelper;
  25021. }());
  25022. BABYLON.MaterialHelper = MaterialHelper;
  25023. })(BABYLON || (BABYLON = {}));
  25024. //# sourceMappingURL=babylon.materialHelper.js.map
  25025. var BABYLON;
  25026. (function (BABYLON) {
  25027. var MaterialDefines = (function () {
  25028. function MaterialDefines() {
  25029. this._isDirty = true;
  25030. this._areLightsDirty = true;
  25031. this._areAttributesDirty = true;
  25032. this._areTexturesDirty = true;
  25033. this._areFresnelDirty = true;
  25034. this._areMiscDirty = true;
  25035. this._areImageProcessingDirty = true;
  25036. this._normals = false;
  25037. this._uvs = false;
  25038. this._needNormals = false;
  25039. this._needUVs = false;
  25040. }
  25041. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25042. get: function () {
  25043. return this._isDirty;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. MaterialDefines.prototype.markAsProcessed = function () {
  25049. this._isDirty = false;
  25050. this._areAttributesDirty = false;
  25051. this._areTexturesDirty = false;
  25052. this._areFresnelDirty = false;
  25053. this._areLightsDirty = false;
  25054. this._areMiscDirty = false;
  25055. this._areImageProcessingDirty = false;
  25056. };
  25057. MaterialDefines.prototype.markAsUnprocessed = function () {
  25058. this._isDirty = true;
  25059. };
  25060. MaterialDefines.prototype.markAllAsDirty = function () {
  25061. this._areTexturesDirty = true;
  25062. this._areAttributesDirty = true;
  25063. this._areLightsDirty = true;
  25064. this._areFresnelDirty = true;
  25065. this._areMiscDirty = true;
  25066. this._areImageProcessingDirty = true;
  25067. this._isDirty = true;
  25068. };
  25069. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25070. this._areImageProcessingDirty = true;
  25071. this._isDirty = true;
  25072. };
  25073. MaterialDefines.prototype.markAsLightDirty = function () {
  25074. this._areLightsDirty = true;
  25075. this._isDirty = true;
  25076. };
  25077. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25078. this._areAttributesDirty = true;
  25079. this._isDirty = true;
  25080. };
  25081. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25082. this._areTexturesDirty = true;
  25083. this._isDirty = true;
  25084. };
  25085. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25086. this._areFresnelDirty = true;
  25087. this._isDirty = true;
  25088. };
  25089. MaterialDefines.prototype.markAsMiscDirty = function () {
  25090. this._areMiscDirty = true;
  25091. this._isDirty = true;
  25092. };
  25093. MaterialDefines.prototype.rebuild = function () {
  25094. if (this._keys) {
  25095. delete this._keys;
  25096. }
  25097. this._keys = [];
  25098. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25099. var key = _a[_i];
  25100. if (key[0] === "_") {
  25101. continue;
  25102. }
  25103. this._keys.push(key);
  25104. }
  25105. };
  25106. MaterialDefines.prototype.isEqual = function (other) {
  25107. if (this._keys.length !== other._keys.length) {
  25108. return false;
  25109. }
  25110. for (var index = 0; index < this._keys.length; index++) {
  25111. var prop = this._keys[index];
  25112. if (this[prop] !== other[prop]) {
  25113. return false;
  25114. }
  25115. }
  25116. return true;
  25117. };
  25118. MaterialDefines.prototype.cloneTo = function (other) {
  25119. if (this._keys.length !== other._keys.length) {
  25120. other._keys = this._keys.slice(0);
  25121. }
  25122. for (var index = 0; index < this._keys.length; index++) {
  25123. var prop = this._keys[index];
  25124. other[prop] = this[prop];
  25125. }
  25126. };
  25127. MaterialDefines.prototype.reset = function () {
  25128. for (var index = 0; index < this._keys.length; index++) {
  25129. var prop = this._keys[index];
  25130. if (typeof (this[prop]) === "number") {
  25131. this[prop] = 0;
  25132. }
  25133. else {
  25134. this[prop] = false;
  25135. }
  25136. }
  25137. };
  25138. MaterialDefines.prototype.toString = function () {
  25139. var result = "";
  25140. for (var index = 0; index < this._keys.length; index++) {
  25141. var prop = this._keys[index];
  25142. var value = this[prop];
  25143. if (typeof (value) === "number") {
  25144. result += "#define " + prop + " " + this[prop] + "\n";
  25145. }
  25146. else if (value) {
  25147. result += "#define " + prop + "\n";
  25148. }
  25149. }
  25150. return result;
  25151. };
  25152. return MaterialDefines;
  25153. }());
  25154. BABYLON.MaterialDefines = MaterialDefines;
  25155. var Material = (function () {
  25156. function Material(name, scene, doNotAdd) {
  25157. this.checkReadyOnEveryCall = false;
  25158. this.checkReadyOnlyOnce = false;
  25159. this.state = "";
  25160. this.alpha = 1.0;
  25161. this._backFaceCulling = true;
  25162. this.doNotSerialize = false;
  25163. this.storeEffectOnSubMeshes = false;
  25164. /**
  25165. * An event triggered when the material is disposed.
  25166. * @type {BABYLON.Observable}
  25167. */
  25168. this.onDisposeObservable = new BABYLON.Observable();
  25169. /**
  25170. * An event triggered when the material is bound.
  25171. * @type {BABYLON.Observable}
  25172. */
  25173. this.onBindObservable = new BABYLON.Observable();
  25174. /**
  25175. * An event triggered when the material is unbound.
  25176. * @type {BABYLON.Observable}
  25177. */
  25178. this.onUnBindObservable = new BABYLON.Observable();
  25179. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25180. this.disableDepthWrite = false;
  25181. this._fogEnabled = true;
  25182. this.pointSize = 1.0;
  25183. this.zOffset = 0;
  25184. this._wasPreviouslyReady = false;
  25185. this._fillMode = Material.TriangleFillMode;
  25186. this.name = name;
  25187. this.id = name || BABYLON.Tools.RandomId();
  25188. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25189. if (this._scene.useRightHandedSystem) {
  25190. this.sideOrientation = Material.ClockWiseSideOrientation;
  25191. }
  25192. else {
  25193. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25194. }
  25195. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25196. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  25197. if (!doNotAdd) {
  25198. this._scene.materials.push(this);
  25199. }
  25200. }
  25201. Object.defineProperty(Material, "TriangleFillMode", {
  25202. get: function () {
  25203. return Material._TriangleFillMode;
  25204. },
  25205. enumerable: true,
  25206. configurable: true
  25207. });
  25208. Object.defineProperty(Material, "WireFrameFillMode", {
  25209. get: function () {
  25210. return Material._WireFrameFillMode;
  25211. },
  25212. enumerable: true,
  25213. configurable: true
  25214. });
  25215. Object.defineProperty(Material, "PointFillMode", {
  25216. get: function () {
  25217. return Material._PointFillMode;
  25218. },
  25219. enumerable: true,
  25220. configurable: true
  25221. });
  25222. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25223. get: function () {
  25224. return Material._ClockWiseSideOrientation;
  25225. },
  25226. enumerable: true,
  25227. configurable: true
  25228. });
  25229. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25230. get: function () {
  25231. return Material._CounterClockWiseSideOrientation;
  25232. },
  25233. enumerable: true,
  25234. configurable: true
  25235. });
  25236. Object.defineProperty(Material, "TextureDirtyFlag", {
  25237. get: function () {
  25238. return Material._TextureDirtyFlag;
  25239. },
  25240. enumerable: true,
  25241. configurable: true
  25242. });
  25243. Object.defineProperty(Material, "LightDirtyFlag", {
  25244. get: function () {
  25245. return Material._LightDirtyFlag;
  25246. },
  25247. enumerable: true,
  25248. configurable: true
  25249. });
  25250. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25251. get: function () {
  25252. return Material._FresnelDirtyFlag;
  25253. },
  25254. enumerable: true,
  25255. configurable: true
  25256. });
  25257. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25258. get: function () {
  25259. return Material._AttributesDirtyFlag;
  25260. },
  25261. enumerable: true,
  25262. configurable: true
  25263. });
  25264. Object.defineProperty(Material, "MiscDirtyFlag", {
  25265. get: function () {
  25266. return Material._MiscDirtyFlag;
  25267. },
  25268. enumerable: true,
  25269. configurable: true
  25270. });
  25271. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25272. get: function () {
  25273. return this._backFaceCulling;
  25274. },
  25275. set: function (value) {
  25276. if (this._backFaceCulling === value) {
  25277. return;
  25278. }
  25279. this._backFaceCulling = value;
  25280. this.markAsDirty(Material.TextureDirtyFlag);
  25281. },
  25282. enumerable: true,
  25283. configurable: true
  25284. });
  25285. Object.defineProperty(Material.prototype, "onDispose", {
  25286. set: function (callback) {
  25287. if (this._onDisposeObserver) {
  25288. this.onDisposeObservable.remove(this._onDisposeObserver);
  25289. }
  25290. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25291. },
  25292. enumerable: true,
  25293. configurable: true
  25294. });
  25295. Object.defineProperty(Material.prototype, "onBind", {
  25296. set: function (callback) {
  25297. if (this._onBindObserver) {
  25298. this.onBindObservable.remove(this._onBindObserver);
  25299. }
  25300. this._onBindObserver = this.onBindObservable.add(callback);
  25301. },
  25302. enumerable: true,
  25303. configurable: true
  25304. });
  25305. Object.defineProperty(Material.prototype, "fogEnabled", {
  25306. get: function () {
  25307. return this._fogEnabled;
  25308. },
  25309. set: function (value) {
  25310. if (this._fogEnabled === value) {
  25311. return;
  25312. }
  25313. this._fogEnabled = value;
  25314. this.markAsDirty(Material.MiscDirtyFlag);
  25315. },
  25316. enumerable: true,
  25317. configurable: true
  25318. });
  25319. Object.defineProperty(Material.prototype, "wireframe", {
  25320. get: function () {
  25321. return this._fillMode === Material.WireFrameFillMode;
  25322. },
  25323. set: function (value) {
  25324. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25325. },
  25326. enumerable: true,
  25327. configurable: true
  25328. });
  25329. Object.defineProperty(Material.prototype, "pointsCloud", {
  25330. get: function () {
  25331. return this._fillMode === Material.PointFillMode;
  25332. },
  25333. set: function (value) {
  25334. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25335. },
  25336. enumerable: true,
  25337. configurable: true
  25338. });
  25339. Object.defineProperty(Material.prototype, "fillMode", {
  25340. get: function () {
  25341. return this._fillMode;
  25342. },
  25343. set: function (value) {
  25344. if (this._fillMode === value) {
  25345. return;
  25346. }
  25347. this._fillMode = value;
  25348. this.markAsDirty(Material.MiscDirtyFlag);
  25349. },
  25350. enumerable: true,
  25351. configurable: true
  25352. });
  25353. /**
  25354. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25355. * subclasses should override adding information pertainent to themselves
  25356. */
  25357. Material.prototype.toString = function (fullDetails) {
  25358. var ret = "Name: " + this.name;
  25359. if (fullDetails) {
  25360. }
  25361. return ret;
  25362. };
  25363. /**
  25364. * Child classes can use it to update shaders
  25365. */
  25366. Material.prototype.getClassName = function () {
  25367. return "Material";
  25368. };
  25369. Object.defineProperty(Material.prototype, "isFrozen", {
  25370. get: function () {
  25371. return this.checkReadyOnlyOnce;
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. Material.prototype.freeze = function () {
  25377. this.checkReadyOnlyOnce = true;
  25378. };
  25379. Material.prototype.unfreeze = function () {
  25380. this.checkReadyOnlyOnce = false;
  25381. };
  25382. Material.prototype.isReady = function (mesh, useInstances) {
  25383. return true;
  25384. };
  25385. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25386. return false;
  25387. };
  25388. Material.prototype.getEffect = function () {
  25389. return this._effect;
  25390. };
  25391. Material.prototype.getScene = function () {
  25392. return this._scene;
  25393. };
  25394. Material.prototype.needAlphaBlending = function () {
  25395. return (this.alpha < 1.0);
  25396. };
  25397. Material.prototype.needAlphaTesting = function () {
  25398. return false;
  25399. };
  25400. Material.prototype.getAlphaTestTexture = function () {
  25401. return null;
  25402. };
  25403. Material.prototype.markDirty = function () {
  25404. this._wasPreviouslyReady = false;
  25405. };
  25406. Material.prototype._preBind = function (effect) {
  25407. var engine = this._scene.getEngine();
  25408. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25409. engine.enableEffect(effect ? effect : this._effect);
  25410. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25411. };
  25412. Material.prototype.bind = function (world, mesh) {
  25413. };
  25414. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25415. };
  25416. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25417. };
  25418. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25419. sceneUbo.bindToEffect(effect, "Scene");
  25420. };
  25421. Material.prototype.bindView = function (effect) {
  25422. if (!this._useUBO) {
  25423. effect.setMatrix("view", this.getScene().getViewMatrix());
  25424. }
  25425. else {
  25426. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25427. }
  25428. };
  25429. Material.prototype.bindViewProjection = function (effect) {
  25430. if (!this._useUBO) {
  25431. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25432. }
  25433. else {
  25434. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25435. }
  25436. };
  25437. Material.prototype._afterBind = function (mesh) {
  25438. this._scene._cachedMaterial = this;
  25439. if (mesh) {
  25440. this._scene._cachedVisibility = mesh.visibility;
  25441. }
  25442. else {
  25443. this._scene._cachedVisibility = 1;
  25444. }
  25445. this.onBindObservable.notifyObservers(mesh);
  25446. if (this.disableDepthWrite) {
  25447. var engine = this._scene.getEngine();
  25448. this._cachedDepthWriteState = engine.getDepthWrite();
  25449. engine.setDepthWrite(false);
  25450. }
  25451. };
  25452. Material.prototype.unbind = function () {
  25453. this.onUnBindObservable.notifyObservers(this);
  25454. if (this.disableDepthWrite) {
  25455. var engine = this._scene.getEngine();
  25456. engine.setDepthWrite(this._cachedDepthWriteState);
  25457. }
  25458. };
  25459. Material.prototype.getActiveTextures = function () {
  25460. return [];
  25461. };
  25462. Material.prototype.hasTexture = function (texture) {
  25463. return false;
  25464. };
  25465. Material.prototype.clone = function (name) {
  25466. return null;
  25467. };
  25468. Material.prototype.getBindedMeshes = function () {
  25469. var result = new Array();
  25470. for (var index = 0; index < this._scene.meshes.length; index++) {
  25471. var mesh = this._scene.meshes[index];
  25472. if (mesh.material === this) {
  25473. result.push(mesh);
  25474. }
  25475. }
  25476. return result;
  25477. };
  25478. /**
  25479. * Force shader compilation including textures ready check
  25480. */
  25481. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25482. var _this = this;
  25483. var subMesh = new BABYLON.BaseSubMesh();
  25484. var scene = this.getScene();
  25485. var engine = scene.getEngine();
  25486. var checkReady = function () {
  25487. if (!_this._scene || !_this._scene.getEngine()) {
  25488. return;
  25489. }
  25490. if (subMesh._materialDefines) {
  25491. subMesh._materialDefines._renderId = -1;
  25492. }
  25493. var alphaTestState = engine.getAlphaTesting();
  25494. var clipPlaneState = scene.clipPlane;
  25495. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25496. if (options && options.clipPlane) {
  25497. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25498. }
  25499. if (_this.storeEffectOnSubMeshes) {
  25500. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25501. if (onCompiled) {
  25502. onCompiled(_this);
  25503. }
  25504. }
  25505. else {
  25506. setTimeout(checkReady, 16);
  25507. }
  25508. }
  25509. else {
  25510. if (_this.isReady(mesh)) {
  25511. if (onCompiled) {
  25512. onCompiled(_this);
  25513. }
  25514. }
  25515. else {
  25516. setTimeout(checkReady, 16);
  25517. }
  25518. }
  25519. engine.setAlphaTesting(alphaTestState);
  25520. if (options && options.clipPlane) {
  25521. scene.clipPlane = clipPlaneState;
  25522. }
  25523. };
  25524. checkReady();
  25525. };
  25526. Material.prototype.markAsDirty = function (flag) {
  25527. if (flag & Material.TextureDirtyFlag) {
  25528. this._markAllSubMeshesAsTexturesDirty();
  25529. }
  25530. if (flag & Material.LightDirtyFlag) {
  25531. this._markAllSubMeshesAsLightsDirty();
  25532. }
  25533. if (flag & Material.FresnelDirtyFlag) {
  25534. this._markAllSubMeshesAsFresnelDirty();
  25535. }
  25536. if (flag & Material.AttributesDirtyFlag) {
  25537. this._markAllSubMeshesAsAttributesDirty();
  25538. }
  25539. if (flag & Material.MiscDirtyFlag) {
  25540. this._markAllSubMeshesAsMiscDirty();
  25541. }
  25542. this.getScene().resetCachedMaterial();
  25543. };
  25544. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25545. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25546. var mesh = _a[_i];
  25547. if (!mesh.subMeshes) {
  25548. continue;
  25549. }
  25550. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25551. var subMesh = _c[_b];
  25552. if (subMesh.getMaterial() !== this) {
  25553. continue;
  25554. }
  25555. if (!subMesh._materialDefines) {
  25556. continue;
  25557. }
  25558. func(subMesh._materialDefines);
  25559. }
  25560. }
  25561. };
  25562. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25563. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25564. };
  25565. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25566. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25567. };
  25568. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25569. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25570. };
  25571. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25572. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25573. };
  25574. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25575. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25576. };
  25577. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25578. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25579. };
  25580. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25581. // Animations
  25582. this.getScene().stopAnimation(this);
  25583. // Remove from scene
  25584. var index = this._scene.materials.indexOf(this);
  25585. if (index >= 0) {
  25586. this._scene.materials.splice(index, 1);
  25587. }
  25588. // Remove from meshes
  25589. for (index = 0; index < this._scene.meshes.length; index++) {
  25590. var mesh = this._scene.meshes[index];
  25591. if (mesh.material === this) {
  25592. mesh.material = null;
  25593. if (mesh.geometry) {
  25594. var geometry = mesh.geometry;
  25595. if (this.storeEffectOnSubMeshes) {
  25596. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25597. var subMesh = _a[_i];
  25598. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25599. }
  25600. }
  25601. else {
  25602. geometry._releaseVertexArrayObject(this._effect);
  25603. }
  25604. }
  25605. }
  25606. }
  25607. this._uniformBuffer.dispose();
  25608. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25609. if (forceDisposeEffect && this._effect) {
  25610. if (this.storeEffectOnSubMeshes) {
  25611. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25612. var subMesh = _c[_b];
  25613. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25614. }
  25615. }
  25616. else {
  25617. this._scene.getEngine()._releaseEffect(this._effect);
  25618. }
  25619. this._effect = null;
  25620. }
  25621. // Callback
  25622. this.onDisposeObservable.notifyObservers(this);
  25623. this.onDisposeObservable.clear();
  25624. this.onBindObservable.clear();
  25625. this.onUnBindObservable.clear();
  25626. };
  25627. Material.prototype.serialize = function () {
  25628. return BABYLON.SerializationHelper.Serialize(this);
  25629. };
  25630. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25631. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25632. multiMaterial.id = parsedMultiMaterial.id;
  25633. if (BABYLON.Tags) {
  25634. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25635. }
  25636. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25637. var subMatId = parsedMultiMaterial.materials[matIndex];
  25638. if (subMatId) {
  25639. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25640. }
  25641. else {
  25642. multiMaterial.subMaterials.push(null);
  25643. }
  25644. }
  25645. return multiMaterial;
  25646. };
  25647. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25648. if (!parsedMaterial.customType) {
  25649. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25650. }
  25651. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25652. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25653. if (!BABYLON.LegacyPBRMaterial) {
  25654. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25655. return;
  25656. }
  25657. }
  25658. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25659. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25660. ;
  25661. };
  25662. Material._TriangleFillMode = 0;
  25663. Material._WireFrameFillMode = 1;
  25664. Material._PointFillMode = 2;
  25665. Material._ClockWiseSideOrientation = 0;
  25666. Material._CounterClockWiseSideOrientation = 1;
  25667. Material._TextureDirtyFlag = 1;
  25668. Material._LightDirtyFlag = 2;
  25669. Material._FresnelDirtyFlag = 4;
  25670. Material._AttributesDirtyFlag = 8;
  25671. Material._MiscDirtyFlag = 16;
  25672. __decorate([
  25673. BABYLON.serialize()
  25674. ], Material.prototype, "id", void 0);
  25675. __decorate([
  25676. BABYLON.serialize()
  25677. ], Material.prototype, "name", void 0);
  25678. __decorate([
  25679. BABYLON.serialize()
  25680. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25681. __decorate([
  25682. BABYLON.serialize()
  25683. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25684. __decorate([
  25685. BABYLON.serialize()
  25686. ], Material.prototype, "state", void 0);
  25687. __decorate([
  25688. BABYLON.serialize()
  25689. ], Material.prototype, "alpha", void 0);
  25690. __decorate([
  25691. BABYLON.serialize("backFaceCulling")
  25692. ], Material.prototype, "_backFaceCulling", void 0);
  25693. __decorate([
  25694. BABYLON.serialize()
  25695. ], Material.prototype, "sideOrientation", void 0);
  25696. __decorate([
  25697. BABYLON.serialize()
  25698. ], Material.prototype, "alphaMode", void 0);
  25699. __decorate([
  25700. BABYLON.serialize()
  25701. ], Material.prototype, "disableDepthWrite", void 0);
  25702. __decorate([
  25703. BABYLON.serialize("fogEnabled")
  25704. ], Material.prototype, "_fogEnabled", void 0);
  25705. __decorate([
  25706. BABYLON.serialize()
  25707. ], Material.prototype, "pointSize", void 0);
  25708. __decorate([
  25709. BABYLON.serialize()
  25710. ], Material.prototype, "zOffset", void 0);
  25711. __decorate([
  25712. BABYLON.serialize()
  25713. ], Material.prototype, "wireframe", null);
  25714. __decorate([
  25715. BABYLON.serialize()
  25716. ], Material.prototype, "pointsCloud", null);
  25717. __decorate([
  25718. BABYLON.serialize()
  25719. ], Material.prototype, "fillMode", null);
  25720. return Material;
  25721. }());
  25722. BABYLON.Material = Material;
  25723. })(BABYLON || (BABYLON = {}));
  25724. //# sourceMappingURL=babylon.material.js.map
  25725. var BABYLON;
  25726. (function (BABYLON) {
  25727. var UniformBuffer = (function () {
  25728. /**
  25729. * Uniform buffer objects.
  25730. *
  25731. * Handles blocks of uniform on the GPU.
  25732. *
  25733. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25734. *
  25735. * For more information, please refer to :
  25736. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25737. */
  25738. function UniformBuffer(engine, data, dynamic) {
  25739. this._engine = engine;
  25740. this._noUBO = engine.webGLVersion === 1;
  25741. this._dynamic = dynamic;
  25742. this._data = data || [];
  25743. this._uniformLocations = {};
  25744. this._uniformSizes = {};
  25745. this._uniformLocationPointer = 0;
  25746. this._needSync = false;
  25747. if (this._noUBO) {
  25748. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25749. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25750. this.updateFloat = this._updateFloatForEffect;
  25751. this.updateFloat2 = this._updateFloat2ForEffect;
  25752. this.updateFloat3 = this._updateFloat3ForEffect;
  25753. this.updateFloat4 = this._updateFloat4ForEffect;
  25754. this.updateMatrix = this._updateMatrixForEffect;
  25755. this.updateVector3 = this._updateVector3ForEffect;
  25756. this.updateVector4 = this._updateVector4ForEffect;
  25757. this.updateColor3 = this._updateColor3ForEffect;
  25758. this.updateColor4 = this._updateColor4ForEffect;
  25759. }
  25760. else {
  25761. this._engine._uniformBuffers.push(this);
  25762. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25763. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25764. this.updateFloat = this._updateFloatForUniform;
  25765. this.updateFloat2 = this._updateFloat2ForUniform;
  25766. this.updateFloat3 = this._updateFloat3ForUniform;
  25767. this.updateFloat4 = this._updateFloat4ForUniform;
  25768. this.updateMatrix = this._updateMatrixForUniform;
  25769. this.updateVector3 = this._updateVector3ForUniform;
  25770. this.updateVector4 = this._updateVector4ForUniform;
  25771. this.updateColor3 = this._updateColor3ForUniform;
  25772. this.updateColor4 = this._updateColor4ForUniform;
  25773. }
  25774. }
  25775. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25776. // Properties
  25777. /**
  25778. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25779. * or just falling back on setUniformXXX calls.
  25780. */
  25781. get: function () {
  25782. return !this._noUBO;
  25783. },
  25784. enumerable: true,
  25785. configurable: true
  25786. });
  25787. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25788. /**
  25789. * Indicates if the WebGL underlying uniform buffer is in sync
  25790. * with the javascript cache data.
  25791. */
  25792. get: function () {
  25793. return !this._needSync;
  25794. },
  25795. enumerable: true,
  25796. configurable: true
  25797. });
  25798. /**
  25799. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25800. * Also, a dynamic UniformBuffer will disable cache verification and always
  25801. * update the underlying WebGL uniform buffer to the GPU.
  25802. */
  25803. UniformBuffer.prototype.isDynamic = function () {
  25804. return this._dynamic;
  25805. };
  25806. /**
  25807. * The data cache on JS side.
  25808. */
  25809. UniformBuffer.prototype.getData = function () {
  25810. return this._bufferData;
  25811. };
  25812. /**
  25813. * The underlying WebGL Uniform buffer.
  25814. */
  25815. UniformBuffer.prototype.getBuffer = function () {
  25816. return this._buffer;
  25817. };
  25818. /**
  25819. * std140 layout specifies how to align data within an UBO structure.
  25820. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25821. * for specs.
  25822. */
  25823. UniformBuffer.prototype._fillAlignment = function (size) {
  25824. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25825. // and 4x4 matrices
  25826. // TODO : change if other types are used
  25827. var alignment;
  25828. if (size <= 2) {
  25829. alignment = size;
  25830. }
  25831. else {
  25832. alignment = 4;
  25833. }
  25834. if ((this._uniformLocationPointer % alignment) !== 0) {
  25835. var oldPointer = this._uniformLocationPointer;
  25836. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25837. var diff = this._uniformLocationPointer - oldPointer;
  25838. for (var i = 0; i < diff; i++) {
  25839. this._data.push(0);
  25840. }
  25841. }
  25842. };
  25843. /**
  25844. * Adds an uniform in the buffer.
  25845. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25846. * for the layout to be correct !
  25847. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25848. * @param {number|number[]} size Data size, or data directly.
  25849. */
  25850. UniformBuffer.prototype.addUniform = function (name, size) {
  25851. if (this._noUBO) {
  25852. return;
  25853. }
  25854. if (this._uniformLocations[name] !== undefined) {
  25855. // Already existing uniform
  25856. return;
  25857. }
  25858. // This function must be called in the order of the shader layout !
  25859. // size can be the size of the uniform, or data directly
  25860. var data;
  25861. if (size instanceof Array) {
  25862. data = size;
  25863. size = data.length;
  25864. }
  25865. else {
  25866. size = size;
  25867. data = [];
  25868. // Fill with zeros
  25869. for (var i = 0; i < size; i++) {
  25870. data.push(0);
  25871. }
  25872. }
  25873. this._fillAlignment(size);
  25874. this._uniformSizes[name] = size;
  25875. this._uniformLocations[name] = this._uniformLocationPointer;
  25876. this._uniformLocationPointer += size;
  25877. for (var i = 0; i < size; i++) {
  25878. this._data.push(data[i]);
  25879. }
  25880. this._needSync = true;
  25881. };
  25882. /**
  25883. * Wrapper for addUniform.
  25884. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25885. * @param {Matrix} mat A 4x4 matrix.
  25886. */
  25887. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25888. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25889. };
  25890. /**
  25891. * Wrapper for addUniform.
  25892. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25893. * @param {number} x
  25894. * @param {number} y
  25895. */
  25896. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25897. var temp = [x, y];
  25898. this.addUniform(name, temp);
  25899. };
  25900. /**
  25901. * Wrapper for addUniform.
  25902. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25903. * @param {number} x
  25904. * @param {number} y
  25905. * @param {number} z
  25906. */
  25907. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25908. var temp = [x, y, z];
  25909. this.addUniform(name, temp);
  25910. };
  25911. /**
  25912. * Wrapper for addUniform.
  25913. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25914. * @param {Color3} color
  25915. */
  25916. UniformBuffer.prototype.addColor3 = function (name, color) {
  25917. var temp = [];
  25918. color.toArray(temp);
  25919. this.addUniform(name, temp);
  25920. };
  25921. /**
  25922. * Wrapper for addUniform.
  25923. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25924. * @param {Color3} color
  25925. * @param {number} alpha
  25926. */
  25927. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25928. var temp = [];
  25929. color.toArray(temp);
  25930. temp.push(alpha);
  25931. this.addUniform(name, temp);
  25932. };
  25933. /**
  25934. * Wrapper for addUniform.
  25935. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25936. * @param {Vector3} vector
  25937. */
  25938. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25939. var temp = [];
  25940. vector.toArray(temp);
  25941. this.addUniform(name, temp);
  25942. };
  25943. /**
  25944. * Wrapper for addUniform.
  25945. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25946. */
  25947. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25948. this.addUniform(name, 12);
  25949. };
  25950. /**
  25951. * Wrapper for addUniform.
  25952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25953. */
  25954. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25955. this.addUniform(name, 8);
  25956. };
  25957. /**
  25958. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25959. */
  25960. UniformBuffer.prototype.create = function () {
  25961. if (this._noUBO) {
  25962. return;
  25963. }
  25964. if (this._buffer) {
  25965. return; // nothing to do
  25966. }
  25967. // See spec, alignment must be filled as a vec4
  25968. this._fillAlignment(4);
  25969. this._bufferData = new Float32Array(this._data);
  25970. this._rebuild();
  25971. this._needSync = true;
  25972. };
  25973. UniformBuffer.prototype._rebuild = function () {
  25974. if (this._noUBO) {
  25975. return;
  25976. }
  25977. if (this._dynamic) {
  25978. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25979. }
  25980. else {
  25981. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25982. }
  25983. };
  25984. /**
  25985. * Updates the WebGL Uniform Buffer on the GPU.
  25986. * If the `dynamic` flag is set to true, no cache comparison is done.
  25987. * Otherwise, the buffer will be updated only if the cache differs.
  25988. */
  25989. UniformBuffer.prototype.update = function () {
  25990. if (!this._buffer) {
  25991. this.create();
  25992. return;
  25993. }
  25994. if (!this._dynamic && !this._needSync) {
  25995. return;
  25996. }
  25997. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25998. this._needSync = false;
  25999. };
  26000. /**
  26001. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26002. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26003. * @param {number[]|Float32Array} data Flattened data
  26004. * @param {number} size Size of the data.
  26005. */
  26006. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26007. var location = this._uniformLocations[uniformName];
  26008. if (location === undefined) {
  26009. if (this._buffer) {
  26010. // Cannot add an uniform if the buffer is already created
  26011. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26012. return;
  26013. }
  26014. this.addUniform(uniformName, size);
  26015. location = this._uniformLocations[uniformName];
  26016. }
  26017. if (!this._buffer) {
  26018. this.create();
  26019. }
  26020. if (!this._dynamic) {
  26021. // Cache for static uniform buffers
  26022. var changed = false;
  26023. for (var i = 0; i < size; i++) {
  26024. if (this._bufferData[location + i] !== data[i]) {
  26025. changed = true;
  26026. this._bufferData[location + i] = data[i];
  26027. }
  26028. }
  26029. this._needSync = this._needSync || changed;
  26030. }
  26031. else {
  26032. // No cache for dynamic
  26033. for (var i = 0; i < size; i++) {
  26034. this._bufferData[location + i] = data[i];
  26035. }
  26036. }
  26037. };
  26038. // Update methods
  26039. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26040. // To match std140, matrix must be realigned
  26041. for (var i = 0; i < 3; i++) {
  26042. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26043. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26044. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26045. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26046. }
  26047. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26048. };
  26049. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26050. this._currentEffect.setMatrix3x3(name, matrix);
  26051. };
  26052. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26053. this._currentEffect.setMatrix2x2(name, matrix);
  26054. };
  26055. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26056. // To match std140, matrix must be realigned
  26057. for (var i = 0; i < 2; i++) {
  26058. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26059. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26060. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26061. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26062. }
  26063. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26064. };
  26065. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26066. this._currentEffect.setFloat(name, x);
  26067. };
  26068. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26069. UniformBuffer._tempBuffer[0] = x;
  26070. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26071. };
  26072. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26073. if (suffix === void 0) { suffix = ""; }
  26074. this._currentEffect.setFloat2(name + suffix, x, y);
  26075. };
  26076. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26077. if (suffix === void 0) { suffix = ""; }
  26078. UniformBuffer._tempBuffer[0] = x;
  26079. UniformBuffer._tempBuffer[1] = y;
  26080. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26081. };
  26082. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26083. if (suffix === void 0) { suffix = ""; }
  26084. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26085. };
  26086. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26087. if (suffix === void 0) { suffix = ""; }
  26088. UniformBuffer._tempBuffer[0] = x;
  26089. UniformBuffer._tempBuffer[1] = y;
  26090. UniformBuffer._tempBuffer[2] = z;
  26091. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26092. };
  26093. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26094. if (suffix === void 0) { suffix = ""; }
  26095. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26096. };
  26097. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26098. if (suffix === void 0) { suffix = ""; }
  26099. UniformBuffer._tempBuffer[0] = x;
  26100. UniformBuffer._tempBuffer[1] = y;
  26101. UniformBuffer._tempBuffer[2] = z;
  26102. UniformBuffer._tempBuffer[3] = w;
  26103. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26104. };
  26105. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26106. this._currentEffect.setMatrix(name, mat);
  26107. };
  26108. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26109. this.updateUniform(name, mat.toArray(), 16);
  26110. };
  26111. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26112. this._currentEffect.setVector3(name, vector);
  26113. };
  26114. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26115. vector.toArray(UniformBuffer._tempBuffer);
  26116. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26117. };
  26118. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26119. this._currentEffect.setVector4(name, vector);
  26120. };
  26121. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26122. vector.toArray(UniformBuffer._tempBuffer);
  26123. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26124. };
  26125. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26126. if (suffix === void 0) { suffix = ""; }
  26127. this._currentEffect.setColor3(name + suffix, color);
  26128. };
  26129. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26130. if (suffix === void 0) { suffix = ""; }
  26131. color.toArray(UniformBuffer._tempBuffer);
  26132. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26133. };
  26134. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26135. if (suffix === void 0) { suffix = ""; }
  26136. this._currentEffect.setColor4(name + suffix, color, alpha);
  26137. };
  26138. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26139. if (suffix === void 0) { suffix = ""; }
  26140. color.toArray(UniformBuffer._tempBuffer);
  26141. UniformBuffer._tempBuffer[3] = alpha;
  26142. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26143. };
  26144. /**
  26145. * Sets a sampler uniform on the effect.
  26146. * @param {string} name Name of the sampler.
  26147. * @param {Texture} texture
  26148. */
  26149. UniformBuffer.prototype.setTexture = function (name, texture) {
  26150. this._currentEffect.setTexture(name, texture);
  26151. };
  26152. /**
  26153. * Directly updates the value of the uniform in the cache AND on the GPU.
  26154. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26155. * @param {number[]|Float32Array} data Flattened data
  26156. */
  26157. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26158. this.updateUniform(uniformName, data, data.length);
  26159. this.update();
  26160. };
  26161. /**
  26162. * Binds this uniform buffer to an effect.
  26163. * @param {Effect} effect
  26164. * @param {string} name Name of the uniform block in the shader.
  26165. */
  26166. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26167. this._currentEffect = effect;
  26168. if (this._noUBO) {
  26169. return;
  26170. }
  26171. effect.bindUniformBuffer(this._buffer, name);
  26172. };
  26173. /**
  26174. * Disposes the uniform buffer.
  26175. */
  26176. UniformBuffer.prototype.dispose = function () {
  26177. if (this._noUBO) {
  26178. return;
  26179. }
  26180. var index = this._engine._uniformBuffers.indexOf(this);
  26181. if (index !== -1) {
  26182. this._engine._uniformBuffers.splice(index, 1);
  26183. }
  26184. if (!this._buffer) {
  26185. return;
  26186. }
  26187. if (this._engine._releaseBuffer(this._buffer)) {
  26188. this._buffer = null;
  26189. }
  26190. };
  26191. // Pool for avoiding memory leaks
  26192. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26193. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26194. return UniformBuffer;
  26195. }());
  26196. BABYLON.UniformBuffer = UniformBuffer;
  26197. })(BABYLON || (BABYLON = {}));
  26198. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26199. var BABYLON;
  26200. (function (BABYLON) {
  26201. var PushMaterial = (function (_super) {
  26202. __extends(PushMaterial, _super);
  26203. function PushMaterial(name, scene) {
  26204. var _this = _super.call(this, name, scene) || this;
  26205. _this.storeEffectOnSubMeshes = true;
  26206. return _this;
  26207. }
  26208. PushMaterial.prototype.getEffect = function () {
  26209. return this._activeEffect;
  26210. };
  26211. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26212. if (!mesh) {
  26213. return false;
  26214. }
  26215. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26216. return true;
  26217. }
  26218. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26219. };
  26220. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26221. this._activeEffect.setMatrix("world", world);
  26222. };
  26223. PushMaterial.prototype.bind = function (world, mesh) {
  26224. if (!mesh) {
  26225. return;
  26226. }
  26227. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26228. };
  26229. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26230. _super.prototype._afterBind.call(this, mesh);
  26231. this.getScene()._cachedEffect = effect;
  26232. };
  26233. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26234. if (visibility === void 0) { visibility = 1; }
  26235. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26236. };
  26237. return PushMaterial;
  26238. }(BABYLON.Material));
  26239. BABYLON.PushMaterial = PushMaterial;
  26240. })(BABYLON || (BABYLON = {}));
  26241. //# sourceMappingURL=babylon.pushMaterial.js.map
  26242. var BABYLON;
  26243. (function (BABYLON) {
  26244. var VertexData = (function () {
  26245. function VertexData() {
  26246. }
  26247. VertexData.prototype.set = function (data, kind) {
  26248. switch (kind) {
  26249. case BABYLON.VertexBuffer.PositionKind:
  26250. this.positions = data;
  26251. break;
  26252. case BABYLON.VertexBuffer.NormalKind:
  26253. this.normals = data;
  26254. break;
  26255. case BABYLON.VertexBuffer.TangentKind:
  26256. this.tangents = data;
  26257. break;
  26258. case BABYLON.VertexBuffer.UVKind:
  26259. this.uvs = data;
  26260. break;
  26261. case BABYLON.VertexBuffer.UV2Kind:
  26262. this.uvs2 = data;
  26263. break;
  26264. case BABYLON.VertexBuffer.UV3Kind:
  26265. this.uvs3 = data;
  26266. break;
  26267. case BABYLON.VertexBuffer.UV4Kind:
  26268. this.uvs4 = data;
  26269. break;
  26270. case BABYLON.VertexBuffer.UV5Kind:
  26271. this.uvs5 = data;
  26272. break;
  26273. case BABYLON.VertexBuffer.UV6Kind:
  26274. this.uvs6 = data;
  26275. break;
  26276. case BABYLON.VertexBuffer.ColorKind:
  26277. this.colors = data;
  26278. break;
  26279. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26280. this.matricesIndices = data;
  26281. break;
  26282. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26283. this.matricesWeights = data;
  26284. break;
  26285. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26286. this.matricesIndicesExtra = data;
  26287. break;
  26288. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26289. this.matricesWeightsExtra = data;
  26290. break;
  26291. }
  26292. };
  26293. /**
  26294. * Associates the vertexData to the passed Mesh.
  26295. * Sets it as updatable or not (default `false`).
  26296. * Returns the VertexData.
  26297. */
  26298. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26299. this._applyTo(mesh, updatable);
  26300. return this;
  26301. };
  26302. /**
  26303. * Associates the vertexData to the passed Geometry.
  26304. * Sets it as updatable or not (default `false`).
  26305. * Returns the VertexData.
  26306. */
  26307. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26308. this._applyTo(geometry, updatable);
  26309. return this;
  26310. };
  26311. /**
  26312. * Updates the associated mesh.
  26313. * Returns the VertexData.
  26314. */
  26315. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26316. this._update(mesh);
  26317. return this;
  26318. };
  26319. /**
  26320. * Updates the associated geometry.
  26321. * Returns the VertexData.
  26322. */
  26323. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26324. this._update(geometry);
  26325. return this;
  26326. };
  26327. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26328. if (this.positions) {
  26329. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26330. }
  26331. if (this.normals) {
  26332. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26333. }
  26334. if (this.tangents) {
  26335. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26336. }
  26337. if (this.uvs) {
  26338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26339. }
  26340. if (this.uvs2) {
  26341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26342. }
  26343. if (this.uvs3) {
  26344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26345. }
  26346. if (this.uvs4) {
  26347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26348. }
  26349. if (this.uvs5) {
  26350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26351. }
  26352. if (this.uvs6) {
  26353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26354. }
  26355. if (this.colors) {
  26356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26357. }
  26358. if (this.matricesIndices) {
  26359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26360. }
  26361. if (this.matricesWeights) {
  26362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26363. }
  26364. if (this.matricesIndicesExtra) {
  26365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26366. }
  26367. if (this.matricesWeightsExtra) {
  26368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26369. }
  26370. if (this.indices) {
  26371. meshOrGeometry.setIndices(this.indices);
  26372. }
  26373. return this;
  26374. };
  26375. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26376. if (this.positions) {
  26377. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26378. }
  26379. if (this.normals) {
  26380. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26381. }
  26382. if (this.tangents) {
  26383. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26384. }
  26385. if (this.uvs) {
  26386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26387. }
  26388. if (this.uvs2) {
  26389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26390. }
  26391. if (this.uvs3) {
  26392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26393. }
  26394. if (this.uvs4) {
  26395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26396. }
  26397. if (this.uvs5) {
  26398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26399. }
  26400. if (this.uvs6) {
  26401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26402. }
  26403. if (this.colors) {
  26404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26405. }
  26406. if (this.matricesIndices) {
  26407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26408. }
  26409. if (this.matricesWeights) {
  26410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26411. }
  26412. if (this.matricesIndicesExtra) {
  26413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26414. }
  26415. if (this.matricesWeightsExtra) {
  26416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26417. }
  26418. if (this.indices) {
  26419. meshOrGeometry.setIndices(this.indices);
  26420. }
  26421. return this;
  26422. };
  26423. /**
  26424. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26425. * Returns the VertexData.
  26426. */
  26427. VertexData.prototype.transform = function (matrix) {
  26428. var transformed = BABYLON.Vector3.Zero();
  26429. var index;
  26430. if (this.positions) {
  26431. var position = BABYLON.Vector3.Zero();
  26432. for (index = 0; index < this.positions.length; index += 3) {
  26433. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26434. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26435. this.positions[index] = transformed.x;
  26436. this.positions[index + 1] = transformed.y;
  26437. this.positions[index + 2] = transformed.z;
  26438. }
  26439. }
  26440. if (this.normals) {
  26441. var normal = BABYLON.Vector3.Zero();
  26442. for (index = 0; index < this.normals.length; index += 3) {
  26443. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26444. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26445. this.normals[index] = transformed.x;
  26446. this.normals[index + 1] = transformed.y;
  26447. this.normals[index + 2] = transformed.z;
  26448. }
  26449. }
  26450. if (this.tangents) {
  26451. var tangent = BABYLON.Vector4.Zero();
  26452. var tangentTransformed = BABYLON.Vector4.Zero();
  26453. for (index = 0; index < this.tangents.length; index += 4) {
  26454. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26455. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26456. this.tangents[index] = tangentTransformed.x;
  26457. this.tangents[index + 1] = tangentTransformed.y;
  26458. this.tangents[index + 2] = tangentTransformed.z;
  26459. this.tangents[index + 3] = tangentTransformed.w;
  26460. }
  26461. }
  26462. return this;
  26463. };
  26464. /**
  26465. * Merges the passed VertexData into the current one.
  26466. * Returns the modified VertexData.
  26467. */
  26468. VertexData.prototype.merge = function (other) {
  26469. if (other.indices) {
  26470. if (!this.indices) {
  26471. this.indices = [];
  26472. }
  26473. var offset = this.positions ? this.positions.length / 3 : 0;
  26474. for (var index = 0; index < other.indices.length; index++) {
  26475. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26476. this.indices.push(other.indices[index] + offset);
  26477. }
  26478. }
  26479. this.positions = this._mergeElement(this.positions, other.positions);
  26480. this.normals = this._mergeElement(this.normals, other.normals);
  26481. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26482. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26483. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26484. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26485. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26486. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26487. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26488. this.colors = this._mergeElement(this.colors, other.colors);
  26489. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26490. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26491. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26492. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26493. return this;
  26494. };
  26495. VertexData.prototype._mergeElement = function (source, other) {
  26496. if (!other)
  26497. return source;
  26498. if (!source)
  26499. return other;
  26500. var len = other.length + source.length;
  26501. var isSrcTypedArray = source instanceof Float32Array;
  26502. var isOthTypedArray = other instanceof Float32Array;
  26503. // use non-loop method when the source is Float32Array
  26504. if (isSrcTypedArray) {
  26505. var ret32 = new Float32Array(len);
  26506. ret32.set(source);
  26507. ret32.set(other, source.length);
  26508. return ret32;
  26509. // source is number[], when other is also use concat
  26510. }
  26511. else if (!isOthTypedArray) {
  26512. return source.concat(other);
  26513. // source is a number[], but other is a Float32Array, loop required
  26514. }
  26515. else {
  26516. var ret = source.slice(0); // copy source to a separate array
  26517. for (var i = 0, len = other.length; i < len; i++) {
  26518. ret.push(other[i]);
  26519. }
  26520. return ret;
  26521. }
  26522. };
  26523. /**
  26524. * Serializes the VertexData.
  26525. * Returns a serialized object.
  26526. */
  26527. VertexData.prototype.serialize = function () {
  26528. var serializationObject = this.serialize();
  26529. if (this.positions) {
  26530. serializationObject.positions = this.positions;
  26531. }
  26532. if (this.normals) {
  26533. serializationObject.normals = this.normals;
  26534. }
  26535. if (this.tangents) {
  26536. serializationObject.tangents = this.tangents;
  26537. }
  26538. if (this.uvs) {
  26539. serializationObject.uvs = this.uvs;
  26540. }
  26541. if (this.uvs2) {
  26542. serializationObject.uvs2 = this.uvs2;
  26543. }
  26544. if (this.uvs3) {
  26545. serializationObject.uvs3 = this.uvs3;
  26546. }
  26547. if (this.uvs4) {
  26548. serializationObject.uvs4 = this.uvs4;
  26549. }
  26550. if (this.uvs5) {
  26551. serializationObject.uvs5 = this.uvs5;
  26552. }
  26553. if (this.uvs6) {
  26554. serializationObject.uvs6 = this.uvs6;
  26555. }
  26556. if (this.colors) {
  26557. serializationObject.colors = this.colors;
  26558. }
  26559. if (this.matricesIndices) {
  26560. serializationObject.matricesIndices = this.matricesIndices;
  26561. serializationObject.matricesIndices._isExpanded = true;
  26562. }
  26563. if (this.matricesWeights) {
  26564. serializationObject.matricesWeights = this.matricesWeights;
  26565. }
  26566. if (this.matricesIndicesExtra) {
  26567. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26568. serializationObject.matricesIndicesExtra._isExpanded = true;
  26569. }
  26570. if (this.matricesWeightsExtra) {
  26571. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26572. }
  26573. serializationObject.indices = this.indices;
  26574. return serializationObject;
  26575. };
  26576. // Statics
  26577. /**
  26578. * Returns the object VertexData associated to the passed mesh.
  26579. */
  26580. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26581. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26582. };
  26583. /**
  26584. * Returns the object VertexData associated to the passed geometry.
  26585. */
  26586. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26587. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26588. };
  26589. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26590. var result = new VertexData();
  26591. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26592. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26593. }
  26594. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26595. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26596. }
  26597. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26598. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26599. }
  26600. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26601. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26602. }
  26603. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26604. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26605. }
  26606. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26607. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26608. }
  26609. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26610. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26611. }
  26612. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26613. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26614. }
  26615. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26616. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26617. }
  26618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26619. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26620. }
  26621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26622. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26623. }
  26624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26625. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26626. }
  26627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26628. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26629. }
  26630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26631. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26632. }
  26633. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26634. return result;
  26635. };
  26636. /**
  26637. * Creates the vertexData of the Ribbon.
  26638. */
  26639. VertexData.CreateRibbon = function (options) {
  26640. var pathArray = options.pathArray;
  26641. var closeArray = options.closeArray || false;
  26642. var closePath = options.closePath || false;
  26643. var invertUV = options.invertUV || false;
  26644. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26645. var offset = options.offset || defaultOffset;
  26646. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26647. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26648. var customUV = options.uvs;
  26649. var customColors = options.colors;
  26650. var positions = [];
  26651. var indices = [];
  26652. var normals = [];
  26653. var uvs = [];
  26654. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26655. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26656. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26657. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26658. var minlg; // minimal length among all paths from pathArray
  26659. var lg = []; // array of path lengths : nb of vertex per path
  26660. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26661. var p; // path iterator
  26662. var i; // point iterator
  26663. var j; // point iterator
  26664. // if single path in pathArray
  26665. if (pathArray.length < 2) {
  26666. var ar1 = [];
  26667. var ar2 = [];
  26668. for (i = 0; i < pathArray[0].length - offset; i++) {
  26669. ar1.push(pathArray[0][i]);
  26670. ar2.push(pathArray[0][i + offset]);
  26671. }
  26672. pathArray = [ar1, ar2];
  26673. }
  26674. // positions and horizontal distances (u)
  26675. var idc = 0;
  26676. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26677. var path;
  26678. var l;
  26679. minlg = pathArray[0].length;
  26680. var vectlg;
  26681. var dist;
  26682. for (p = 0; p < pathArray.length; p++) {
  26683. uTotalDistance[p] = 0;
  26684. us[p] = [0];
  26685. path = pathArray[p];
  26686. l = path.length;
  26687. minlg = (minlg < l) ? minlg : l;
  26688. j = 0;
  26689. while (j < l) {
  26690. positions.push(path[j].x, path[j].y, path[j].z);
  26691. if (j > 0) {
  26692. vectlg = path[j].subtract(path[j - 1]).length();
  26693. dist = vectlg + uTotalDistance[p];
  26694. us[p].push(dist);
  26695. uTotalDistance[p] = dist;
  26696. }
  26697. j++;
  26698. }
  26699. if (closePath) {
  26700. j--;
  26701. positions.push(path[0].x, path[0].y, path[0].z);
  26702. vectlg = path[j].subtract(path[0]).length();
  26703. dist = vectlg + uTotalDistance[p];
  26704. us[p].push(dist);
  26705. uTotalDistance[p] = dist;
  26706. }
  26707. lg[p] = l + closePathCorr;
  26708. idx[p] = idc;
  26709. idc += (l + closePathCorr);
  26710. }
  26711. // vertical distances (v)
  26712. var path1;
  26713. var path2;
  26714. var vertex1;
  26715. var vertex2;
  26716. for (i = 0; i < minlg + closePathCorr; i++) {
  26717. vTotalDistance[i] = 0;
  26718. vs[i] = [0];
  26719. for (p = 0; p < pathArray.length - 1; p++) {
  26720. path1 = pathArray[p];
  26721. path2 = pathArray[p + 1];
  26722. if (i === minlg) {
  26723. vertex1 = path1[0];
  26724. vertex2 = path2[0];
  26725. }
  26726. else {
  26727. vertex1 = path1[i];
  26728. vertex2 = path2[i];
  26729. }
  26730. vectlg = vertex2.subtract(vertex1).length();
  26731. dist = vectlg + vTotalDistance[i];
  26732. vs[i].push(dist);
  26733. vTotalDistance[i] = dist;
  26734. }
  26735. if (closeArray) {
  26736. path1 = pathArray[p];
  26737. path2 = pathArray[0];
  26738. if (i === minlg) {
  26739. vertex2 = path2[0];
  26740. }
  26741. vectlg = vertex2.subtract(vertex1).length();
  26742. dist = vectlg + vTotalDistance[i];
  26743. vTotalDistance[i] = dist;
  26744. }
  26745. }
  26746. // uvs
  26747. var u;
  26748. var v;
  26749. if (customUV) {
  26750. for (p = 0; p < customUV.length; p++) {
  26751. uvs.push(customUV[p].x, customUV[p].y);
  26752. }
  26753. }
  26754. else {
  26755. for (p = 0; p < pathArray.length; p++) {
  26756. for (i = 0; i < minlg + closePathCorr; i++) {
  26757. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26758. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26759. if (invertUV) {
  26760. uvs.push(v, u);
  26761. }
  26762. else {
  26763. uvs.push(u, v);
  26764. }
  26765. }
  26766. }
  26767. }
  26768. // indices
  26769. p = 0; // path index
  26770. var pi = 0; // positions array index
  26771. var l1 = lg[p] - 1; // path1 length
  26772. var l2 = lg[p + 1] - 1; // path2 length
  26773. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26774. var shft = idx[1] - idx[0]; // shift
  26775. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26776. while (pi <= min && p < path1nb) {
  26777. // 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
  26778. indices.push(pi, pi + shft, pi + 1);
  26779. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26780. pi += 1;
  26781. if (pi === min) {
  26782. p++;
  26783. if (p === lg.length - 1) {
  26784. shft = idx[0] - idx[p];
  26785. l1 = lg[p] - 1;
  26786. l2 = lg[0] - 1;
  26787. }
  26788. else {
  26789. shft = idx[p + 1] - idx[p];
  26790. l1 = lg[p] - 1;
  26791. l2 = lg[p + 1] - 1;
  26792. }
  26793. pi = idx[p];
  26794. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26795. }
  26796. }
  26797. // normals
  26798. VertexData.ComputeNormals(positions, indices, normals);
  26799. if (closePath) {
  26800. var indexFirst = 0;
  26801. var indexLast = 0;
  26802. for (p = 0; p < pathArray.length; p++) {
  26803. indexFirst = idx[p] * 3;
  26804. if (p + 1 < pathArray.length) {
  26805. indexLast = (idx[p + 1] - 1) * 3;
  26806. }
  26807. else {
  26808. indexLast = normals.length - 3;
  26809. }
  26810. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26811. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26812. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26813. normals[indexLast] = normals[indexFirst];
  26814. normals[indexLast + 1] = normals[indexFirst + 1];
  26815. normals[indexLast + 2] = normals[indexFirst + 2];
  26816. }
  26817. }
  26818. // sides
  26819. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26820. // Colors
  26821. if (customColors) {
  26822. var colors = new Float32Array(customColors.length * 4);
  26823. for (var c = 0; c < customColors.length; c++) {
  26824. colors[c * 4] = customColors[c].r;
  26825. colors[c * 4 + 1] = customColors[c].g;
  26826. colors[c * 4 + 2] = customColors[c].b;
  26827. colors[c * 4 + 3] = customColors[c].a;
  26828. }
  26829. }
  26830. // Result
  26831. var vertexData = new VertexData();
  26832. var positions32 = new Float32Array(positions);
  26833. var normals32 = new Float32Array(normals);
  26834. var uvs32 = new Float32Array(uvs);
  26835. vertexData.indices = indices;
  26836. vertexData.positions = positions32;
  26837. vertexData.normals = normals32;
  26838. vertexData.uvs = uvs32;
  26839. if (customColors) {
  26840. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26841. }
  26842. if (closePath) {
  26843. vertexData._idx = idx;
  26844. }
  26845. return vertexData;
  26846. };
  26847. /**
  26848. * Creates the VertexData of the Box.
  26849. */
  26850. VertexData.CreateBox = function (options) {
  26851. var normalsSource = [
  26852. new BABYLON.Vector3(0, 0, 1),
  26853. new BABYLON.Vector3(0, 0, -1),
  26854. new BABYLON.Vector3(1, 0, 0),
  26855. new BABYLON.Vector3(-1, 0, 0),
  26856. new BABYLON.Vector3(0, 1, 0),
  26857. new BABYLON.Vector3(0, -1, 0)
  26858. ];
  26859. var indices = [];
  26860. var positions = [];
  26861. var normals = [];
  26862. var uvs = [];
  26863. var width = options.width || options.size || 1;
  26864. var height = options.height || options.size || 1;
  26865. var depth = options.depth || options.size || 1;
  26866. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26867. var faceUV = options.faceUV || new Array(6);
  26868. var faceColors = options.faceColors;
  26869. var colors = [];
  26870. // default face colors and UV if undefined
  26871. for (var f = 0; f < 6; f++) {
  26872. if (faceUV[f] === undefined) {
  26873. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26874. }
  26875. if (faceColors && faceColors[f] === undefined) {
  26876. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26877. }
  26878. }
  26879. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26880. // Create each face in turn.
  26881. for (var index = 0; index < normalsSource.length; index++) {
  26882. var normal = normalsSource[index];
  26883. // Get two vectors perpendicular to the face normal and to each other.
  26884. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26885. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26886. // Six indices (two triangles) per face.
  26887. var verticesLength = positions.length / 3;
  26888. indices.push(verticesLength);
  26889. indices.push(verticesLength + 1);
  26890. indices.push(verticesLength + 2);
  26891. indices.push(verticesLength);
  26892. indices.push(verticesLength + 2);
  26893. indices.push(verticesLength + 3);
  26894. // Four vertices per face.
  26895. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26896. positions.push(vertex.x, vertex.y, vertex.z);
  26897. normals.push(normal.x, normal.y, normal.z);
  26898. uvs.push(faceUV[index].z, faceUV[index].w);
  26899. if (faceColors) {
  26900. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26901. }
  26902. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26903. positions.push(vertex.x, vertex.y, vertex.z);
  26904. normals.push(normal.x, normal.y, normal.z);
  26905. uvs.push(faceUV[index].x, faceUV[index].w);
  26906. if (faceColors) {
  26907. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26908. }
  26909. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26910. positions.push(vertex.x, vertex.y, vertex.z);
  26911. normals.push(normal.x, normal.y, normal.z);
  26912. uvs.push(faceUV[index].x, faceUV[index].y);
  26913. if (faceColors) {
  26914. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26915. }
  26916. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26917. positions.push(vertex.x, vertex.y, vertex.z);
  26918. normals.push(normal.x, normal.y, normal.z);
  26919. uvs.push(faceUV[index].z, faceUV[index].y);
  26920. if (faceColors) {
  26921. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26922. }
  26923. }
  26924. // sides
  26925. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26926. // Result
  26927. var vertexData = new VertexData();
  26928. vertexData.indices = indices;
  26929. vertexData.positions = positions;
  26930. vertexData.normals = normals;
  26931. vertexData.uvs = uvs;
  26932. if (faceColors) {
  26933. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26934. vertexData.colors = totalColors;
  26935. }
  26936. return vertexData;
  26937. };
  26938. /**
  26939. * Creates the VertexData of the Sphere.
  26940. */
  26941. VertexData.CreateSphere = function (options) {
  26942. var segments = options.segments || 32;
  26943. var diameterX = options.diameterX || options.diameter || 1;
  26944. var diameterY = options.diameterY || options.diameter || 1;
  26945. var diameterZ = options.diameterZ || options.diameter || 1;
  26946. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26947. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26948. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26949. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26950. var totalZRotationSteps = 2 + segments;
  26951. var totalYRotationSteps = 2 * totalZRotationSteps;
  26952. var indices = [];
  26953. var positions = [];
  26954. var normals = [];
  26955. var uvs = [];
  26956. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26957. var normalizedZ = zRotationStep / totalZRotationSteps;
  26958. var angleZ = normalizedZ * Math.PI * slice;
  26959. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26960. var normalizedY = yRotationStep / totalYRotationSteps;
  26961. var angleY = normalizedY * Math.PI * 2 * arc;
  26962. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26963. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26964. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26965. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26966. var vertex = complete.multiply(radius);
  26967. var normal = complete.divide(radius).normalize();
  26968. positions.push(vertex.x, vertex.y, vertex.z);
  26969. normals.push(normal.x, normal.y, normal.z);
  26970. uvs.push(normalizedY, normalizedZ);
  26971. }
  26972. if (zRotationStep > 0) {
  26973. var verticesCount = positions.length / 3;
  26974. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26975. indices.push((firstIndex));
  26976. indices.push((firstIndex + 1));
  26977. indices.push(firstIndex + totalYRotationSteps + 1);
  26978. indices.push((firstIndex + totalYRotationSteps + 1));
  26979. indices.push((firstIndex + 1));
  26980. indices.push((firstIndex + totalYRotationSteps + 2));
  26981. }
  26982. }
  26983. }
  26984. // Sides
  26985. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26986. // Result
  26987. var vertexData = new VertexData();
  26988. vertexData.indices = indices;
  26989. vertexData.positions = positions;
  26990. vertexData.normals = normals;
  26991. vertexData.uvs = uvs;
  26992. return vertexData;
  26993. };
  26994. /**
  26995. * Creates the VertexData of the Cylinder or Cone.
  26996. */
  26997. VertexData.CreateCylinder = function (options) {
  26998. var height = options.height || 2;
  26999. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27000. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27001. var tessellation = options.tessellation || 24;
  27002. var subdivisions = options.subdivisions || 1;
  27003. var hasRings = options.hasRings;
  27004. var enclose = options.enclose;
  27005. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27006. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27007. var faceUV = options.faceUV || new Array(3);
  27008. var faceColors = options.faceColors;
  27009. // default face colors and UV if undefined
  27010. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27011. var ringNb = (hasRings) ? subdivisions : 1;
  27012. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27013. var f;
  27014. for (f = 0; f < surfaceNb; f++) {
  27015. if (faceColors && faceColors[f] === undefined) {
  27016. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27017. }
  27018. }
  27019. for (f = 0; f < surfaceNb; f++) {
  27020. if (faceUV && faceUV[f] === undefined) {
  27021. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27022. }
  27023. }
  27024. var indices = [];
  27025. var positions = [];
  27026. var normals = [];
  27027. var uvs = [];
  27028. var colors = [];
  27029. var angle_step = Math.PI * 2 * arc / tessellation;
  27030. var angle;
  27031. var h;
  27032. var radius;
  27033. var tan = (diameterBottom - diameterTop) / 2 / height;
  27034. var ringVertex = BABYLON.Vector3.Zero();
  27035. var ringNormal = BABYLON.Vector3.Zero();
  27036. var ringFirstVertex = BABYLON.Vector3.Zero();
  27037. var ringFirstNormal = BABYLON.Vector3.Zero();
  27038. var quadNormal = BABYLON.Vector3.Zero();
  27039. var Y = BABYLON.Axis.Y;
  27040. // positions, normals, uvs
  27041. var i;
  27042. var j;
  27043. var r;
  27044. var ringIdx = 1;
  27045. var s = 1; // surface index
  27046. var cs = 0;
  27047. var v = 0;
  27048. for (i = 0; i <= subdivisions; i++) {
  27049. h = i / subdivisions;
  27050. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27051. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27052. for (r = 0; r < ringIdx; r++) {
  27053. if (hasRings) {
  27054. s += r;
  27055. }
  27056. if (enclose) {
  27057. s += 2 * r;
  27058. }
  27059. for (j = 0; j <= tessellation; j++) {
  27060. angle = j * angle_step;
  27061. // position
  27062. ringVertex.x = Math.cos(-angle) * radius;
  27063. ringVertex.y = -height / 2 + h * height;
  27064. ringVertex.z = Math.sin(-angle) * radius;
  27065. // normal
  27066. if (diameterTop === 0 && i === subdivisions) {
  27067. // if no top cap, reuse former normals
  27068. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27069. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27070. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27071. }
  27072. else {
  27073. ringNormal.x = ringVertex.x;
  27074. ringNormal.z = ringVertex.z;
  27075. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27076. ringNormal.normalize();
  27077. }
  27078. // keep first ring vertex values for enclose
  27079. if (j === 0) {
  27080. ringFirstVertex.copyFrom(ringVertex);
  27081. ringFirstNormal.copyFrom(ringNormal);
  27082. }
  27083. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27084. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27085. if (hasRings) {
  27086. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27087. }
  27088. else {
  27089. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27090. }
  27091. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27092. if (faceColors) {
  27093. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27094. }
  27095. }
  27096. // if enclose, add four vertices and their dedicated normals
  27097. if (arc !== 1 && enclose) {
  27098. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27099. positions.push(0, ringVertex.y, 0);
  27100. positions.push(0, ringVertex.y, 0);
  27101. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27102. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27103. quadNormal.normalize();
  27104. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27105. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27106. quadNormal.normalize();
  27107. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27108. if (hasRings) {
  27109. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27110. }
  27111. else {
  27112. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27113. }
  27114. uvs.push(faceUV[s + 1].x, v);
  27115. uvs.push(faceUV[s + 1].z, v);
  27116. if (hasRings) {
  27117. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27118. }
  27119. else {
  27120. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27121. }
  27122. uvs.push(faceUV[s + 2].x, v);
  27123. uvs.push(faceUV[s + 2].z, v);
  27124. if (faceColors) {
  27125. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27126. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27127. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27128. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27129. }
  27130. }
  27131. if (cs !== s) {
  27132. cs = s;
  27133. }
  27134. }
  27135. }
  27136. // indices
  27137. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27138. var s;
  27139. i = 0;
  27140. for (s = 0; s < subdivisions; s++) {
  27141. for (j = 0; j < tessellation; j++) {
  27142. var i0 = i * (e + 1) + j;
  27143. var i1 = (i + 1) * (e + 1) + j;
  27144. var i2 = i * (e + 1) + (j + 1);
  27145. var i3 = (i + 1) * (e + 1) + (j + 1);
  27146. indices.push(i0, i1, i2);
  27147. indices.push(i3, i2, i1);
  27148. }
  27149. if (arc !== 1 && enclose) {
  27150. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27151. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27152. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27153. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27154. }
  27155. i = (hasRings) ? (i + 2) : (i + 1);
  27156. }
  27157. // Caps
  27158. var createCylinderCap = function (isTop) {
  27159. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27160. if (radius === 0) {
  27161. return;
  27162. }
  27163. // Cap positions, normals & uvs
  27164. var angle;
  27165. var circleVector;
  27166. var i;
  27167. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27168. var c;
  27169. if (faceColors) {
  27170. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27171. }
  27172. // cap center
  27173. var vbase = positions.length / 3;
  27174. var offset = isTop ? height / 2 : -height / 2;
  27175. var center = new BABYLON.Vector3(0, offset, 0);
  27176. positions.push(center.x, center.y, center.z);
  27177. normals.push(0, isTop ? 1 : -1, 0);
  27178. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27179. if (faceColors) {
  27180. colors.push(c.r, c.g, c.b, c.a);
  27181. }
  27182. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27183. for (i = 0; i <= tessellation; i++) {
  27184. angle = Math.PI * 2 * i * arc / tessellation;
  27185. var cos = Math.cos(-angle);
  27186. var sin = Math.sin(-angle);
  27187. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27188. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27189. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27190. normals.push(0, isTop ? 1 : -1, 0);
  27191. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27192. if (faceColors) {
  27193. colors.push(c.r, c.g, c.b, c.a);
  27194. }
  27195. }
  27196. // Cap indices
  27197. for (i = 0; i < tessellation; i++) {
  27198. if (!isTop) {
  27199. indices.push(vbase);
  27200. indices.push(vbase + (i + 1));
  27201. indices.push(vbase + (i + 2));
  27202. }
  27203. else {
  27204. indices.push(vbase);
  27205. indices.push(vbase + (i + 2));
  27206. indices.push(vbase + (i + 1));
  27207. }
  27208. }
  27209. };
  27210. // add caps to geometry
  27211. createCylinderCap(false);
  27212. createCylinderCap(true);
  27213. // Sides
  27214. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27215. var vertexData = new VertexData();
  27216. vertexData.indices = indices;
  27217. vertexData.positions = positions;
  27218. vertexData.normals = normals;
  27219. vertexData.uvs = uvs;
  27220. if (faceColors) {
  27221. vertexData.colors = colors;
  27222. }
  27223. return vertexData;
  27224. };
  27225. /**
  27226. * Creates the VertexData of the Torus.
  27227. */
  27228. VertexData.CreateTorus = function (options) {
  27229. var indices = [];
  27230. var positions = [];
  27231. var normals = [];
  27232. var uvs = [];
  27233. var diameter = options.diameter || 1;
  27234. var thickness = options.thickness || 0.5;
  27235. var tessellation = options.tessellation || 16;
  27236. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27237. var stride = tessellation + 1;
  27238. for (var i = 0; i <= tessellation; i++) {
  27239. var u = i / tessellation;
  27240. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27241. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27242. for (var j = 0; j <= tessellation; j++) {
  27243. var v = 1 - j / tessellation;
  27244. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27245. var dx = Math.cos(innerAngle);
  27246. var dy = Math.sin(innerAngle);
  27247. // Create a vertex.
  27248. var normal = new BABYLON.Vector3(dx, dy, 0);
  27249. var position = normal.scale(thickness / 2);
  27250. var textureCoordinate = new BABYLON.Vector2(u, v);
  27251. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27252. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27253. positions.push(position.x, position.y, position.z);
  27254. normals.push(normal.x, normal.y, normal.z);
  27255. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27256. // And create indices for two triangles.
  27257. var nextI = (i + 1) % stride;
  27258. var nextJ = (j + 1) % stride;
  27259. indices.push(i * stride + j);
  27260. indices.push(i * stride + nextJ);
  27261. indices.push(nextI * stride + j);
  27262. indices.push(i * stride + nextJ);
  27263. indices.push(nextI * stride + nextJ);
  27264. indices.push(nextI * stride + j);
  27265. }
  27266. }
  27267. // Sides
  27268. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27269. // Result
  27270. var vertexData = new VertexData();
  27271. vertexData.indices = indices;
  27272. vertexData.positions = positions;
  27273. vertexData.normals = normals;
  27274. vertexData.uvs = uvs;
  27275. return vertexData;
  27276. };
  27277. /**
  27278. * Creates the VertexData of the LineSystem.
  27279. */
  27280. VertexData.CreateLineSystem = function (options) {
  27281. var indices = [];
  27282. var positions = [];
  27283. var lines = options.lines;
  27284. var idx = 0;
  27285. for (var l = 0; l < lines.length; l++) {
  27286. var points = lines[l];
  27287. for (var index = 0; index < points.length; index++) {
  27288. positions.push(points[index].x, points[index].y, points[index].z);
  27289. if (index > 0) {
  27290. indices.push(idx - 1);
  27291. indices.push(idx);
  27292. }
  27293. idx++;
  27294. }
  27295. }
  27296. var vertexData = new VertexData();
  27297. vertexData.indices = indices;
  27298. vertexData.positions = positions;
  27299. return vertexData;
  27300. };
  27301. /**
  27302. * Create the VertexData of the DashedLines.
  27303. */
  27304. VertexData.CreateDashedLines = function (options) {
  27305. var dashSize = options.dashSize || 3;
  27306. var gapSize = options.gapSize || 1;
  27307. var dashNb = options.dashNb || 200;
  27308. var points = options.points;
  27309. var positions = new Array();
  27310. var indices = new Array();
  27311. var curvect = BABYLON.Vector3.Zero();
  27312. var lg = 0;
  27313. var nb = 0;
  27314. var shft = 0;
  27315. var dashshft = 0;
  27316. var curshft = 0;
  27317. var idx = 0;
  27318. var i = 0;
  27319. for (i = 0; i < points.length - 1; i++) {
  27320. points[i + 1].subtractToRef(points[i], curvect);
  27321. lg += curvect.length();
  27322. }
  27323. shft = lg / dashNb;
  27324. dashshft = dashSize * shft / (dashSize + gapSize);
  27325. for (i = 0; i < points.length - 1; i++) {
  27326. points[i + 1].subtractToRef(points[i], curvect);
  27327. nb = Math.floor(curvect.length() / shft);
  27328. curvect.normalize();
  27329. for (var j = 0; j < nb; j++) {
  27330. curshft = shft * j;
  27331. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27332. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27333. indices.push(idx, idx + 1);
  27334. idx += 2;
  27335. }
  27336. }
  27337. // Result
  27338. var vertexData = new VertexData();
  27339. vertexData.positions = positions;
  27340. vertexData.indices = indices;
  27341. return vertexData;
  27342. };
  27343. /**
  27344. * Creates the VertexData of the Ground.
  27345. */
  27346. VertexData.CreateGround = function (options) {
  27347. var indices = [];
  27348. var positions = [];
  27349. var normals = [];
  27350. var uvs = [];
  27351. var row, col;
  27352. var width = options.width || 1;
  27353. var height = options.height || 1;
  27354. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27355. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27356. for (row = 0; row <= subdivisionsY; row++) {
  27357. for (col = 0; col <= subdivisionsX; col++) {
  27358. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27359. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27360. positions.push(position.x, position.y, position.z);
  27361. normals.push(normal.x, normal.y, normal.z);
  27362. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27363. }
  27364. }
  27365. for (row = 0; row < subdivisionsY; row++) {
  27366. for (col = 0; col < subdivisionsX; col++) {
  27367. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27368. indices.push(col + 1 + row * (subdivisionsX + 1));
  27369. indices.push(col + row * (subdivisionsX + 1));
  27370. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27371. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27372. indices.push(col + row * (subdivisionsX + 1));
  27373. }
  27374. }
  27375. // Result
  27376. var vertexData = new VertexData();
  27377. vertexData.indices = indices;
  27378. vertexData.positions = positions;
  27379. vertexData.normals = normals;
  27380. vertexData.uvs = uvs;
  27381. return vertexData;
  27382. };
  27383. /**
  27384. * Creates the VertexData of the TiledGround.
  27385. */
  27386. VertexData.CreateTiledGround = function (options) {
  27387. var xmin = options.xmin || -1.0;
  27388. var zmin = options.zmin || -1.0;
  27389. var xmax = options.xmax || 1.0;
  27390. var zmax = options.zmax || 1.0;
  27391. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27392. var precision = options.precision || { w: 1, h: 1 };
  27393. var indices = [];
  27394. var positions = [];
  27395. var normals = [];
  27396. var uvs = [];
  27397. var row, col, tileRow, tileCol;
  27398. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27399. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27400. precision.w = (precision.w < 1) ? 1 : precision.w;
  27401. precision.h = (precision.h < 1) ? 1 : precision.h;
  27402. var tileSize = {
  27403. 'w': (xmax - xmin) / subdivisions.w,
  27404. 'h': (zmax - zmin) / subdivisions.h
  27405. };
  27406. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27407. // Indices
  27408. var base = positions.length / 3;
  27409. var rowLength = precision.w + 1;
  27410. for (row = 0; row < precision.h; row++) {
  27411. for (col = 0; col < precision.w; col++) {
  27412. var square = [
  27413. base + col + row * rowLength,
  27414. base + (col + 1) + row * rowLength,
  27415. base + (col + 1) + (row + 1) * rowLength,
  27416. base + col + (row + 1) * rowLength
  27417. ];
  27418. indices.push(square[1]);
  27419. indices.push(square[2]);
  27420. indices.push(square[3]);
  27421. indices.push(square[0]);
  27422. indices.push(square[1]);
  27423. indices.push(square[3]);
  27424. }
  27425. }
  27426. // Position, normals and uvs
  27427. var position = BABYLON.Vector3.Zero();
  27428. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27429. for (row = 0; row <= precision.h; row++) {
  27430. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27431. for (col = 0; col <= precision.w; col++) {
  27432. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27433. position.y = 0;
  27434. positions.push(position.x, position.y, position.z);
  27435. normals.push(normal.x, normal.y, normal.z);
  27436. uvs.push(col / precision.w, row / precision.h);
  27437. }
  27438. }
  27439. }
  27440. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27441. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27442. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27443. }
  27444. }
  27445. // Result
  27446. var vertexData = new VertexData();
  27447. vertexData.indices = indices;
  27448. vertexData.positions = positions;
  27449. vertexData.normals = normals;
  27450. vertexData.uvs = uvs;
  27451. return vertexData;
  27452. };
  27453. /**
  27454. * Creates the VertexData of the Ground designed from a heightmap.
  27455. */
  27456. VertexData.CreateGroundFromHeightMap = function (options) {
  27457. var indices = [];
  27458. var positions = [];
  27459. var normals = [];
  27460. var uvs = [];
  27461. var row, col;
  27462. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27463. // Vertices
  27464. for (row = 0; row <= options.subdivisions; row++) {
  27465. for (col = 0; col <= options.subdivisions; col++) {
  27466. 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));
  27467. // Compute height
  27468. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27469. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27470. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27471. var r = options.buffer[pos] / 255.0;
  27472. var g = options.buffer[pos + 1] / 255.0;
  27473. var b = options.buffer[pos + 2] / 255.0;
  27474. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27475. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27476. // Add vertex
  27477. positions.push(position.x, position.y, position.z);
  27478. normals.push(0, 0, 0);
  27479. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27480. }
  27481. }
  27482. // Indices
  27483. for (row = 0; row < options.subdivisions; row++) {
  27484. for (col = 0; col < options.subdivisions; col++) {
  27485. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27486. indices.push(col + 1 + row * (options.subdivisions + 1));
  27487. indices.push(col + row * (options.subdivisions + 1));
  27488. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27489. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27490. indices.push(col + row * (options.subdivisions + 1));
  27491. }
  27492. }
  27493. // Normals
  27494. VertexData.ComputeNormals(positions, indices, normals);
  27495. // Result
  27496. var vertexData = new VertexData();
  27497. vertexData.indices = indices;
  27498. vertexData.positions = positions;
  27499. vertexData.normals = normals;
  27500. vertexData.uvs = uvs;
  27501. return vertexData;
  27502. };
  27503. /**
  27504. * Creates the VertexData of the Plane.
  27505. */
  27506. VertexData.CreatePlane = function (options) {
  27507. var indices = [];
  27508. var positions = [];
  27509. var normals = [];
  27510. var uvs = [];
  27511. var width = options.width || options.size || 1;
  27512. var height = options.height || options.size || 1;
  27513. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27514. // Vertices
  27515. var halfWidth = width / 2.0;
  27516. var halfHeight = height / 2.0;
  27517. positions.push(-halfWidth, -halfHeight, 0);
  27518. normals.push(0, 0, -1.0);
  27519. uvs.push(0.0, 0.0);
  27520. positions.push(halfWidth, -halfHeight, 0);
  27521. normals.push(0, 0, -1.0);
  27522. uvs.push(1.0, 0.0);
  27523. positions.push(halfWidth, halfHeight, 0);
  27524. normals.push(0, 0, -1.0);
  27525. uvs.push(1.0, 1.0);
  27526. positions.push(-halfWidth, halfHeight, 0);
  27527. normals.push(0, 0, -1.0);
  27528. uvs.push(0.0, 1.0);
  27529. // Indices
  27530. indices.push(0);
  27531. indices.push(1);
  27532. indices.push(2);
  27533. indices.push(0);
  27534. indices.push(2);
  27535. indices.push(3);
  27536. // Sides
  27537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27538. // Result
  27539. var vertexData = new VertexData();
  27540. vertexData.indices = indices;
  27541. vertexData.positions = positions;
  27542. vertexData.normals = normals;
  27543. vertexData.uvs = uvs;
  27544. return vertexData;
  27545. };
  27546. /**
  27547. * Creates the VertexData of the Disc or regular Polygon.
  27548. */
  27549. VertexData.CreateDisc = function (options) {
  27550. var positions = [];
  27551. var indices = [];
  27552. var normals = [];
  27553. var uvs = [];
  27554. var radius = options.radius || 0.5;
  27555. var tessellation = options.tessellation || 64;
  27556. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27557. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27558. // positions and uvs
  27559. positions.push(0, 0, 0); // disc center first
  27560. uvs.push(0.5, 0.5);
  27561. var theta = Math.PI * 2 * arc;
  27562. var step = theta / tessellation;
  27563. for (var a = 0; a < theta; a += step) {
  27564. var x = Math.cos(a);
  27565. var y = Math.sin(a);
  27566. var u = (x + 1) / 2;
  27567. var v = (1 - y) / 2;
  27568. positions.push(radius * x, radius * y, 0);
  27569. uvs.push(u, v);
  27570. }
  27571. if (arc === 1) {
  27572. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27573. uvs.push(uvs[2], uvs[3]);
  27574. }
  27575. //indices
  27576. var vertexNb = positions.length / 3;
  27577. for (var i = 1; i < vertexNb - 1; i++) {
  27578. indices.push(i + 1, 0, i);
  27579. }
  27580. // result
  27581. VertexData.ComputeNormals(positions, indices, normals);
  27582. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27583. var vertexData = new VertexData();
  27584. vertexData.indices = indices;
  27585. vertexData.positions = positions;
  27586. vertexData.normals = normals;
  27587. vertexData.uvs = uvs;
  27588. return vertexData;
  27589. };
  27590. /**
  27591. * Re-creates the VertexData of the Polygon for sideOrientation.
  27592. */
  27593. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27594. var faceUV = fUV || new Array(3);
  27595. var faceColors = fColors;
  27596. var colors = [];
  27597. // default face colors and UV if undefined
  27598. for (var f = 0; f < 3; f++) {
  27599. if (faceUV[f] === undefined) {
  27600. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27601. }
  27602. if (faceColors && faceColors[f] === undefined) {
  27603. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27604. }
  27605. }
  27606. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27607. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27608. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27609. var indices = polygon.getIndices();
  27610. // set face colours and textures
  27611. var idx = 0;
  27612. var face = 0;
  27613. for (var index = 0; index < normals.length; index += 3) {
  27614. //Edge Face no. 1
  27615. if (Math.abs(normals[index + 1]) < 0.001) {
  27616. face = 1;
  27617. }
  27618. //Top Face no. 0
  27619. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27620. face = 0;
  27621. }
  27622. //Bottom Face no. 2
  27623. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27624. face = 2;
  27625. }
  27626. idx = index / 3;
  27627. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27628. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27629. if (faceColors) {
  27630. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27631. }
  27632. }
  27633. // sides
  27634. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27635. // Result
  27636. var vertexData = new VertexData();
  27637. vertexData.indices = indices;
  27638. vertexData.positions = positions;
  27639. vertexData.normals = normals;
  27640. vertexData.uvs = uvs;
  27641. if (faceColors) {
  27642. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27643. vertexData.colors = totalColors;
  27644. }
  27645. return vertexData;
  27646. };
  27647. /**
  27648. * Creates the VertexData of the IcoSphere.
  27649. */
  27650. VertexData.CreateIcoSphere = function (options) {
  27651. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27652. var radius = options.radius || 1;
  27653. var flat = (options.flat === undefined) ? true : options.flat;
  27654. var subdivisions = options.subdivisions || 4;
  27655. var radiusX = options.radiusX || radius;
  27656. var radiusY = options.radiusY || radius;
  27657. var radiusZ = options.radiusZ || radius;
  27658. var t = (1 + Math.sqrt(5)) / 2;
  27659. // 12 vertex x,y,z
  27660. var ico_vertices = [
  27661. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27662. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27663. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27664. ];
  27665. // index of 3 vertex makes a face of icopshere
  27666. var ico_indices = [
  27667. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27668. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27669. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27670. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27671. ];
  27672. // vertex for uv have aliased position, not for UV
  27673. var vertices_unalias_id = [
  27674. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27675. // vertex alias
  27676. 0,
  27677. 2,
  27678. 3,
  27679. 3,
  27680. 3,
  27681. 4,
  27682. 7,
  27683. 8,
  27684. 9,
  27685. 9,
  27686. 10,
  27687. 11 // 23: B + 12
  27688. ];
  27689. // uv as integer step (not pixels !)
  27690. var ico_vertexuv = [
  27691. 5, 1, 3, 1, 6, 4, 0, 0,
  27692. 5, 3, 4, 2, 2, 2, 4, 0,
  27693. 2, 0, 1, 1, 6, 0, 6, 2,
  27694. // vertex alias (for same vertex on different faces)
  27695. 0, 4,
  27696. 3, 3,
  27697. 4, 4,
  27698. 3, 1,
  27699. 4, 2,
  27700. 4, 4,
  27701. 0, 2,
  27702. 1, 1,
  27703. 2, 2,
  27704. 3, 3,
  27705. 1, 3,
  27706. 2, 4 // 23: B + 12
  27707. ];
  27708. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27709. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27710. // First island of uv mapping
  27711. // v = 4h 3+ 2
  27712. // v = 3h 9+ 4
  27713. // v = 2h 9+ 5 B
  27714. // v = 1h 9 1 0
  27715. // v = 0h 3 8 7 A
  27716. // u = 0 1 2 3 4 5 6 *a
  27717. // Second island of uv mapping
  27718. // v = 4h 0+ B+ 4+
  27719. // v = 3h A+ 2+
  27720. // v = 2h 7+ 6 3+
  27721. // v = 1h 8+ 3+
  27722. // v = 0h
  27723. // u = 0 1 2 3 4 5 6 *a
  27724. // Face layout on texture UV mapping
  27725. // ============
  27726. // \ 4 /\ 16 / ======
  27727. // \ / \ / /\ 11 /
  27728. // \/ 7 \/ / \ /
  27729. // ======= / 10 \/
  27730. // /\ 17 /\ =======
  27731. // / \ / \ \ 15 /\
  27732. // / 8 \/ 12 \ \ / \
  27733. // ============ \/ 6 \
  27734. // \ 18 /\ ============
  27735. // \ / \ \ 5 /\ 0 /
  27736. // \/ 13 \ \ / \ /
  27737. // ======= \/ 1 \/
  27738. // =============
  27739. // /\ 19 /\ 2 /\
  27740. // / \ / \ / \
  27741. // / 14 \/ 9 \/ 3 \
  27742. // ===================
  27743. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27744. var ustep = 138 / 1024;
  27745. var vstep = 239 / 1024;
  27746. var uoffset = 60 / 1024;
  27747. var voffset = 26 / 1024;
  27748. // Second island should have margin, not to touch the first island
  27749. // avoid any borderline artefact in pixel rounding
  27750. var island_u_offset = -40 / 1024;
  27751. var island_v_offset = +20 / 1024;
  27752. // face is either island 0 or 1 :
  27753. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27754. var island = [
  27755. 0, 0, 0, 0, 1,
  27756. 0, 0, 1, 1, 0,
  27757. 0, 0, 1, 1, 0,
  27758. 0, 1, 1, 1, 0 // 15 - 19
  27759. ];
  27760. var indices = [];
  27761. var positions = [];
  27762. var normals = [];
  27763. var uvs = [];
  27764. var current_indice = 0;
  27765. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27766. var face_vertex_pos = new Array(3);
  27767. var face_vertex_uv = new Array(3);
  27768. var v012;
  27769. for (v012 = 0; v012 < 3; v012++) {
  27770. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27771. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27772. }
  27773. // create all with normals
  27774. for (var face = 0; face < 20; face++) {
  27775. // 3 vertex per face
  27776. for (v012 = 0; v012 < 3; v012++) {
  27777. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27778. var v_id = ico_indices[3 * face + v012];
  27779. // vertex have 3D position (x,y,z)
  27780. 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]);
  27781. // Normalize to get normal, then scale to radius
  27782. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27783. // uv Coordinates from vertex ID
  27784. 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);
  27785. }
  27786. // Subdivide the face (interpolate pos, norm, uv)
  27787. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27788. // - norm is linear interpolation of vertex corner normal
  27789. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27790. // - uv is linear interpolation
  27791. //
  27792. // Topology is as below for sub-divide by 2
  27793. // vertex shown as v0,v1,v2
  27794. // interp index is i1 to progress in range [v0,v1[
  27795. // interp index is i2 to progress in range [v0,v2[
  27796. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27797. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27798. //
  27799. //
  27800. // i2 v2
  27801. // ^ ^
  27802. // / / \
  27803. // / / \
  27804. // / / \
  27805. // / / (0,1) \
  27806. // / #---------\
  27807. // / / \ (0,0)'/ \
  27808. // / / \ / \
  27809. // / / \ / \
  27810. // / / (0,0) \ / (1,0) \
  27811. // / #---------#---------\
  27812. // v0 v1
  27813. //
  27814. // --------------------> i1
  27815. //
  27816. // interp of (i1,i2):
  27817. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27818. // along i1 : lerp(x0,x1, i1/(S-i2))
  27819. //
  27820. // centroid of triangle is needed to get help normal computation
  27821. // (c1,c2) are used for centroid location
  27822. var interp_vertex = function (i1, i2, c1, c2) {
  27823. // vertex is interpolated from
  27824. // - face_vertex_pos[0..2]
  27825. // - face_vertex_uv[0..2]
  27826. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27827. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27828. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27829. pos_interp.normalize();
  27830. var vertex_normal;
  27831. if (flat) {
  27832. // in flat mode, recalculate normal as face centroid normal
  27833. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27834. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27835. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27836. }
  27837. else {
  27838. // in smooth mode, recalculate normal from each single vertex position
  27839. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27840. }
  27841. // Vertex normal need correction due to X,Y,Z radius scaling
  27842. vertex_normal.x /= radiusX;
  27843. vertex_normal.y /= radiusY;
  27844. vertex_normal.z /= radiusZ;
  27845. vertex_normal.normalize();
  27846. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27847. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27848. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27849. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27850. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27851. uvs.push(uv_interp.x, uv_interp.y);
  27852. // push each vertex has member of a face
  27853. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27854. indices.push(current_indice);
  27855. current_indice++;
  27856. };
  27857. for (var i2 = 0; i2 < subdivisions; i2++) {
  27858. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27859. // face : (i1,i2) for /\ :
  27860. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27861. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27862. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27863. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27864. if (i1 + i2 + 1 < subdivisions) {
  27865. // face : (i1,i2)' for \/ :
  27866. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27867. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27868. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27869. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27870. }
  27871. }
  27872. }
  27873. }
  27874. // Sides
  27875. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27876. // Result
  27877. var vertexData = new VertexData();
  27878. vertexData.indices = indices;
  27879. vertexData.positions = positions;
  27880. vertexData.normals = normals;
  27881. vertexData.uvs = uvs;
  27882. return vertexData;
  27883. };
  27884. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27885. /**
  27886. * Creates the VertexData of the Polyhedron.
  27887. */
  27888. VertexData.CreatePolyhedron = function (options) {
  27889. // provided polyhedron types :
  27890. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27891. // 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)
  27892. var polyhedra = [];
  27893. 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]] };
  27894. 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]] };
  27895. polyhedra[2] = {
  27896. 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]],
  27897. 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]]
  27898. };
  27899. polyhedra[3] = {
  27900. 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]],
  27901. 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]]
  27902. };
  27903. polyhedra[4] = {
  27904. 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]],
  27905. 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]]
  27906. };
  27907. 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]] };
  27908. 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]] };
  27909. 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]] };
  27910. 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]] };
  27911. 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]] };
  27912. 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]] };
  27913. 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]] };
  27914. 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]] };
  27915. 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]] };
  27916. polyhedra[14] = {
  27917. 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]],
  27918. 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]]
  27919. };
  27920. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27921. var size = options.size;
  27922. var sizeX = options.sizeX || size || 1;
  27923. var sizeY = options.sizeY || size || 1;
  27924. var sizeZ = options.sizeZ || size || 1;
  27925. var data = options.custom || polyhedra[type];
  27926. var nbfaces = data.face.length;
  27927. var faceUV = options.faceUV || new Array(nbfaces);
  27928. var faceColors = options.faceColors;
  27929. var flat = (options.flat === undefined) ? true : options.flat;
  27930. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27931. var positions = [];
  27932. var indices = [];
  27933. var normals = [];
  27934. var uvs = [];
  27935. var colors = [];
  27936. var index = 0;
  27937. var faceIdx = 0; // face cursor in the array "indexes"
  27938. var indexes = [];
  27939. var i = 0;
  27940. var f = 0;
  27941. var u, v, ang, x, y, tmp;
  27942. // default face colors and UV if undefined
  27943. if (flat) {
  27944. for (f = 0; f < nbfaces; f++) {
  27945. if (faceColors && faceColors[f] === undefined) {
  27946. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27947. }
  27948. if (faceUV && faceUV[f] === undefined) {
  27949. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27950. }
  27951. }
  27952. }
  27953. if (!flat) {
  27954. for (i = 0; i < data.vertex.length; i++) {
  27955. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27956. uvs.push(0, 0);
  27957. }
  27958. for (f = 0; f < nbfaces; f++) {
  27959. for (i = 0; i < data.face[f].length - 2; i++) {
  27960. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27961. }
  27962. }
  27963. }
  27964. else {
  27965. for (f = 0; f < nbfaces; f++) {
  27966. var fl = data.face[f].length; // number of vertices of the current face
  27967. ang = 2 * Math.PI / fl;
  27968. x = 0.5 * Math.tan(ang / 2);
  27969. y = 0.5;
  27970. // positions, uvs, colors
  27971. for (i = 0; i < fl; i++) {
  27972. // positions
  27973. 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);
  27974. indexes.push(index);
  27975. index++;
  27976. // uvs
  27977. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27978. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27979. uvs.push(u, v);
  27980. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27981. y = x * Math.sin(ang) + y * Math.cos(ang);
  27982. x = tmp;
  27983. // colors
  27984. if (faceColors) {
  27985. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27986. }
  27987. }
  27988. // indices from indexes
  27989. for (i = 0; i < fl - 2; i++) {
  27990. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27991. }
  27992. faceIdx += fl;
  27993. }
  27994. }
  27995. VertexData.ComputeNormals(positions, indices, normals);
  27996. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27997. var vertexData = new VertexData();
  27998. vertexData.positions = positions;
  27999. vertexData.indices = indices;
  28000. vertexData.normals = normals;
  28001. vertexData.uvs = uvs;
  28002. if (faceColors && flat) {
  28003. vertexData.colors = colors;
  28004. }
  28005. return vertexData;
  28006. };
  28007. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28008. /**
  28009. * Creates the VertexData of the Torus Knot.
  28010. */
  28011. VertexData.CreateTorusKnot = function (options) {
  28012. var indices = [];
  28013. var positions = [];
  28014. var normals = [];
  28015. var uvs = [];
  28016. var radius = options.radius || 2;
  28017. var tube = options.tube || 0.5;
  28018. var radialSegments = options.radialSegments || 32;
  28019. var tubularSegments = options.tubularSegments || 32;
  28020. var p = options.p || 2;
  28021. var q = options.q || 3;
  28022. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28023. // Helper
  28024. var getPos = function (angle) {
  28025. var cu = Math.cos(angle);
  28026. var su = Math.sin(angle);
  28027. var quOverP = q / p * angle;
  28028. var cs = Math.cos(quOverP);
  28029. var tx = radius * (2 + cs) * 0.5 * cu;
  28030. var ty = radius * (2 + cs) * su * 0.5;
  28031. var tz = radius * Math.sin(quOverP) * 0.5;
  28032. return new BABYLON.Vector3(tx, ty, tz);
  28033. };
  28034. // Vertices
  28035. var i;
  28036. var j;
  28037. for (i = 0; i <= radialSegments; i++) {
  28038. var modI = i % radialSegments;
  28039. var u = modI / radialSegments * 2 * p * Math.PI;
  28040. var p1 = getPos(u);
  28041. var p2 = getPos(u + 0.01);
  28042. var tang = p2.subtract(p1);
  28043. var n = p2.add(p1);
  28044. var bitan = BABYLON.Vector3.Cross(tang, n);
  28045. n = BABYLON.Vector3.Cross(bitan, tang);
  28046. bitan.normalize();
  28047. n.normalize();
  28048. for (j = 0; j < tubularSegments; j++) {
  28049. var modJ = j % tubularSegments;
  28050. var v = modJ / tubularSegments * 2 * Math.PI;
  28051. var cx = -tube * Math.cos(v);
  28052. var cy = tube * Math.sin(v);
  28053. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28054. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28055. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28056. uvs.push(i / radialSegments);
  28057. uvs.push(j / tubularSegments);
  28058. }
  28059. }
  28060. for (i = 0; i < radialSegments; i++) {
  28061. for (j = 0; j < tubularSegments; j++) {
  28062. var jNext = (j + 1) % tubularSegments;
  28063. var a = i * tubularSegments + j;
  28064. var b = (i + 1) * tubularSegments + j;
  28065. var c = (i + 1) * tubularSegments + jNext;
  28066. var d = i * tubularSegments + jNext;
  28067. indices.push(d);
  28068. indices.push(b);
  28069. indices.push(a);
  28070. indices.push(d);
  28071. indices.push(c);
  28072. indices.push(b);
  28073. }
  28074. }
  28075. // Normals
  28076. VertexData.ComputeNormals(positions, indices, normals);
  28077. // Sides
  28078. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28079. // Result
  28080. var vertexData = new VertexData();
  28081. vertexData.indices = indices;
  28082. vertexData.positions = positions;
  28083. vertexData.normals = normals;
  28084. vertexData.uvs = uvs;
  28085. return vertexData;
  28086. };
  28087. // Tools
  28088. /**
  28089. * @param {any} - positions (number[] or Float32Array)
  28090. * @param {any} - indices (number[] or Uint16Array)
  28091. * @param {any} - normals (number[] or Float32Array)
  28092. * options (optional) :
  28093. * facetPositions : optional array of facet positions (vector3)
  28094. * facetNormals : optional array of facet normals (vector3)
  28095. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28096. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28097. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28098. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28099. * bInfo : optional bounding info, required for facetPartitioning computation
  28100. */
  28101. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28102. // temporary scalar variables
  28103. var index = 0; // facet index
  28104. var p1p2x = 0.0; // p1p2 vector x coordinate
  28105. var p1p2y = 0.0; // p1p2 vector y coordinate
  28106. var p1p2z = 0.0; // p1p2 vector z coordinate
  28107. var p3p2x = 0.0; // p3p2 vector x coordinate
  28108. var p3p2y = 0.0; // p3p2 vector y coordinate
  28109. var p3p2z = 0.0; // p3p2 vector z coordinate
  28110. var faceNormalx = 0.0; // facet normal x coordinate
  28111. var faceNormaly = 0.0; // facet normal y coordinate
  28112. var faceNormalz = 0.0; // facet normal z coordinate
  28113. var length = 0.0; // facet normal length before normalization
  28114. var v1x = 0; // vector1 x index in the positions array
  28115. var v1y = 0; // vector1 y index in the positions array
  28116. var v1z = 0; // vector1 z index in the positions array
  28117. var v2x = 0; // vector2 x index in the positions array
  28118. var v2y = 0; // vector2 y index in the positions array
  28119. var v2z = 0; // vector2 z index in the positions array
  28120. var v3x = 0; // vector3 x index in the positions array
  28121. var v3y = 0; // vector3 y index in the positions array
  28122. var v3z = 0; // vector3 z index in the positions array
  28123. var computeFacetNormals = false;
  28124. var computeFacetPositions = false;
  28125. var computeFacetPartitioning = false;
  28126. var faceNormalSign = 1;
  28127. if (options) {
  28128. computeFacetNormals = (options.facetNormals) ? true : false;
  28129. computeFacetPositions = (options.facetPositions) ? true : false;
  28130. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28131. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28132. }
  28133. // facetPartitioning reinit if needed
  28134. if (computeFacetPartitioning) {
  28135. var ox = 0; // X partitioning index for facet position
  28136. var oy = 0; // Y partinioning index for facet position
  28137. var oz = 0; // Z partinioning index for facet position
  28138. var b1x = 0; // X partitioning index for facet v1 vertex
  28139. var b1y = 0; // Y partitioning index for facet v1 vertex
  28140. var b1z = 0; // z partitioning index for facet v1 vertex
  28141. var b2x = 0; // X partitioning index for facet v2 vertex
  28142. var b2y = 0; // Y partitioning index for facet v2 vertex
  28143. var b2z = 0; // Z partitioning index for facet v2 vertex
  28144. var b3x = 0; // X partitioning index for facet v3 vertex
  28145. var b3y = 0; // Y partitioning index for facet v3 vertex
  28146. var b3z = 0; // Z partitioning index for facet v3 vertex
  28147. var block_idx_o = 0; // facet barycenter block index
  28148. var block_idx_v1 = 0; // v1 vertex block index
  28149. var block_idx_v2 = 0; // v2 vertex block index
  28150. var block_idx_v3 = 0; // v3 vertex block index
  28151. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28152. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28153. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28154. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28155. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28156. var subSq = options.subDiv.max * options.subDiv.max;
  28157. options.facetPartitioning.length = 0;
  28158. }
  28159. // reset the normals
  28160. for (index = 0; index < positions.length; index++) {
  28161. normals[index] = 0.0;
  28162. }
  28163. // Loop : 1 indice triplet = 1 facet
  28164. var nbFaces = indices.length / 3;
  28165. for (index = 0; index < nbFaces; index++) {
  28166. // get the indexes of the coordinates of each vertex of the facet
  28167. v1x = indices[index * 3] * 3;
  28168. v1y = v1x + 1;
  28169. v1z = v1x + 2;
  28170. v2x = indices[index * 3 + 1] * 3;
  28171. v2y = v2x + 1;
  28172. v2z = v2x + 2;
  28173. v3x = indices[index * 3 + 2] * 3;
  28174. v3y = v3x + 1;
  28175. v3z = v3x + 2;
  28176. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28177. p1p2y = positions[v1y] - positions[v2y];
  28178. p1p2z = positions[v1z] - positions[v2z];
  28179. p3p2x = positions[v3x] - positions[v2x];
  28180. p3p2y = positions[v3y] - positions[v2y];
  28181. p3p2z = positions[v3z] - positions[v2z];
  28182. // compute the face normal with the cross product
  28183. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28184. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28185. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28186. // normalize this normal and store it in the array facetData
  28187. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28188. length = (length === 0) ? 1.0 : length;
  28189. faceNormalx /= length;
  28190. faceNormaly /= length;
  28191. faceNormalz /= length;
  28192. if (computeFacetNormals) {
  28193. options.facetNormals[index].x = faceNormalx;
  28194. options.facetNormals[index].y = faceNormaly;
  28195. options.facetNormals[index].z = faceNormalz;
  28196. }
  28197. if (computeFacetPositions) {
  28198. // compute and the facet barycenter coordinates in the array facetPositions
  28199. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28200. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28201. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28202. }
  28203. if (computeFacetPartitioning) {
  28204. // store the facet indexes in arrays in the main facetPartitioning array :
  28205. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28206. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28207. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28208. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28209. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28210. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28211. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28212. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28213. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28214. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28215. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28216. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28217. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28218. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28219. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28220. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28221. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28222. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28223. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28224. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28225. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28226. // push each facet index in each block containing the vertex
  28227. options.facetPartitioning[block_idx_v1].push(index);
  28228. if (block_idx_v2 != block_idx_v1) {
  28229. options.facetPartitioning[block_idx_v2].push(index);
  28230. }
  28231. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28232. options.facetPartitioning[block_idx_v3].push(index);
  28233. }
  28234. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28235. options.facetPartitioning[block_idx_o].push(index);
  28236. }
  28237. }
  28238. // compute the normals anyway
  28239. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28240. normals[v1y] += faceNormaly;
  28241. normals[v1z] += faceNormalz;
  28242. normals[v2x] += faceNormalx;
  28243. normals[v2y] += faceNormaly;
  28244. normals[v2z] += faceNormalz;
  28245. normals[v3x] += faceNormalx;
  28246. normals[v3y] += faceNormaly;
  28247. normals[v3z] += faceNormalz;
  28248. }
  28249. // last normalization of each normal
  28250. for (index = 0; index < normals.length / 3; index++) {
  28251. faceNormalx = normals[index * 3];
  28252. faceNormaly = normals[index * 3 + 1];
  28253. faceNormalz = normals[index * 3 + 2];
  28254. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28255. length = (length === 0) ? 1.0 : length;
  28256. faceNormalx /= length;
  28257. faceNormaly /= length;
  28258. faceNormalz /= length;
  28259. normals[index * 3] = faceNormalx;
  28260. normals[index * 3 + 1] = faceNormaly;
  28261. normals[index * 3 + 2] = faceNormalz;
  28262. }
  28263. };
  28264. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28265. var li = indices.length;
  28266. var ln = normals.length;
  28267. var i;
  28268. var n;
  28269. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28270. switch (sideOrientation) {
  28271. case BABYLON.Mesh.FRONTSIDE:
  28272. // nothing changed
  28273. break;
  28274. case BABYLON.Mesh.BACKSIDE:
  28275. var tmp;
  28276. // indices
  28277. for (i = 0; i < li; i += 3) {
  28278. tmp = indices[i];
  28279. indices[i] = indices[i + 2];
  28280. indices[i + 2] = tmp;
  28281. }
  28282. // normals
  28283. for (n = 0; n < ln; n++) {
  28284. normals[n] = -normals[n];
  28285. }
  28286. break;
  28287. case BABYLON.Mesh.DOUBLESIDE:
  28288. // positions
  28289. var lp = positions.length;
  28290. var l = lp / 3;
  28291. for (var p = 0; p < lp; p++) {
  28292. positions[lp + p] = positions[p];
  28293. }
  28294. // indices
  28295. for (i = 0; i < li; i += 3) {
  28296. indices[i + li] = indices[i + 2] + l;
  28297. indices[i + 1 + li] = indices[i + 1] + l;
  28298. indices[i + 2 + li] = indices[i] + l;
  28299. }
  28300. // normals
  28301. for (n = 0; n < ln; n++) {
  28302. normals[ln + n] = -normals[n];
  28303. }
  28304. // uvs
  28305. var lu = uvs.length;
  28306. var u = 0;
  28307. for (u = 0; u < lu; u++) {
  28308. uvs[u + lu] = uvs[u];
  28309. }
  28310. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28311. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28312. u = 0;
  28313. for (i = 0; i < lu / 2; i++) {
  28314. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28315. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28316. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28317. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28318. u += 2;
  28319. }
  28320. break;
  28321. }
  28322. };
  28323. /**
  28324. * Creates a new VertexData from the imported parameters.
  28325. */
  28326. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28327. var vertexData = new VertexData();
  28328. // positions
  28329. var positions = parsedVertexData.positions;
  28330. if (positions) {
  28331. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28332. }
  28333. // normals
  28334. var normals = parsedVertexData.normals;
  28335. if (normals) {
  28336. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28337. }
  28338. // tangents
  28339. var tangents = parsedVertexData.tangents;
  28340. if (tangents) {
  28341. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28342. }
  28343. // uvs
  28344. var uvs = parsedVertexData.uvs;
  28345. if (uvs) {
  28346. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28347. }
  28348. // uv2s
  28349. var uv2s = parsedVertexData.uv2s;
  28350. if (uv2s) {
  28351. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28352. }
  28353. // uv3s
  28354. var uv3s = parsedVertexData.uv3s;
  28355. if (uv3s) {
  28356. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28357. }
  28358. // uv4s
  28359. var uv4s = parsedVertexData.uv4s;
  28360. if (uv4s) {
  28361. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28362. }
  28363. // uv5s
  28364. var uv5s = parsedVertexData.uv5s;
  28365. if (uv5s) {
  28366. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28367. }
  28368. // uv6s
  28369. var uv6s = parsedVertexData.uv6s;
  28370. if (uv6s) {
  28371. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28372. }
  28373. // colors
  28374. var colors = parsedVertexData.colors;
  28375. if (colors) {
  28376. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28377. }
  28378. // matricesIndices
  28379. var matricesIndices = parsedVertexData.matricesIndices;
  28380. if (matricesIndices) {
  28381. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28382. }
  28383. // matricesWeights
  28384. var matricesWeights = parsedVertexData.matricesWeights;
  28385. if (matricesWeights) {
  28386. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28387. }
  28388. // indices
  28389. var indices = parsedVertexData.indices;
  28390. if (indices) {
  28391. vertexData.indices = indices;
  28392. }
  28393. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28394. };
  28395. return VertexData;
  28396. }());
  28397. BABYLON.VertexData = VertexData;
  28398. })(BABYLON || (BABYLON = {}));
  28399. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28400. var BABYLON;
  28401. (function (BABYLON) {
  28402. var Geometry = (function () {
  28403. function Geometry(id, scene, vertexData, updatable, mesh) {
  28404. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28405. this._totalVertices = 0;
  28406. this._isDisposed = false;
  28407. this.id = id;
  28408. this._engine = scene.getEngine();
  28409. this._meshes = [];
  28410. this._scene = scene;
  28411. //Init vertex buffer cache
  28412. this._vertexBuffers = {};
  28413. this._indices = [];
  28414. this._updatable = updatable;
  28415. // vertexData
  28416. if (vertexData) {
  28417. this.setAllVerticesData(vertexData, updatable);
  28418. }
  28419. else {
  28420. this._totalVertices = 0;
  28421. this._indices = [];
  28422. }
  28423. if (this._engine.getCaps().vertexArrayObject) {
  28424. this._vertexArrayObjects = {};
  28425. }
  28426. // applyToMesh
  28427. if (mesh) {
  28428. if (mesh.getClassName() === "LinesMesh") {
  28429. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28430. this.updateExtend();
  28431. }
  28432. this.applyToMesh(mesh);
  28433. mesh.computeWorldMatrix(true);
  28434. }
  28435. }
  28436. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28437. /**
  28438. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  28439. * @returns The Bias Vector
  28440. */
  28441. get: function () {
  28442. return this._boundingBias;
  28443. },
  28444. set: function (value) {
  28445. if (this._boundingBias && this._boundingBias.equals(value)) {
  28446. return;
  28447. }
  28448. this._boundingBias = value.clone();
  28449. this.updateBoundingInfo(true, null);
  28450. },
  28451. enumerable: true,
  28452. configurable: true
  28453. });
  28454. Object.defineProperty(Geometry.prototype, "extend", {
  28455. get: function () {
  28456. return this._extend;
  28457. },
  28458. enumerable: true,
  28459. configurable: true
  28460. });
  28461. Geometry.prototype.getScene = function () {
  28462. return this._scene;
  28463. };
  28464. Geometry.prototype.getEngine = function () {
  28465. return this._engine;
  28466. };
  28467. Geometry.prototype.isReady = function () {
  28468. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28469. };
  28470. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28471. get: function () {
  28472. for (var index = 0; index < this._meshes.length; index++) {
  28473. if (!this._meshes[index].doNotSerialize) {
  28474. return false;
  28475. }
  28476. }
  28477. return true;
  28478. },
  28479. enumerable: true,
  28480. configurable: true
  28481. });
  28482. Geometry.prototype._rebuild = function () {
  28483. if (this._vertexArrayObjects) {
  28484. this._vertexArrayObjects = {};
  28485. }
  28486. // Index buffer
  28487. if (this._meshes.length !== 0 && this._indices) {
  28488. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28489. }
  28490. // Vertex buffers
  28491. for (var key in this._vertexBuffers) {
  28492. var vertexBuffer = this._vertexBuffers[key];
  28493. vertexBuffer._rebuild();
  28494. }
  28495. };
  28496. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28497. vertexData.applyToGeometry(this, updatable);
  28498. this.notifyUpdate();
  28499. };
  28500. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28501. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28502. this.setVerticesBuffer(buffer);
  28503. };
  28504. Geometry.prototype.removeVerticesData = function (kind) {
  28505. if (this._vertexBuffers[kind]) {
  28506. this._vertexBuffers[kind].dispose();
  28507. delete this._vertexBuffers[kind];
  28508. }
  28509. };
  28510. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28511. var kind = buffer.getKind();
  28512. if (this._vertexBuffers[kind]) {
  28513. this._vertexBuffers[kind].dispose();
  28514. }
  28515. this._vertexBuffers[kind] = buffer;
  28516. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28517. var data = buffer.getData();
  28518. var stride = buffer.getStrideSize();
  28519. this._totalVertices = data.length / stride;
  28520. this.updateExtend(data, stride);
  28521. this._resetPointsArrayCache();
  28522. var meshes = this._meshes;
  28523. var numOfMeshes = meshes.length;
  28524. for (var index = 0; index < numOfMeshes; index++) {
  28525. var mesh = meshes[index];
  28526. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28527. mesh._createGlobalSubMesh(false);
  28528. mesh.computeWorldMatrix(true);
  28529. }
  28530. }
  28531. this.notifyUpdate(kind);
  28532. if (this._vertexArrayObjects) {
  28533. this._disposeVertexArrayObjects();
  28534. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28535. }
  28536. };
  28537. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28538. var vertexBuffer = this.getVertexBuffer(kind);
  28539. if (!vertexBuffer) {
  28540. return;
  28541. }
  28542. vertexBuffer.updateDirectly(data, offset);
  28543. this.notifyUpdate(kind);
  28544. };
  28545. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28546. var vertexBuffer = this.getVertexBuffer(kind);
  28547. if (!vertexBuffer) {
  28548. return;
  28549. }
  28550. vertexBuffer.update(data);
  28551. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28552. var stride = vertexBuffer.getStrideSize();
  28553. this._totalVertices = data.length / stride;
  28554. this.updateBoundingInfo(updateExtends, data);
  28555. }
  28556. this.notifyUpdate(kind);
  28557. };
  28558. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28559. if (updateExtends) {
  28560. this.updateExtend(data);
  28561. }
  28562. var meshes = this._meshes;
  28563. var numOfMeshes = meshes.length;
  28564. this._resetPointsArrayCache();
  28565. for (var index = 0; index < numOfMeshes; index++) {
  28566. var mesh = meshes[index];
  28567. if (updateExtends) {
  28568. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28569. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28570. var subMesh = mesh.subMeshes[subIndex];
  28571. subMesh.refreshBoundingInfo();
  28572. }
  28573. }
  28574. }
  28575. };
  28576. Geometry.prototype._bind = function (effect, indexToBind) {
  28577. if (indexToBind === void 0) { indexToBind = undefined; }
  28578. if (indexToBind === undefined) {
  28579. indexToBind = this._indexBuffer;
  28580. }
  28581. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28582. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28583. return;
  28584. }
  28585. // Using VAO
  28586. if (!this._vertexArrayObjects[effect.key]) {
  28587. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28588. }
  28589. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28590. };
  28591. Geometry.prototype.getTotalVertices = function () {
  28592. if (!this.isReady()) {
  28593. return 0;
  28594. }
  28595. return this._totalVertices;
  28596. };
  28597. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28598. var vertexBuffer = this.getVertexBuffer(kind);
  28599. if (!vertexBuffer) {
  28600. return null;
  28601. }
  28602. var orig = vertexBuffer.getData();
  28603. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28604. return orig;
  28605. }
  28606. else {
  28607. var len = orig.length;
  28608. var copy = [];
  28609. for (var i = 0; i < len; i++) {
  28610. copy.push(orig[i]);
  28611. }
  28612. return copy;
  28613. }
  28614. };
  28615. Geometry.prototype.getVertexBuffer = function (kind) {
  28616. if (!this.isReady()) {
  28617. return null;
  28618. }
  28619. return this._vertexBuffers[kind];
  28620. };
  28621. Geometry.prototype.getVertexBuffers = function () {
  28622. if (!this.isReady()) {
  28623. return null;
  28624. }
  28625. return this._vertexBuffers;
  28626. };
  28627. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28628. if (!this._vertexBuffers) {
  28629. if (this._delayInfo) {
  28630. return this._delayInfo.indexOf(kind) !== -1;
  28631. }
  28632. return false;
  28633. }
  28634. return this._vertexBuffers[kind] !== undefined;
  28635. };
  28636. Geometry.prototype.getVerticesDataKinds = function () {
  28637. var result = [];
  28638. var kind;
  28639. if (!this._vertexBuffers && this._delayInfo) {
  28640. for (kind in this._delayInfo) {
  28641. result.push(kind);
  28642. }
  28643. }
  28644. else {
  28645. for (kind in this._vertexBuffers) {
  28646. result.push(kind);
  28647. }
  28648. }
  28649. return result;
  28650. };
  28651. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28652. if (this._indexBuffer) {
  28653. this._engine._releaseBuffer(this._indexBuffer);
  28654. }
  28655. this._disposeVertexArrayObjects();
  28656. this._indices = indices;
  28657. if (this._meshes.length !== 0 && this._indices) {
  28658. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28659. }
  28660. if (totalVertices !== undefined) {
  28661. this._totalVertices = totalVertices;
  28662. }
  28663. var meshes = this._meshes;
  28664. var numOfMeshes = meshes.length;
  28665. for (var index = 0; index < numOfMeshes; index++) {
  28666. meshes[index]._createGlobalSubMesh(true);
  28667. }
  28668. this.notifyUpdate();
  28669. };
  28670. Geometry.prototype.getTotalIndices = function () {
  28671. if (!this.isReady()) {
  28672. return 0;
  28673. }
  28674. return this._indices.length;
  28675. };
  28676. Geometry.prototype.getIndices = function (copyWhenShared) {
  28677. if (!this.isReady()) {
  28678. return null;
  28679. }
  28680. var orig = this._indices;
  28681. if (!copyWhenShared || this._meshes.length === 1) {
  28682. return orig;
  28683. }
  28684. else {
  28685. var len = orig.length;
  28686. var copy = [];
  28687. for (var i = 0; i < len; i++) {
  28688. copy.push(orig[i]);
  28689. }
  28690. return copy;
  28691. }
  28692. };
  28693. Geometry.prototype.getIndexBuffer = function () {
  28694. if (!this.isReady()) {
  28695. return null;
  28696. }
  28697. return this._indexBuffer;
  28698. };
  28699. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28700. if (!effect || !this._vertexArrayObjects) {
  28701. return;
  28702. }
  28703. if (this._vertexArrayObjects[effect.key]) {
  28704. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28705. delete this._vertexArrayObjects[effect.key];
  28706. }
  28707. };
  28708. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28709. var meshes = this._meshes;
  28710. var index = meshes.indexOf(mesh);
  28711. if (index === -1) {
  28712. return;
  28713. }
  28714. meshes.splice(index, 1);
  28715. mesh._geometry = null;
  28716. if (meshes.length === 0 && shouldDispose) {
  28717. this.dispose();
  28718. }
  28719. };
  28720. Geometry.prototype.applyToMesh = function (mesh) {
  28721. if (mesh._geometry === this) {
  28722. return;
  28723. }
  28724. var previousGeometry = mesh._geometry;
  28725. if (previousGeometry) {
  28726. previousGeometry.releaseForMesh(mesh);
  28727. }
  28728. var meshes = this._meshes;
  28729. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28730. mesh._geometry = this;
  28731. this._scene.pushGeometry(this);
  28732. meshes.push(mesh);
  28733. if (this.isReady()) {
  28734. this._applyToMesh(mesh);
  28735. }
  28736. else {
  28737. mesh._boundingInfo = this._boundingInfo;
  28738. }
  28739. };
  28740. Geometry.prototype.updateExtend = function (data, stride) {
  28741. if (data === void 0) { data = null; }
  28742. if (!data) {
  28743. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28744. }
  28745. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28746. };
  28747. Geometry.prototype._applyToMesh = function (mesh) {
  28748. var numOfMeshes = this._meshes.length;
  28749. // vertexBuffers
  28750. for (var kind in this._vertexBuffers) {
  28751. if (numOfMeshes === 1) {
  28752. this._vertexBuffers[kind].create();
  28753. }
  28754. var buffer = this._vertexBuffers[kind].getBuffer();
  28755. if (buffer)
  28756. buffer.references = numOfMeshes;
  28757. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28758. if (!this._extend) {
  28759. this.updateExtend(this._vertexBuffers[kind].getData());
  28760. }
  28761. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28762. mesh._createGlobalSubMesh(false);
  28763. //bounding info was just created again, world matrix should be applied again.
  28764. mesh._updateBoundingInfo();
  28765. }
  28766. }
  28767. // indexBuffer
  28768. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28769. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28770. }
  28771. if (this._indexBuffer) {
  28772. this._indexBuffer.references = numOfMeshes;
  28773. }
  28774. };
  28775. Geometry.prototype.notifyUpdate = function (kind) {
  28776. if (this.onGeometryUpdated) {
  28777. this.onGeometryUpdated(this, kind);
  28778. }
  28779. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28780. var mesh = _a[_i];
  28781. mesh._markSubMeshesAsAttributesDirty();
  28782. }
  28783. };
  28784. Geometry.prototype.load = function (scene, onLoaded) {
  28785. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28786. return;
  28787. }
  28788. if (this.isReady()) {
  28789. if (onLoaded) {
  28790. onLoaded();
  28791. }
  28792. return;
  28793. }
  28794. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28795. this._queueLoad(scene, onLoaded);
  28796. };
  28797. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28798. var _this = this;
  28799. scene._addPendingData(this);
  28800. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28801. _this._delayLoadingFunction(JSON.parse(data), _this);
  28802. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28803. _this._delayInfo = [];
  28804. scene._removePendingData(_this);
  28805. var meshes = _this._meshes;
  28806. var numOfMeshes = meshes.length;
  28807. for (var index = 0; index < numOfMeshes; index++) {
  28808. _this._applyToMesh(meshes[index]);
  28809. }
  28810. if (onLoaded) {
  28811. onLoaded();
  28812. }
  28813. }, function () { }, scene.database);
  28814. };
  28815. /**
  28816. * Invert the geometry to move from a right handed system to a left handed one.
  28817. */
  28818. Geometry.prototype.toLeftHanded = function () {
  28819. // Flip faces
  28820. var tIndices = this.getIndices(false);
  28821. if (tIndices != null && tIndices.length > 0) {
  28822. for (var i = 0; i < tIndices.length; i += 3) {
  28823. var tTemp = tIndices[i + 0];
  28824. tIndices[i + 0] = tIndices[i + 2];
  28825. tIndices[i + 2] = tTemp;
  28826. }
  28827. this.setIndices(tIndices);
  28828. }
  28829. // Negate position.z
  28830. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28831. if (tPositions != null && tPositions.length > 0) {
  28832. for (var i = 0; i < tPositions.length; i += 3) {
  28833. tPositions[i + 2] = -tPositions[i + 2];
  28834. }
  28835. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28836. }
  28837. // Negate normal.z
  28838. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28839. if (tNormals != null && tNormals.length > 0) {
  28840. for (var i = 0; i < tNormals.length; i += 3) {
  28841. tNormals[i + 2] = -tNormals[i + 2];
  28842. }
  28843. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28844. }
  28845. };
  28846. // Cache
  28847. Geometry.prototype._resetPointsArrayCache = function () {
  28848. this._positions = null;
  28849. };
  28850. Geometry.prototype._generatePointsArray = function () {
  28851. if (this._positions)
  28852. return true;
  28853. this._positions = [];
  28854. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28855. if (!data) {
  28856. return false;
  28857. }
  28858. for (var index = 0; index < data.length; index += 3) {
  28859. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28860. }
  28861. return true;
  28862. };
  28863. Geometry.prototype.isDisposed = function () {
  28864. return this._isDisposed;
  28865. };
  28866. Geometry.prototype._disposeVertexArrayObjects = function () {
  28867. if (this._vertexArrayObjects) {
  28868. for (var kind in this._vertexArrayObjects) {
  28869. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28870. }
  28871. this._vertexArrayObjects = {};
  28872. }
  28873. };
  28874. Geometry.prototype.dispose = function () {
  28875. var meshes = this._meshes;
  28876. var numOfMeshes = meshes.length;
  28877. var index;
  28878. for (index = 0; index < numOfMeshes; index++) {
  28879. this.releaseForMesh(meshes[index]);
  28880. }
  28881. this._meshes = [];
  28882. this._disposeVertexArrayObjects();
  28883. for (var kind in this._vertexBuffers) {
  28884. this._vertexBuffers[kind].dispose();
  28885. }
  28886. this._vertexBuffers = {};
  28887. this._totalVertices = 0;
  28888. if (this._indexBuffer) {
  28889. this._engine._releaseBuffer(this._indexBuffer);
  28890. }
  28891. this._indexBuffer = null;
  28892. this._indices = [];
  28893. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28894. this.delayLoadingFile = null;
  28895. this._delayLoadingFunction = null;
  28896. this._delayInfo = [];
  28897. this._boundingInfo = null;
  28898. this._scene.removeGeometry(this);
  28899. this._isDisposed = true;
  28900. };
  28901. Geometry.prototype.copy = function (id) {
  28902. var vertexData = new BABYLON.VertexData();
  28903. vertexData.indices = [];
  28904. var indices = this.getIndices();
  28905. for (var index = 0; index < indices.length; index++) {
  28906. vertexData.indices.push(indices[index]);
  28907. }
  28908. var updatable = false;
  28909. var stopChecking = false;
  28910. var kind;
  28911. for (kind in this._vertexBuffers) {
  28912. // using slice() to make a copy of the array and not just reference it
  28913. var data = this.getVerticesData(kind);
  28914. if (data instanceof Float32Array) {
  28915. vertexData.set(new Float32Array(data), kind);
  28916. }
  28917. else {
  28918. vertexData.set(data.slice(0), kind);
  28919. }
  28920. if (!stopChecking) {
  28921. updatable = this.getVertexBuffer(kind).isUpdatable();
  28922. stopChecking = !updatable;
  28923. }
  28924. }
  28925. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28926. geometry.delayLoadState = this.delayLoadState;
  28927. geometry.delayLoadingFile = this.delayLoadingFile;
  28928. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28929. for (kind in this._delayInfo) {
  28930. geometry._delayInfo = geometry._delayInfo || [];
  28931. geometry._delayInfo.push(kind);
  28932. }
  28933. // Bounding info
  28934. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28935. return geometry;
  28936. };
  28937. Geometry.prototype.serialize = function () {
  28938. var serializationObject = {};
  28939. serializationObject.id = this.id;
  28940. serializationObject.updatable = this._updatable;
  28941. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28942. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28943. }
  28944. return serializationObject;
  28945. };
  28946. Geometry.prototype.toNumberArray = function (origin) {
  28947. if (Array.isArray(origin)) {
  28948. return origin;
  28949. }
  28950. else {
  28951. return Array.prototype.slice.call(origin);
  28952. }
  28953. };
  28954. Geometry.prototype.serializeVerticeData = function () {
  28955. var serializationObject = this.serialize();
  28956. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28957. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28958. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28959. serializationObject.positions._updatable = true;
  28960. }
  28961. }
  28962. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28963. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28964. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28965. serializationObject.normals._updatable = true;
  28966. }
  28967. }
  28968. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28969. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28970. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28971. serializationObject.uvs._updatable = true;
  28972. }
  28973. }
  28974. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28975. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28976. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28977. serializationObject.uv2s._updatable = true;
  28978. }
  28979. }
  28980. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28981. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28982. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28983. serializationObject.uv3s._updatable = true;
  28984. }
  28985. }
  28986. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28987. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28988. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28989. serializationObject.uv4s._updatable = true;
  28990. }
  28991. }
  28992. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28993. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28994. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28995. serializationObject.uv5s._updatable = true;
  28996. }
  28997. }
  28998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28999. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29000. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29001. serializationObject.uv6s._updatable = true;
  29002. }
  29003. }
  29004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29005. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29006. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29007. serializationObject.colors._updatable = true;
  29008. }
  29009. }
  29010. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29011. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29012. serializationObject.matricesIndices._isExpanded = true;
  29013. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29014. serializationObject.matricesIndices._updatable = true;
  29015. }
  29016. }
  29017. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29018. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29019. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29020. serializationObject.matricesWeights._updatable = true;
  29021. }
  29022. }
  29023. serializationObject.indices = this.toNumberArray(this.getIndices());
  29024. return serializationObject;
  29025. };
  29026. // Statics
  29027. Geometry.ExtractFromMesh = function (mesh, id) {
  29028. var geometry = mesh._geometry;
  29029. if (!geometry) {
  29030. return null;
  29031. }
  29032. return geometry.copy(id);
  29033. };
  29034. /**
  29035. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29036. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29037. * Be aware Math.random() could cause collisions, but:
  29038. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  29039. */
  29040. Geometry.RandomId = function () {
  29041. return BABYLON.Tools.RandomId();
  29042. };
  29043. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29044. var scene = mesh.getScene();
  29045. // Geometry
  29046. var geometryId = parsedGeometry.geometryId;
  29047. if (geometryId) {
  29048. var geometry = scene.getGeometryByID(geometryId);
  29049. if (geometry) {
  29050. geometry.applyToMesh(mesh);
  29051. }
  29052. }
  29053. else if (parsedGeometry instanceof ArrayBuffer) {
  29054. var binaryInfo = mesh._binaryInfo;
  29055. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29056. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29057. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29058. }
  29059. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29060. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29061. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29062. }
  29063. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29064. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29065. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29066. }
  29067. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29068. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29069. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29070. }
  29071. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29072. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29073. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29074. }
  29075. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29076. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29077. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29078. }
  29079. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29080. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29081. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29082. }
  29083. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29084. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29085. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29086. }
  29087. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29088. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29089. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29090. }
  29091. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29092. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29093. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29094. }
  29095. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29096. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29097. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29098. }
  29099. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29100. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29101. mesh.setIndices(indicesData);
  29102. }
  29103. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29104. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29105. mesh.subMeshes = [];
  29106. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29107. var materialIndex = subMeshesData[(i * 5) + 0];
  29108. var verticesStart = subMeshesData[(i * 5) + 1];
  29109. var verticesCount = subMeshesData[(i * 5) + 2];
  29110. var indexStart = subMeshesData[(i * 5) + 3];
  29111. var indexCount = subMeshesData[(i * 5) + 4];
  29112. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29113. }
  29114. }
  29115. }
  29116. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29117. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29118. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29119. if (parsedGeometry.uvs) {
  29120. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29121. }
  29122. if (parsedGeometry.uvs2) {
  29123. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29124. }
  29125. if (parsedGeometry.uvs3) {
  29126. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29127. }
  29128. if (parsedGeometry.uvs4) {
  29129. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29130. }
  29131. if (parsedGeometry.uvs5) {
  29132. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29133. }
  29134. if (parsedGeometry.uvs6) {
  29135. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29136. }
  29137. if (parsedGeometry.colors) {
  29138. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29139. }
  29140. if (parsedGeometry.matricesIndices) {
  29141. if (!parsedGeometry.matricesIndices._isExpanded) {
  29142. var floatIndices = [];
  29143. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29144. var matricesIndex = parsedGeometry.matricesIndices[i];
  29145. floatIndices.push(matricesIndex & 0x000000FF);
  29146. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29147. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29148. floatIndices.push(matricesIndex >> 24);
  29149. }
  29150. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29151. }
  29152. else {
  29153. delete parsedGeometry.matricesIndices._isExpanded;
  29154. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29155. }
  29156. }
  29157. if (parsedGeometry.matricesIndicesExtra) {
  29158. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29159. var floatIndices = [];
  29160. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29161. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29162. floatIndices.push(matricesIndex & 0x000000FF);
  29163. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29164. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29165. floatIndices.push(matricesIndex >> 24);
  29166. }
  29167. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29168. }
  29169. else {
  29170. delete parsedGeometry.matricesIndices._isExpanded;
  29171. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29172. }
  29173. }
  29174. if (parsedGeometry.matricesWeights) {
  29175. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29176. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29177. }
  29178. if (parsedGeometry.matricesWeightsExtra) {
  29179. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29180. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29181. }
  29182. mesh.setIndices(parsedGeometry.indices);
  29183. }
  29184. // SubMeshes
  29185. if (parsedGeometry.subMeshes) {
  29186. mesh.subMeshes = [];
  29187. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29188. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29189. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29190. }
  29191. }
  29192. // Flat shading
  29193. if (mesh._shouldGenerateFlatShading) {
  29194. mesh.convertToFlatShadedMesh();
  29195. delete mesh._shouldGenerateFlatShading;
  29196. }
  29197. // Update
  29198. mesh.computeWorldMatrix(true);
  29199. // Octree
  29200. if (scene['_selectionOctree']) {
  29201. scene['_selectionOctree'].addMesh(mesh);
  29202. }
  29203. };
  29204. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29205. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29206. return;
  29207. }
  29208. var size = matricesWeights.length;
  29209. for (var i = 0; i < size; i += influencers) {
  29210. var weight = 0;
  29211. var biggerIndex = i;
  29212. var biggerWeight = 0;
  29213. for (var j = 0; j < influencers - 1; j++) {
  29214. weight += matricesWeights[i + j];
  29215. if (matricesWeights[i + j] > biggerWeight) {
  29216. biggerWeight = matricesWeights[i + j];
  29217. biggerIndex = i + j;
  29218. }
  29219. }
  29220. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29221. }
  29222. };
  29223. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29224. if (scene.getGeometryByID(parsedVertexData.id)) {
  29225. return null; // null since geometry could be something else than a box...
  29226. }
  29227. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29228. if (BABYLON.Tags) {
  29229. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29230. }
  29231. if (parsedVertexData.delayLoadingFile) {
  29232. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29233. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29234. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29235. geometry._delayInfo = [];
  29236. if (parsedVertexData.hasUVs) {
  29237. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29238. }
  29239. if (parsedVertexData.hasUVs2) {
  29240. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29241. }
  29242. if (parsedVertexData.hasUVs3) {
  29243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29244. }
  29245. if (parsedVertexData.hasUVs4) {
  29246. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29247. }
  29248. if (parsedVertexData.hasUVs5) {
  29249. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29250. }
  29251. if (parsedVertexData.hasUVs6) {
  29252. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29253. }
  29254. if (parsedVertexData.hasColors) {
  29255. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29256. }
  29257. if (parsedVertexData.hasMatricesIndices) {
  29258. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29259. }
  29260. if (parsedVertexData.hasMatricesWeights) {
  29261. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29262. }
  29263. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29264. }
  29265. else {
  29266. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29267. }
  29268. scene.pushGeometry(geometry, true);
  29269. return geometry;
  29270. };
  29271. return Geometry;
  29272. }());
  29273. BABYLON.Geometry = Geometry;
  29274. /////// Primitives //////////////////////////////////////////////
  29275. (function (Geometry) {
  29276. var Primitives;
  29277. (function (Primitives) {
  29278. /// Abstract class
  29279. var _Primitive = (function (_super) {
  29280. __extends(_Primitive, _super);
  29281. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29282. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29283. _this._canBeRegenerated = _canBeRegenerated;
  29284. _this._beingRegenerated = true;
  29285. _this.regenerate();
  29286. _this._beingRegenerated = false;
  29287. return _this;
  29288. }
  29289. _Primitive.prototype.canBeRegenerated = function () {
  29290. return this._canBeRegenerated;
  29291. };
  29292. _Primitive.prototype.regenerate = function () {
  29293. if (!this._canBeRegenerated) {
  29294. return;
  29295. }
  29296. this._beingRegenerated = true;
  29297. this.setAllVerticesData(this._regenerateVertexData(), false);
  29298. this._beingRegenerated = false;
  29299. };
  29300. _Primitive.prototype.asNewGeometry = function (id) {
  29301. return _super.prototype.copy.call(this, id);
  29302. };
  29303. // overrides
  29304. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29305. if (!this._beingRegenerated) {
  29306. return;
  29307. }
  29308. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29309. };
  29310. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29311. if (!this._beingRegenerated) {
  29312. return;
  29313. }
  29314. _super.prototype.setVerticesData.call(this, kind, data, false);
  29315. };
  29316. // to override
  29317. // protected
  29318. _Primitive.prototype._regenerateVertexData = function () {
  29319. throw new Error("Abstract method");
  29320. };
  29321. _Primitive.prototype.copy = function (id) {
  29322. throw new Error("Must be overriden in sub-classes.");
  29323. };
  29324. _Primitive.prototype.serialize = function () {
  29325. var serializationObject = _super.prototype.serialize.call(this);
  29326. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29327. return serializationObject;
  29328. };
  29329. return _Primitive;
  29330. }(Geometry));
  29331. Primitives._Primitive = _Primitive;
  29332. var Ribbon = (function (_super) {
  29333. __extends(Ribbon, _super);
  29334. // Members
  29335. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29336. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29337. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29338. _this.pathArray = pathArray;
  29339. _this.closeArray = closeArray;
  29340. _this.closePath = closePath;
  29341. _this.offset = offset;
  29342. _this.side = side;
  29343. return _this;
  29344. }
  29345. Ribbon.prototype._regenerateVertexData = function () {
  29346. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29347. };
  29348. Ribbon.prototype.copy = function (id) {
  29349. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29350. };
  29351. return Ribbon;
  29352. }(_Primitive));
  29353. Primitives.Ribbon = Ribbon;
  29354. var Box = (function (_super) {
  29355. __extends(Box, _super);
  29356. // Members
  29357. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29358. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29359. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29360. _this.size = size;
  29361. _this.side = side;
  29362. return _this;
  29363. }
  29364. Box.prototype._regenerateVertexData = function () {
  29365. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29366. };
  29367. Box.prototype.copy = function (id) {
  29368. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29369. };
  29370. Box.prototype.serialize = function () {
  29371. var serializationObject = _super.prototype.serialize.call(this);
  29372. serializationObject.size = this.size;
  29373. return serializationObject;
  29374. };
  29375. Box.Parse = function (parsedBox, scene) {
  29376. if (scene.getGeometryByID(parsedBox.id)) {
  29377. return null; // null since geometry could be something else than a box...
  29378. }
  29379. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29380. if (BABYLON.Tags) {
  29381. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29382. }
  29383. scene.pushGeometry(box, true);
  29384. return box;
  29385. };
  29386. return Box;
  29387. }(_Primitive));
  29388. Primitives.Box = Box;
  29389. var Sphere = (function (_super) {
  29390. __extends(Sphere, _super);
  29391. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29392. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29393. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29394. _this.segments = segments;
  29395. _this.diameter = diameter;
  29396. _this.side = side;
  29397. return _this;
  29398. }
  29399. Sphere.prototype._regenerateVertexData = function () {
  29400. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29401. };
  29402. Sphere.prototype.copy = function (id) {
  29403. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29404. };
  29405. Sphere.prototype.serialize = function () {
  29406. var serializationObject = _super.prototype.serialize.call(this);
  29407. serializationObject.segments = this.segments;
  29408. serializationObject.diameter = this.diameter;
  29409. return serializationObject;
  29410. };
  29411. Sphere.Parse = function (parsedSphere, scene) {
  29412. if (scene.getGeometryByID(parsedSphere.id)) {
  29413. return null; // null since geometry could be something else than a sphere...
  29414. }
  29415. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29416. if (BABYLON.Tags) {
  29417. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29418. }
  29419. scene.pushGeometry(sphere, true);
  29420. return sphere;
  29421. };
  29422. return Sphere;
  29423. }(_Primitive));
  29424. Primitives.Sphere = Sphere;
  29425. var Disc = (function (_super) {
  29426. __extends(Disc, _super);
  29427. // Members
  29428. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29429. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29430. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29431. _this.radius = radius;
  29432. _this.tessellation = tessellation;
  29433. _this.side = side;
  29434. return _this;
  29435. }
  29436. Disc.prototype._regenerateVertexData = function () {
  29437. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29438. };
  29439. Disc.prototype.copy = function (id) {
  29440. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29441. };
  29442. return Disc;
  29443. }(_Primitive));
  29444. Primitives.Disc = Disc;
  29445. var Cylinder = (function (_super) {
  29446. __extends(Cylinder, _super);
  29447. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29448. if (subdivisions === void 0) { subdivisions = 1; }
  29449. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29450. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29451. _this.height = height;
  29452. _this.diameterTop = diameterTop;
  29453. _this.diameterBottom = diameterBottom;
  29454. _this.tessellation = tessellation;
  29455. _this.subdivisions = subdivisions;
  29456. _this.side = side;
  29457. return _this;
  29458. }
  29459. Cylinder.prototype._regenerateVertexData = function () {
  29460. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29461. };
  29462. Cylinder.prototype.copy = function (id) {
  29463. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29464. };
  29465. Cylinder.prototype.serialize = function () {
  29466. var serializationObject = _super.prototype.serialize.call(this);
  29467. serializationObject.height = this.height;
  29468. serializationObject.diameterTop = this.diameterTop;
  29469. serializationObject.diameterBottom = this.diameterBottom;
  29470. serializationObject.tessellation = this.tessellation;
  29471. return serializationObject;
  29472. };
  29473. Cylinder.Parse = function (parsedCylinder, scene) {
  29474. if (scene.getGeometryByID(parsedCylinder.id)) {
  29475. return null; // null since geometry could be something else than a cylinder...
  29476. }
  29477. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29478. if (BABYLON.Tags) {
  29479. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29480. }
  29481. scene.pushGeometry(cylinder, true);
  29482. return cylinder;
  29483. };
  29484. return Cylinder;
  29485. }(_Primitive));
  29486. Primitives.Cylinder = Cylinder;
  29487. var Torus = (function (_super) {
  29488. __extends(Torus, _super);
  29489. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29490. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29491. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29492. _this.diameter = diameter;
  29493. _this.thickness = thickness;
  29494. _this.tessellation = tessellation;
  29495. _this.side = side;
  29496. return _this;
  29497. }
  29498. Torus.prototype._regenerateVertexData = function () {
  29499. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29500. };
  29501. Torus.prototype.copy = function (id) {
  29502. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29503. };
  29504. Torus.prototype.serialize = function () {
  29505. var serializationObject = _super.prototype.serialize.call(this);
  29506. serializationObject.diameter = this.diameter;
  29507. serializationObject.thickness = this.thickness;
  29508. serializationObject.tessellation = this.tessellation;
  29509. return serializationObject;
  29510. };
  29511. Torus.Parse = function (parsedTorus, scene) {
  29512. if (scene.getGeometryByID(parsedTorus.id)) {
  29513. return null; // null since geometry could be something else than a torus...
  29514. }
  29515. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29516. if (BABYLON.Tags) {
  29517. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29518. }
  29519. scene.pushGeometry(torus, true);
  29520. return torus;
  29521. };
  29522. return Torus;
  29523. }(_Primitive));
  29524. Primitives.Torus = Torus;
  29525. var Ground = (function (_super) {
  29526. __extends(Ground, _super);
  29527. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29528. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29529. _this.width = width;
  29530. _this.height = height;
  29531. _this.subdivisions = subdivisions;
  29532. return _this;
  29533. }
  29534. Ground.prototype._regenerateVertexData = function () {
  29535. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29536. };
  29537. Ground.prototype.copy = function (id) {
  29538. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29539. };
  29540. Ground.prototype.serialize = function () {
  29541. var serializationObject = _super.prototype.serialize.call(this);
  29542. serializationObject.width = this.width;
  29543. serializationObject.height = this.height;
  29544. serializationObject.subdivisions = this.subdivisions;
  29545. return serializationObject;
  29546. };
  29547. Ground.Parse = function (parsedGround, scene) {
  29548. if (scene.getGeometryByID(parsedGround.id)) {
  29549. return null; // null since geometry could be something else than a ground...
  29550. }
  29551. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29552. if (BABYLON.Tags) {
  29553. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29554. }
  29555. scene.pushGeometry(ground, true);
  29556. return ground;
  29557. };
  29558. return Ground;
  29559. }(_Primitive));
  29560. Primitives.Ground = Ground;
  29561. var TiledGround = (function (_super) {
  29562. __extends(TiledGround, _super);
  29563. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29564. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29565. _this.xmin = xmin;
  29566. _this.zmin = zmin;
  29567. _this.xmax = xmax;
  29568. _this.zmax = zmax;
  29569. _this.subdivisions = subdivisions;
  29570. _this.precision = precision;
  29571. return _this;
  29572. }
  29573. TiledGround.prototype._regenerateVertexData = function () {
  29574. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29575. };
  29576. TiledGround.prototype.copy = function (id) {
  29577. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29578. };
  29579. return TiledGround;
  29580. }(_Primitive));
  29581. Primitives.TiledGround = TiledGround;
  29582. var Plane = (function (_super) {
  29583. __extends(Plane, _super);
  29584. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29585. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29586. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29587. _this.size = size;
  29588. _this.side = side;
  29589. return _this;
  29590. }
  29591. Plane.prototype._regenerateVertexData = function () {
  29592. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29593. };
  29594. Plane.prototype.copy = function (id) {
  29595. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29596. };
  29597. Plane.prototype.serialize = function () {
  29598. var serializationObject = _super.prototype.serialize.call(this);
  29599. serializationObject.size = this.size;
  29600. return serializationObject;
  29601. };
  29602. Plane.Parse = function (parsedPlane, scene) {
  29603. if (scene.getGeometryByID(parsedPlane.id)) {
  29604. return null; // null since geometry could be something else than a ground...
  29605. }
  29606. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29607. if (BABYLON.Tags) {
  29608. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29609. }
  29610. scene.pushGeometry(plane, true);
  29611. return plane;
  29612. };
  29613. return Plane;
  29614. }(_Primitive));
  29615. Primitives.Plane = Plane;
  29616. var TorusKnot = (function (_super) {
  29617. __extends(TorusKnot, _super);
  29618. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29619. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29620. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29621. _this.radius = radius;
  29622. _this.tube = tube;
  29623. _this.radialSegments = radialSegments;
  29624. _this.tubularSegments = tubularSegments;
  29625. _this.p = p;
  29626. _this.q = q;
  29627. _this.side = side;
  29628. return _this;
  29629. }
  29630. TorusKnot.prototype._regenerateVertexData = function () {
  29631. 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 });
  29632. };
  29633. TorusKnot.prototype.copy = function (id) {
  29634. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29635. };
  29636. TorusKnot.prototype.serialize = function () {
  29637. var serializationObject = _super.prototype.serialize.call(this);
  29638. serializationObject.radius = this.radius;
  29639. serializationObject.tube = this.tube;
  29640. serializationObject.radialSegments = this.radialSegments;
  29641. serializationObject.tubularSegments = this.tubularSegments;
  29642. serializationObject.p = this.p;
  29643. serializationObject.q = this.q;
  29644. return serializationObject;
  29645. };
  29646. ;
  29647. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29648. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29649. return null; // null since geometry could be something else than a ground...
  29650. }
  29651. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29652. if (BABYLON.Tags) {
  29653. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29654. }
  29655. scene.pushGeometry(torusKnot, true);
  29656. return torusKnot;
  29657. };
  29658. return TorusKnot;
  29659. }(_Primitive));
  29660. Primitives.TorusKnot = TorusKnot;
  29661. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29662. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29663. })(BABYLON || (BABYLON = {}));
  29664. //# sourceMappingURL=babylon.geometry.js.map
  29665. var BABYLON;
  29666. (function (BABYLON) {
  29667. var PostProcessManager = (function () {
  29668. function PostProcessManager(scene) {
  29669. this._vertexBuffers = {};
  29670. this._scene = scene;
  29671. }
  29672. PostProcessManager.prototype._prepareBuffers = function () {
  29673. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29674. return;
  29675. }
  29676. // VBO
  29677. var vertices = [];
  29678. vertices.push(1, 1);
  29679. vertices.push(-1, 1);
  29680. vertices.push(-1, -1);
  29681. vertices.push(1, -1);
  29682. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29683. this._buildIndexBuffer();
  29684. };
  29685. PostProcessManager.prototype._buildIndexBuffer = function () {
  29686. // Indices
  29687. var indices = [];
  29688. indices.push(0);
  29689. indices.push(1);
  29690. indices.push(2);
  29691. indices.push(0);
  29692. indices.push(2);
  29693. indices.push(3);
  29694. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29695. };
  29696. PostProcessManager.prototype._rebuild = function () {
  29697. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29698. return;
  29699. }
  29700. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  29701. this._buildIndexBuffer();
  29702. };
  29703. // Methods
  29704. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29705. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29706. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29707. return false;
  29708. }
  29709. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29710. return true;
  29711. };
  29712. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29713. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29714. var engine = this._scene.getEngine();
  29715. for (var index = 0; index < postProcesses.length; index++) {
  29716. if (index < postProcesses.length - 1) {
  29717. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29718. }
  29719. else {
  29720. if (targetTexture) {
  29721. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29722. }
  29723. else {
  29724. engine.restoreDefaultFramebuffer();
  29725. }
  29726. }
  29727. var pp = postProcesses[index];
  29728. var effect = pp.apply();
  29729. if (effect) {
  29730. pp.onBeforeRenderObservable.notifyObservers(effect);
  29731. // VBOs
  29732. this._prepareBuffers();
  29733. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29734. // Draw order
  29735. engine.draw(true, 0, 6);
  29736. pp.onAfterRenderObservable.notifyObservers(effect);
  29737. }
  29738. }
  29739. // Restore depth buffer
  29740. engine.setDepthBuffer(true);
  29741. engine.setDepthWrite(true);
  29742. };
  29743. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29744. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29745. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29746. return;
  29747. }
  29748. var engine = this._scene.getEngine();
  29749. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29750. if (index < len - 1) {
  29751. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29752. }
  29753. else {
  29754. if (targetTexture) {
  29755. engine.bindFramebuffer(targetTexture, faceIndex);
  29756. }
  29757. else {
  29758. engine.restoreDefaultFramebuffer();
  29759. }
  29760. }
  29761. if (doNotPresent) {
  29762. break;
  29763. }
  29764. var pp = postProcesses[index];
  29765. var effect = pp.apply();
  29766. if (effect) {
  29767. pp.onBeforeRenderObservable.notifyObservers(effect);
  29768. // VBOs
  29769. this._prepareBuffers();
  29770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29771. // Draw order
  29772. engine.draw(true, 0, 6);
  29773. pp.onAfterRenderObservable.notifyObservers(effect);
  29774. }
  29775. }
  29776. // Restore states
  29777. engine.setDepthBuffer(true);
  29778. engine.setDepthWrite(true);
  29779. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29780. };
  29781. PostProcessManager.prototype.dispose = function () {
  29782. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29783. if (buffer) {
  29784. buffer.dispose();
  29785. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29786. }
  29787. if (this._indexBuffer) {
  29788. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29789. this._indexBuffer = null;
  29790. }
  29791. };
  29792. return PostProcessManager;
  29793. }());
  29794. BABYLON.PostProcessManager = PostProcessManager;
  29795. })(BABYLON || (BABYLON = {}));
  29796. //# sourceMappingURL=babylon.postProcessManager.js.map
  29797. var BABYLON;
  29798. (function (BABYLON) {
  29799. /**
  29800. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29801. */
  29802. var PerformanceMonitor = (function () {
  29803. /**
  29804. * constructor
  29805. * @param frameSampleSize The number of samples required to saturate the sliding window
  29806. */
  29807. function PerformanceMonitor(frameSampleSize) {
  29808. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29809. this._enabled = true;
  29810. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29811. }
  29812. /**
  29813. * Samples current frame
  29814. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29815. */
  29816. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29817. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29818. if (!this._enabled)
  29819. return;
  29820. if (this._lastFrameTimeMs != null) {
  29821. var dt = timeMs - this._lastFrameTimeMs;
  29822. this._rollingFrameTime.add(dt);
  29823. }
  29824. this._lastFrameTimeMs = timeMs;
  29825. };
  29826. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29827. /**
  29828. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29829. * @return Average frame time in milliseconds
  29830. */
  29831. get: function () {
  29832. return this._rollingFrameTime.average;
  29833. },
  29834. enumerable: true,
  29835. configurable: true
  29836. });
  29837. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29838. /**
  29839. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29840. * @return Frame time variance in milliseconds squared
  29841. */
  29842. get: function () {
  29843. return this._rollingFrameTime.variance;
  29844. },
  29845. enumerable: true,
  29846. configurable: true
  29847. });
  29848. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29849. /**
  29850. * Returns the frame time of the most recent frame
  29851. * @return Frame time in milliseconds
  29852. */
  29853. get: function () {
  29854. return this._rollingFrameTime.history(0);
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29860. /**
  29861. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29862. * @return Framerate in frames per second
  29863. */
  29864. get: function () {
  29865. return 1000.0 / this._rollingFrameTime.average;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29871. /**
  29872. * Returns the average framerate in frames per second using the most recent frame time
  29873. * @return Framerate in frames per second
  29874. */
  29875. get: function () {
  29876. return 1000.0 / this._rollingFrameTime.history(0);
  29877. },
  29878. enumerable: true,
  29879. configurable: true
  29880. });
  29881. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29882. /**
  29883. * Returns true if enough samples have been taken to completely fill the sliding window
  29884. * @return true if saturated
  29885. */
  29886. get: function () {
  29887. return this._rollingFrameTime.isSaturated();
  29888. },
  29889. enumerable: true,
  29890. configurable: true
  29891. });
  29892. /**
  29893. * Enables contributions to the sliding window sample set
  29894. */
  29895. PerformanceMonitor.prototype.enable = function () {
  29896. this._enabled = true;
  29897. };
  29898. /**
  29899. * Disables contributions to the sliding window sample set
  29900. * Samples will not be interpolated over the disabled period
  29901. */
  29902. PerformanceMonitor.prototype.disable = function () {
  29903. this._enabled = false;
  29904. //clear last sample to avoid interpolating over the disabled period when next enabled
  29905. this._lastFrameTimeMs = null;
  29906. this._lastChangeTimeMs = null;
  29907. };
  29908. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29909. /**
  29910. * Returns true if sampling is enabled
  29911. * @return true if enabled
  29912. */
  29913. get: function () {
  29914. return this._enabled;
  29915. },
  29916. enumerable: true,
  29917. configurable: true
  29918. });
  29919. /**
  29920. * Resets performance monitor
  29921. */
  29922. PerformanceMonitor.prototype.reset = function () {
  29923. //clear last sample to avoid interpolating over the disabled period when next enabled
  29924. this._lastFrameTimeMs = null;
  29925. this._lastChangeTimeMs = null;
  29926. //wipe record
  29927. this._rollingFrameTime.reset();
  29928. };
  29929. return PerformanceMonitor;
  29930. }());
  29931. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29932. /**
  29933. * RollingAverage
  29934. *
  29935. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29936. */
  29937. var RollingAverage = (function () {
  29938. /**
  29939. * constructor
  29940. * @param length The number of samples required to saturate the sliding window
  29941. */
  29942. function RollingAverage(length) {
  29943. this._samples = new Array(length);
  29944. this.reset();
  29945. }
  29946. /**
  29947. * Adds a sample to the sample set
  29948. * @param v The sample value
  29949. */
  29950. RollingAverage.prototype.add = function (v) {
  29951. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29952. var delta;
  29953. //we need to check if we've already wrapped round
  29954. if (this.isSaturated()) {
  29955. //remove bottom of stack from mean
  29956. var bottomValue = this._samples[this._pos];
  29957. delta = bottomValue - this.average;
  29958. this.average -= delta / (this._sampleCount - 1);
  29959. this._m2 -= delta * (bottomValue - this.average);
  29960. }
  29961. else {
  29962. this._sampleCount++;
  29963. }
  29964. //add new value to mean
  29965. delta = v - this.average;
  29966. this.average += delta / (this._sampleCount);
  29967. this._m2 += delta * (v - this.average);
  29968. //set the new variance
  29969. this.variance = this._m2 / (this._sampleCount - 1);
  29970. this._samples[this._pos] = v;
  29971. this._pos++;
  29972. this._pos %= this._samples.length; //positive wrap around
  29973. };
  29974. /**
  29975. * Returns previously added values or null if outside of history or outside the sliding window domain
  29976. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  29977. * @return Value previously recorded with add() or null if outside of range
  29978. */
  29979. RollingAverage.prototype.history = function (i) {
  29980. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  29981. return null;
  29982. }
  29983. var i0 = this._wrapPosition(this._pos - 1.0);
  29984. return this._samples[this._wrapPosition(i0 - i)];
  29985. };
  29986. /**
  29987. * Returns true if enough samples have been taken to completely fill the sliding window
  29988. * @return true if sample-set saturated
  29989. */
  29990. RollingAverage.prototype.isSaturated = function () {
  29991. return this._sampleCount >= this._samples.length;
  29992. };
  29993. /**
  29994. * Resets the rolling average (equivalent to 0 samples taken so far)
  29995. */
  29996. RollingAverage.prototype.reset = function () {
  29997. this.average = 0;
  29998. this.variance = 0;
  29999. this._sampleCount = 0;
  30000. this._pos = 0;
  30001. this._m2 = 0;
  30002. };
  30003. /**
  30004. * Wraps a value around the sample range boundaries
  30005. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30006. * @return Wrapped position in sample range
  30007. */
  30008. RollingAverage.prototype._wrapPosition = function (i) {
  30009. var max = this._samples.length;
  30010. return ((i % max) + max) % max;
  30011. };
  30012. return RollingAverage;
  30013. }());
  30014. BABYLON.RollingAverage = RollingAverage;
  30015. })(BABYLON || (BABYLON = {}));
  30016. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30017. var BABYLON;
  30018. (function (BABYLON) {
  30019. var StandardMaterialDefines = (function (_super) {
  30020. __extends(StandardMaterialDefines, _super);
  30021. function StandardMaterialDefines() {
  30022. var _this = _super.call(this) || this;
  30023. _this.MAINUV1 = false;
  30024. _this.MAINUV2 = false;
  30025. _this.DIFFUSE = false;
  30026. _this.DIFFUSEDIRECTUV = 0;
  30027. _this.AMBIENT = false;
  30028. _this.AMBIENTDIRECTUV = 0;
  30029. _this.OPACITY = false;
  30030. _this.OPACITYDIRECTUV = 0;
  30031. _this.OPACITYRGB = false;
  30032. _this.REFLECTION = false;
  30033. _this.EMISSIVE = false;
  30034. _this.EMISSIVEDIRECTUV = 0;
  30035. _this.SPECULAR = false;
  30036. _this.SPECULARDIRECTUV = 0;
  30037. _this.BUMP = false;
  30038. _this.BUMPDIRECTUV = 0;
  30039. _this.PARALLAX = false;
  30040. _this.PARALLAXOCCLUSION = false;
  30041. _this.SPECULAROVERALPHA = false;
  30042. _this.CLIPPLANE = false;
  30043. _this.ALPHATEST = false;
  30044. _this.ALPHAFROMDIFFUSE = false;
  30045. _this.POINTSIZE = false;
  30046. _this.FOG = false;
  30047. _this.SPECULARTERM = false;
  30048. _this.DIFFUSEFRESNEL = false;
  30049. _this.OPACITYFRESNEL = false;
  30050. _this.REFLECTIONFRESNEL = false;
  30051. _this.REFRACTIONFRESNEL = false;
  30052. _this.EMISSIVEFRESNEL = false;
  30053. _this.FRESNEL = false;
  30054. _this.NORMAL = false;
  30055. _this.UV1 = false;
  30056. _this.UV2 = false;
  30057. _this.VERTEXCOLOR = false;
  30058. _this.VERTEXALPHA = false;
  30059. _this.NUM_BONE_INFLUENCERS = 0;
  30060. _this.BonesPerMesh = 0;
  30061. _this.INSTANCES = false;
  30062. _this.GLOSSINESS = false;
  30063. _this.ROUGHNESS = false;
  30064. _this.EMISSIVEASILLUMINATION = false;
  30065. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30066. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30067. _this.LIGHTMAP = false;
  30068. _this.LIGHTMAPDIRECTUV = 0;
  30069. _this.USELIGHTMAPASSHADOWMAP = false;
  30070. _this.REFLECTIONMAP_3D = false;
  30071. _this.REFLECTIONMAP_SPHERICAL = false;
  30072. _this.REFLECTIONMAP_PLANAR = false;
  30073. _this.REFLECTIONMAP_CUBIC = false;
  30074. _this.REFLECTIONMAP_PROJECTION = false;
  30075. _this.REFLECTIONMAP_SKYBOX = false;
  30076. _this.REFLECTIONMAP_EXPLICIT = false;
  30077. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30078. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30079. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30080. _this.INVERTCUBICMAP = false;
  30081. _this.LOGARITHMICDEPTH = false;
  30082. _this.REFRACTION = false;
  30083. _this.REFRACTIONMAP_3D = false;
  30084. _this.REFLECTIONOVERALPHA = false;
  30085. _this.TWOSIDEDLIGHTING = false;
  30086. _this.SHADOWFLOAT = false;
  30087. _this.MORPHTARGETS = false;
  30088. _this.MORPHTARGETS_NORMAL = false;
  30089. _this.MORPHTARGETS_TANGENT = false;
  30090. _this.NUM_MORPH_INFLUENCERS = 0;
  30091. _this.USERIGHTHANDEDSYSTEM = false;
  30092. _this.IMAGEPROCESSING = false;
  30093. _this.VIGNETTE = false;
  30094. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30095. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30096. _this.TONEMAPPING = false;
  30097. _this.CONTRAST = false;
  30098. _this.COLORCURVES = false;
  30099. _this.COLORGRADING = false;
  30100. _this.SAMPLER3DGREENDEPTH = false;
  30101. _this.SAMPLER3DBGRMAP = false;
  30102. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30103. _this.EXPOSURE = false;
  30104. _this.rebuild();
  30105. return _this;
  30106. }
  30107. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30108. var modes = [
  30109. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30110. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30111. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30112. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30113. ];
  30114. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30115. var mode = modes_1[_i];
  30116. this[mode] = (mode === modeToEnable);
  30117. }
  30118. };
  30119. return StandardMaterialDefines;
  30120. }(BABYLON.MaterialDefines));
  30121. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30122. var StandardMaterial = (function (_super) {
  30123. __extends(StandardMaterial, _super);
  30124. function StandardMaterial(name, scene) {
  30125. var _this = _super.call(this, name, scene) || this;
  30126. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30127. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30128. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30129. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30130. _this.specularPower = 64;
  30131. _this._useAlphaFromDiffuseTexture = false;
  30132. _this._useEmissiveAsIllumination = false;
  30133. _this._linkEmissiveWithDiffuse = false;
  30134. _this._useSpecularOverAlpha = false;
  30135. _this._useReflectionOverAlpha = false;
  30136. _this._disableLighting = false;
  30137. _this._useParallax = false;
  30138. _this._useParallaxOcclusion = false;
  30139. _this.parallaxScaleBias = 0.05;
  30140. _this._roughness = 0;
  30141. _this.indexOfRefraction = 0.98;
  30142. _this.invertRefractionY = true;
  30143. _this._useLightmapAsShadowmap = false;
  30144. _this._useReflectionFresnelFromSpecular = false;
  30145. _this._useGlossinessFromSpecularMapAlpha = false;
  30146. _this._maxSimultaneousLights = 4;
  30147. /**
  30148. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30149. */
  30150. _this._invertNormalMapX = false;
  30151. /**
  30152. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30153. */
  30154. _this._invertNormalMapY = false;
  30155. /**
  30156. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30157. */
  30158. _this._twoSidedLighting = false;
  30159. _this._renderTargets = new BABYLON.SmartArray(16);
  30160. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30161. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30162. // Setup the default processing configuration to the scene.
  30163. _this._attachImageProcessingConfiguration(null);
  30164. _this.getRenderTargetTextures = function () {
  30165. _this._renderTargets.reset();
  30166. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30167. _this._renderTargets.push(_this._reflectionTexture);
  30168. }
  30169. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30170. _this._renderTargets.push(_this._refractionTexture);
  30171. }
  30172. return _this._renderTargets;
  30173. };
  30174. return _this;
  30175. }
  30176. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30177. /**
  30178. * Gets the image processing configuration used either in this material.
  30179. */
  30180. get: function () {
  30181. return this._imageProcessingConfiguration;
  30182. },
  30183. /**
  30184. * Sets the Default image processing configuration used either in the this material.
  30185. *
  30186. * If sets to null, the scene one is in use.
  30187. */
  30188. set: function (value) {
  30189. this._attachImageProcessingConfiguration(value);
  30190. // Ensure the effect will be rebuilt.
  30191. this._markAllSubMeshesAsTexturesDirty();
  30192. },
  30193. enumerable: true,
  30194. configurable: true
  30195. });
  30196. /**
  30197. * Attaches a new image processing configuration to the Standard Material.
  30198. * @param configuration
  30199. */
  30200. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30201. var _this = this;
  30202. if (configuration === this._imageProcessingConfiguration) {
  30203. return;
  30204. }
  30205. // Detaches observer.
  30206. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30207. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30208. }
  30209. // Pick the scene configuration if needed.
  30210. if (!configuration) {
  30211. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30212. }
  30213. else {
  30214. this._imageProcessingConfiguration = configuration;
  30215. }
  30216. // Attaches observer.
  30217. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30218. _this._markAllSubMeshesAsImageProcessingDirty();
  30219. });
  30220. };
  30221. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30222. /**
  30223. * Gets wether the color curves effect is enabled.
  30224. */
  30225. get: function () {
  30226. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30227. },
  30228. /**
  30229. * Sets wether the color curves effect is enabled.
  30230. */
  30231. set: function (value) {
  30232. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30233. },
  30234. enumerable: true,
  30235. configurable: true
  30236. });
  30237. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30238. /**
  30239. * Gets wether the color grading effect is enabled.
  30240. */
  30241. get: function () {
  30242. return this.imageProcessingConfiguration.colorGradingEnabled;
  30243. },
  30244. /**
  30245. * Gets wether the color grading effect is enabled.
  30246. */
  30247. set: function (value) {
  30248. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30249. },
  30250. enumerable: true,
  30251. configurable: true
  30252. });
  30253. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30254. /**
  30255. * Gets wether tonemapping is enabled or not.
  30256. */
  30257. get: function () {
  30258. return this._imageProcessingConfiguration.toneMappingEnabled;
  30259. },
  30260. /**
  30261. * Sets wether tonemapping is enabled or not
  30262. */
  30263. set: function (value) {
  30264. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30265. },
  30266. enumerable: true,
  30267. configurable: true
  30268. });
  30269. ;
  30270. ;
  30271. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30272. /**
  30273. * The camera exposure used on this material.
  30274. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30275. * This corresponds to a photographic exposure.
  30276. */
  30277. get: function () {
  30278. return this._imageProcessingConfiguration.exposure;
  30279. },
  30280. /**
  30281. * The camera exposure used on this material.
  30282. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30283. * This corresponds to a photographic exposure.
  30284. */
  30285. set: function (value) {
  30286. this._imageProcessingConfiguration.exposure = value;
  30287. },
  30288. enumerable: true,
  30289. configurable: true
  30290. });
  30291. ;
  30292. ;
  30293. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30294. /**
  30295. * Gets The camera contrast used on this material.
  30296. */
  30297. get: function () {
  30298. return this._imageProcessingConfiguration.contrast;
  30299. },
  30300. /**
  30301. * Sets The camera contrast used on this material.
  30302. */
  30303. set: function (value) {
  30304. this._imageProcessingConfiguration.contrast = value;
  30305. },
  30306. enumerable: true,
  30307. configurable: true
  30308. });
  30309. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30310. /**
  30311. * Gets the Color Grading 2D Lookup Texture.
  30312. */
  30313. get: function () {
  30314. return this._imageProcessingConfiguration.colorGradingTexture;
  30315. },
  30316. /**
  30317. * Sets the Color Grading 2D Lookup Texture.
  30318. */
  30319. set: function (value) {
  30320. this._imageProcessingConfiguration.colorGradingTexture = value;
  30321. },
  30322. enumerable: true,
  30323. configurable: true
  30324. });
  30325. StandardMaterial.prototype.getClassName = function () {
  30326. return "StandardMaterial";
  30327. };
  30328. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30329. get: function () {
  30330. return this._useLogarithmicDepth;
  30331. },
  30332. set: function (value) {
  30333. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30334. this._markAllSubMeshesAsMiscDirty();
  30335. },
  30336. enumerable: true,
  30337. configurable: true
  30338. });
  30339. StandardMaterial.prototype.needAlphaBlending = function () {
  30340. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30341. };
  30342. StandardMaterial.prototype.needAlphaTesting = function () {
  30343. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30344. };
  30345. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30346. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30347. };
  30348. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30349. return this._diffuseTexture;
  30350. };
  30351. /**
  30352. * Child classes can use it to update shaders
  30353. */
  30354. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30355. if (this.isFrozen) {
  30356. if (this._wasPreviouslyReady && subMesh.effect) {
  30357. return true;
  30358. }
  30359. }
  30360. if (!subMesh._materialDefines) {
  30361. subMesh._materialDefines = new StandardMaterialDefines();
  30362. }
  30363. var scene = this.getScene();
  30364. var defines = subMesh._materialDefines;
  30365. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30366. if (defines._renderId === scene.getRenderId()) {
  30367. return true;
  30368. }
  30369. }
  30370. var engine = scene.getEngine();
  30371. // Lights
  30372. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30373. // Textures
  30374. if (defines._areTexturesDirty) {
  30375. defines._needUVs = false;
  30376. defines.MAINUV1 = false;
  30377. defines.MAINUV2 = false;
  30378. if (scene.texturesEnabled) {
  30379. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30380. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30381. return false;
  30382. }
  30383. else {
  30384. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30385. }
  30386. }
  30387. else {
  30388. defines.DIFFUSE = false;
  30389. }
  30390. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30391. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30392. return false;
  30393. }
  30394. else {
  30395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30396. }
  30397. }
  30398. else {
  30399. defines.AMBIENT = false;
  30400. }
  30401. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30402. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30403. return false;
  30404. }
  30405. else {
  30406. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30407. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30408. }
  30409. }
  30410. else {
  30411. defines.OPACITY = false;
  30412. }
  30413. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30414. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30415. return false;
  30416. }
  30417. else {
  30418. defines._needNormals = true;
  30419. defines.REFLECTION = true;
  30420. defines.ROUGHNESS = (this._roughness > 0);
  30421. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30422. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30423. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30424. switch (this._reflectionTexture.coordinatesMode) {
  30425. case BABYLON.Texture.CUBIC_MODE:
  30426. case BABYLON.Texture.INVCUBIC_MODE:
  30427. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30428. break;
  30429. case BABYLON.Texture.EXPLICIT_MODE:
  30430. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30431. break;
  30432. case BABYLON.Texture.PLANAR_MODE:
  30433. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30434. break;
  30435. case BABYLON.Texture.PROJECTION_MODE:
  30436. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30437. break;
  30438. case BABYLON.Texture.SKYBOX_MODE:
  30439. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30440. break;
  30441. case BABYLON.Texture.SPHERICAL_MODE:
  30442. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30443. break;
  30444. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30445. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30446. break;
  30447. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30448. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30449. break;
  30450. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30451. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30452. break;
  30453. }
  30454. }
  30455. }
  30456. else {
  30457. defines.REFLECTION = false;
  30458. }
  30459. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30460. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30461. return false;
  30462. }
  30463. else {
  30464. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30465. }
  30466. }
  30467. else {
  30468. defines.EMISSIVE = false;
  30469. }
  30470. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30471. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30472. return false;
  30473. }
  30474. else {
  30475. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30476. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30477. }
  30478. }
  30479. else {
  30480. defines.LIGHTMAP = false;
  30481. }
  30482. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30483. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30484. return false;
  30485. }
  30486. else {
  30487. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30488. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30489. }
  30490. }
  30491. else {
  30492. defines.SPECULAR = false;
  30493. }
  30494. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30495. // Bump texure can not be not blocking.
  30496. if (!this._bumpTexture.isReady()) {
  30497. return false;
  30498. }
  30499. else {
  30500. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30501. defines.PARALLAX = this._useParallax;
  30502. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30503. }
  30504. }
  30505. else {
  30506. defines.BUMP = false;
  30507. }
  30508. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30509. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30510. return false;
  30511. }
  30512. else {
  30513. defines._needUVs = true;
  30514. defines.REFRACTION = true;
  30515. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30516. }
  30517. }
  30518. else {
  30519. defines.REFRACTION = false;
  30520. }
  30521. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30522. }
  30523. else {
  30524. defines.DIFFUSE = false;
  30525. defines.AMBIENT = false;
  30526. defines.OPACITY = false;
  30527. defines.REFLECTION = false;
  30528. defines.EMISSIVE = false;
  30529. defines.LIGHTMAP = false;
  30530. defines.BUMP = false;
  30531. defines.REFRACTION = false;
  30532. }
  30533. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30534. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30535. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30536. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30537. }
  30538. if (defines._areImageProcessingDirty) {
  30539. if (!this._imageProcessingConfiguration.isReady()) {
  30540. return false;
  30541. }
  30542. this._imageProcessingConfiguration.prepareDefines(defines);
  30543. }
  30544. if (defines._areFresnelDirty) {
  30545. if (StandardMaterial.FresnelEnabled) {
  30546. // Fresnel
  30547. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  30548. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  30549. this._reflectionFresnelParameters) {
  30550. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  30551. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  30552. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  30553. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  30554. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  30555. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  30556. defines._needNormals = true;
  30557. defines.FRESNEL = true;
  30558. }
  30559. }
  30560. else {
  30561. defines.FRESNEL = false;
  30562. }
  30563. }
  30564. // Misc.
  30565. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30566. // Attribs
  30567. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  30568. // Values that need to be evaluated on every frame
  30569. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  30570. // Get correct effect
  30571. if (defines.isDirty) {
  30572. defines.markAsProcessed();
  30573. scene.resetCachedMaterial();
  30574. // Fallbacks
  30575. var fallbacks = new BABYLON.EffectFallbacks();
  30576. if (defines.REFLECTION) {
  30577. fallbacks.addFallback(0, "REFLECTION");
  30578. }
  30579. if (defines.SPECULAR) {
  30580. fallbacks.addFallback(0, "SPECULAR");
  30581. }
  30582. if (defines.BUMP) {
  30583. fallbacks.addFallback(0, "BUMP");
  30584. }
  30585. if (defines.PARALLAX) {
  30586. fallbacks.addFallback(1, "PARALLAX");
  30587. }
  30588. if (defines.PARALLAXOCCLUSION) {
  30589. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30590. }
  30591. if (defines.SPECULAROVERALPHA) {
  30592. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30593. }
  30594. if (defines.FOG) {
  30595. fallbacks.addFallback(1, "FOG");
  30596. }
  30597. if (defines.POINTSIZE) {
  30598. fallbacks.addFallback(0, "POINTSIZE");
  30599. }
  30600. if (defines.LOGARITHMICDEPTH) {
  30601. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30602. }
  30603. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30604. if (defines.SPECULARTERM) {
  30605. fallbacks.addFallback(0, "SPECULARTERM");
  30606. }
  30607. if (defines.DIFFUSEFRESNEL) {
  30608. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30609. }
  30610. if (defines.OPACITYFRESNEL) {
  30611. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30612. }
  30613. if (defines.REFLECTIONFRESNEL) {
  30614. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30615. }
  30616. if (defines.EMISSIVEFRESNEL) {
  30617. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30618. }
  30619. if (defines.FRESNEL) {
  30620. fallbacks.addFallback(4, "FRESNEL");
  30621. }
  30622. //Attributes
  30623. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30624. if (defines.NORMAL) {
  30625. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30626. }
  30627. if (defines.UV1) {
  30628. attribs.push(BABYLON.VertexBuffer.UVKind);
  30629. }
  30630. if (defines.UV2) {
  30631. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30632. }
  30633. if (defines.VERTEXCOLOR) {
  30634. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30635. }
  30636. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30637. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30638. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30639. var shaderName = "default";
  30640. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30641. "vFogInfos", "vFogColor", "pointSize",
  30642. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30643. "mBones",
  30644. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30645. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30646. "logarithmicDepthConstant", "vNormalReoderParams"
  30647. ];
  30648. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30649. var uniformBuffers = ["Material", "Scene"];
  30650. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30651. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30652. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30653. uniformsNames: uniforms,
  30654. uniformBuffersNames: uniformBuffers,
  30655. samplers: samplers,
  30656. defines: defines,
  30657. maxSimultaneousLights: this._maxSimultaneousLights
  30658. });
  30659. if (this.customShaderNameResolve) {
  30660. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  30661. }
  30662. var join = defines.toString();
  30663. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  30664. attributes: attribs,
  30665. uniformsNames: uniforms,
  30666. uniformBuffersNames: uniformBuffers,
  30667. samplers: samplers,
  30668. defines: join,
  30669. fallbacks: fallbacks,
  30670. onCompiled: this.onCompiled,
  30671. onError: this.onError,
  30672. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  30673. }, engine), defines);
  30674. this.buildUniformLayout();
  30675. }
  30676. if (!subMesh.effect.isReady()) {
  30677. return false;
  30678. }
  30679. defines._renderId = scene.getRenderId();
  30680. this._wasPreviouslyReady = true;
  30681. return true;
  30682. };
  30683. StandardMaterial.prototype.buildUniformLayout = function () {
  30684. // Order is important !
  30685. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  30686. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  30687. this._uniformBuffer.addUniform("opacityParts", 4);
  30688. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  30689. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  30690. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  30691. this._uniformBuffer.addUniform("refractionRightColor", 4);
  30692. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30693. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30694. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  30695. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  30696. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30697. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30698. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30699. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30700. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  30701. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30702. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  30703. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30704. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30705. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30706. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30707. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30708. this._uniformBuffer.addUniform("specularMatrix", 16);
  30709. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30710. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  30711. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30712. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30713. this._uniformBuffer.addUniform("vSpecularColor", 4);
  30714. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30715. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  30716. this._uniformBuffer.addUniform("pointSize", 1);
  30717. this._uniformBuffer.create();
  30718. };
  30719. StandardMaterial.prototype.unbind = function () {
  30720. if (this._activeEffect) {
  30721. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30722. this._activeEffect.setTexture("reflection2DSampler", null);
  30723. }
  30724. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30725. this._activeEffect.setTexture("refraction2DSampler", null);
  30726. }
  30727. }
  30728. _super.prototype.unbind.call(this);
  30729. };
  30730. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30731. var scene = this.getScene();
  30732. var defines = subMesh._materialDefines;
  30733. if (!defines) {
  30734. return;
  30735. }
  30736. var effect = subMesh.effect;
  30737. this._activeEffect = effect;
  30738. // Matrices
  30739. this.bindOnlyWorldMatrix(world);
  30740. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  30741. // Bones
  30742. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  30743. if (mustRebind) {
  30744. this._uniformBuffer.bindToEffect(effect, "Material");
  30745. this.bindViewProjection(effect);
  30746. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30747. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  30748. // Fresnel
  30749. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30750. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30751. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30752. }
  30753. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30754. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30755. }
  30756. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30757. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30758. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30759. }
  30760. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30761. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30762. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30763. }
  30764. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30765. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30766. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30767. }
  30768. }
  30769. // Textures
  30770. if (scene.texturesEnabled) {
  30771. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30772. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  30773. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  30774. }
  30775. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30776. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  30777. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  30778. }
  30779. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30780. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30781. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  30782. }
  30783. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30784. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  30785. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  30786. }
  30787. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30788. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30789. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  30790. }
  30791. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30792. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30793. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  30794. }
  30795. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30796. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  30797. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  30798. }
  30799. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30800. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  30801. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  30802. if (scene._mirroredCameraPosition) {
  30803. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 0 : 1.0, this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 0 : 1.0, this.invertNormalMapY ? 1.0 : -1.0);
  30804. }
  30805. else {
  30806. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 1.0 : 0, this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? 1.0 : 0, this.invertNormalMapY ? -1.0 : 1.0);
  30807. }
  30808. }
  30809. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30810. var depth = 1.0;
  30811. if (!this._refractionTexture.isCube) {
  30812. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30813. if (this._refractionTexture.depth) {
  30814. depth = this._refractionTexture.depth;
  30815. }
  30816. }
  30817. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30818. }
  30819. }
  30820. // Point size
  30821. if (this.pointsCloud) {
  30822. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30823. }
  30824. if (defines.SPECULARTERM) {
  30825. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  30826. }
  30827. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  30828. // Diffuse
  30829. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30830. }
  30831. // Textures
  30832. if (scene.texturesEnabled) {
  30833. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30834. effect.setTexture("diffuseSampler", this._diffuseTexture);
  30835. }
  30836. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30837. effect.setTexture("ambientSampler", this._ambientTexture);
  30838. }
  30839. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30840. effect.setTexture("opacitySampler", this._opacityTexture);
  30841. }
  30842. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30843. if (this._reflectionTexture.isCube) {
  30844. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  30845. }
  30846. else {
  30847. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  30848. }
  30849. }
  30850. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30851. effect.setTexture("emissiveSampler", this._emissiveTexture);
  30852. }
  30853. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30854. effect.setTexture("lightmapSampler", this._lightmapTexture);
  30855. }
  30856. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30857. effect.setTexture("specularSampler", this._specularTexture);
  30858. }
  30859. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30860. effect.setTexture("bumpSampler", this._bumpTexture);
  30861. }
  30862. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30863. var depth = 1.0;
  30864. if (this._refractionTexture.isCube) {
  30865. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  30866. }
  30867. else {
  30868. effect.setTexture("refraction2DSampler", this._refractionTexture);
  30869. }
  30870. }
  30871. }
  30872. // Clip plane
  30873. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  30874. // Colors
  30875. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30876. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  30877. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30878. }
  30879. if (mustRebind || !this.isFrozen) {
  30880. // Lights
  30881. if (scene.lightsEnabled && !this._disableLighting) {
  30882. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  30883. }
  30884. // View
  30885. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  30886. this.bindView(effect);
  30887. }
  30888. // Fog
  30889. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  30890. // Morph targets
  30891. if (defines.NUM_MORPH_INFLUENCERS) {
  30892. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  30893. }
  30894. // Log. depth
  30895. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  30896. // image processing
  30897. this._imageProcessingConfiguration.bind(this._activeEffect);
  30898. }
  30899. this._uniformBuffer.update();
  30900. this._afterBind(mesh, this._activeEffect);
  30901. };
  30902. StandardMaterial.prototype.getAnimatables = function () {
  30903. var results = [];
  30904. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  30905. results.push(this._diffuseTexture);
  30906. }
  30907. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30908. results.push(this._ambientTexture);
  30909. }
  30910. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30911. results.push(this._opacityTexture);
  30912. }
  30913. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30914. results.push(this._reflectionTexture);
  30915. }
  30916. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30917. results.push(this._emissiveTexture);
  30918. }
  30919. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  30920. results.push(this._specularTexture);
  30921. }
  30922. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30923. results.push(this._bumpTexture);
  30924. }
  30925. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30926. results.push(this._lightmapTexture);
  30927. }
  30928. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30929. results.push(this._refractionTexture);
  30930. }
  30931. return results;
  30932. };
  30933. StandardMaterial.prototype.getActiveTextures = function () {
  30934. var activeTextures = _super.prototype.getActiveTextures.call(this);
  30935. if (this._diffuseTexture) {
  30936. activeTextures.push(this._diffuseTexture);
  30937. }
  30938. if (this._ambientTexture) {
  30939. activeTextures.push(this._ambientTexture);
  30940. }
  30941. if (this._opacityTexture) {
  30942. activeTextures.push(this._opacityTexture);
  30943. }
  30944. if (this._reflectionTexture) {
  30945. activeTextures.push(this._reflectionTexture);
  30946. }
  30947. if (this._emissiveTexture) {
  30948. activeTextures.push(this._emissiveTexture);
  30949. }
  30950. if (this._specularTexture) {
  30951. activeTextures.push(this._specularTexture);
  30952. }
  30953. if (this._bumpTexture) {
  30954. activeTextures.push(this._bumpTexture);
  30955. }
  30956. if (this._lightmapTexture) {
  30957. activeTextures.push(this._lightmapTexture);
  30958. }
  30959. if (this._refractionTexture) {
  30960. activeTextures.push(this._refractionTexture);
  30961. }
  30962. return activeTextures;
  30963. };
  30964. StandardMaterial.prototype.hasTexture = function (texture) {
  30965. if (_super.prototype.hasTexture.call(this, texture)) {
  30966. return true;
  30967. }
  30968. if (this._diffuseTexture === texture) {
  30969. return true;
  30970. }
  30971. if (this._ambientTexture === texture) {
  30972. return true;
  30973. }
  30974. if (this._opacityTexture === texture) {
  30975. return true;
  30976. }
  30977. if (this._reflectionTexture === texture) {
  30978. return true;
  30979. }
  30980. if (this._emissiveTexture === texture) {
  30981. return true;
  30982. }
  30983. if (this._specularTexture === texture) {
  30984. return true;
  30985. }
  30986. if (this._bumpTexture === texture) {
  30987. return true;
  30988. }
  30989. if (this._lightmapTexture === texture) {
  30990. return true;
  30991. }
  30992. if (this._refractionTexture === texture) {
  30993. return true;
  30994. }
  30995. return false;
  30996. };
  30997. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30998. if (forceDisposeTextures) {
  30999. if (this._diffuseTexture) {
  31000. this._diffuseTexture.dispose();
  31001. }
  31002. if (this._ambientTexture) {
  31003. this._ambientTexture.dispose();
  31004. }
  31005. if (this._opacityTexture) {
  31006. this._opacityTexture.dispose();
  31007. }
  31008. if (this._reflectionTexture) {
  31009. this._reflectionTexture.dispose();
  31010. }
  31011. if (this._emissiveTexture) {
  31012. this._emissiveTexture.dispose();
  31013. }
  31014. if (this._specularTexture) {
  31015. this._specularTexture.dispose();
  31016. }
  31017. if (this._bumpTexture) {
  31018. this._bumpTexture.dispose();
  31019. }
  31020. if (this._lightmapTexture) {
  31021. this._lightmapTexture.dispose();
  31022. }
  31023. if (this._refractionTexture) {
  31024. this._refractionTexture.dispose();
  31025. }
  31026. }
  31027. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31028. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31029. }
  31030. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31031. };
  31032. StandardMaterial.prototype.clone = function (name) {
  31033. var _this = this;
  31034. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31035. result.name = name;
  31036. result.id = name;
  31037. return result;
  31038. };
  31039. StandardMaterial.prototype.serialize = function () {
  31040. return BABYLON.SerializationHelper.Serialize(this);
  31041. };
  31042. // Statics
  31043. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31044. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31045. };
  31046. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31047. get: function () {
  31048. return StandardMaterial._DiffuseTextureEnabled;
  31049. },
  31050. set: function (value) {
  31051. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31052. return;
  31053. }
  31054. StandardMaterial._DiffuseTextureEnabled = value;
  31055. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31056. },
  31057. enumerable: true,
  31058. configurable: true
  31059. });
  31060. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31061. get: function () {
  31062. return StandardMaterial._AmbientTextureEnabled;
  31063. },
  31064. set: function (value) {
  31065. if (StandardMaterial._AmbientTextureEnabled === value) {
  31066. return;
  31067. }
  31068. StandardMaterial._AmbientTextureEnabled = value;
  31069. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31070. },
  31071. enumerable: true,
  31072. configurable: true
  31073. });
  31074. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31075. get: function () {
  31076. return StandardMaterial._OpacityTextureEnabled;
  31077. },
  31078. set: function (value) {
  31079. if (StandardMaterial._OpacityTextureEnabled === value) {
  31080. return;
  31081. }
  31082. StandardMaterial._OpacityTextureEnabled = value;
  31083. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31084. },
  31085. enumerable: true,
  31086. configurable: true
  31087. });
  31088. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31089. get: function () {
  31090. return StandardMaterial._ReflectionTextureEnabled;
  31091. },
  31092. set: function (value) {
  31093. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31094. return;
  31095. }
  31096. StandardMaterial._ReflectionTextureEnabled = value;
  31097. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31098. },
  31099. enumerable: true,
  31100. configurable: true
  31101. });
  31102. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31103. get: function () {
  31104. return StandardMaterial._EmissiveTextureEnabled;
  31105. },
  31106. set: function (value) {
  31107. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31108. return;
  31109. }
  31110. StandardMaterial._EmissiveTextureEnabled = value;
  31111. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31117. get: function () {
  31118. return StandardMaterial._SpecularTextureEnabled;
  31119. },
  31120. set: function (value) {
  31121. if (StandardMaterial._SpecularTextureEnabled === value) {
  31122. return;
  31123. }
  31124. StandardMaterial._SpecularTextureEnabled = value;
  31125. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31126. },
  31127. enumerable: true,
  31128. configurable: true
  31129. });
  31130. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31131. get: function () {
  31132. return StandardMaterial._BumpTextureEnabled;
  31133. },
  31134. set: function (value) {
  31135. if (StandardMaterial._BumpTextureEnabled === value) {
  31136. return;
  31137. }
  31138. StandardMaterial._BumpTextureEnabled = value;
  31139. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31140. },
  31141. enumerable: true,
  31142. configurable: true
  31143. });
  31144. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31145. get: function () {
  31146. return StandardMaterial._LightmapTextureEnabled;
  31147. },
  31148. set: function (value) {
  31149. if (StandardMaterial._LightmapTextureEnabled === value) {
  31150. return;
  31151. }
  31152. StandardMaterial._LightmapTextureEnabled = value;
  31153. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31154. },
  31155. enumerable: true,
  31156. configurable: true
  31157. });
  31158. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31159. get: function () {
  31160. return StandardMaterial._RefractionTextureEnabled;
  31161. },
  31162. set: function (value) {
  31163. if (StandardMaterial._RefractionTextureEnabled === value) {
  31164. return;
  31165. }
  31166. StandardMaterial._RefractionTextureEnabled = value;
  31167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31168. },
  31169. enumerable: true,
  31170. configurable: true
  31171. });
  31172. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31173. get: function () {
  31174. return StandardMaterial._ColorGradingTextureEnabled;
  31175. },
  31176. set: function (value) {
  31177. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31178. return;
  31179. }
  31180. StandardMaterial._ColorGradingTextureEnabled = value;
  31181. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31182. },
  31183. enumerable: true,
  31184. configurable: true
  31185. });
  31186. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31187. get: function () {
  31188. return StandardMaterial._FresnelEnabled;
  31189. },
  31190. set: function (value) {
  31191. if (StandardMaterial._FresnelEnabled === value) {
  31192. return;
  31193. }
  31194. StandardMaterial._FresnelEnabled = value;
  31195. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31196. },
  31197. enumerable: true,
  31198. configurable: true
  31199. });
  31200. // Flags used to enable or disable a type of texture for all Standard Materials
  31201. StandardMaterial._DiffuseTextureEnabled = true;
  31202. StandardMaterial._AmbientTextureEnabled = true;
  31203. StandardMaterial._OpacityTextureEnabled = true;
  31204. StandardMaterial._ReflectionTextureEnabled = true;
  31205. StandardMaterial._EmissiveTextureEnabled = true;
  31206. StandardMaterial._SpecularTextureEnabled = true;
  31207. StandardMaterial._BumpTextureEnabled = true;
  31208. StandardMaterial._LightmapTextureEnabled = true;
  31209. StandardMaterial._RefractionTextureEnabled = true;
  31210. StandardMaterial._ColorGradingTextureEnabled = true;
  31211. StandardMaterial._FresnelEnabled = true;
  31212. __decorate([
  31213. BABYLON.serializeAsTexture("diffuseTexture")
  31214. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31215. __decorate([
  31216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31217. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31218. __decorate([
  31219. BABYLON.serializeAsTexture("ambientTexture")
  31220. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31221. __decorate([
  31222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31223. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31224. __decorate([
  31225. BABYLON.serializeAsTexture("opacityTexture")
  31226. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31227. __decorate([
  31228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31229. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31230. __decorate([
  31231. BABYLON.serializeAsTexture("reflectionTexture")
  31232. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31233. __decorate([
  31234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31235. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31236. __decorate([
  31237. BABYLON.serializeAsTexture("emissiveTexture")
  31238. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31239. __decorate([
  31240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31241. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31242. __decorate([
  31243. BABYLON.serializeAsTexture("specularTexture")
  31244. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31245. __decorate([
  31246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31247. ], StandardMaterial.prototype, "specularTexture", void 0);
  31248. __decorate([
  31249. BABYLON.serializeAsTexture("bumpTexture")
  31250. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31251. __decorate([
  31252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31253. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31254. __decorate([
  31255. BABYLON.serializeAsTexture("lightmapTexture")
  31256. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31257. __decorate([
  31258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31259. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31260. __decorate([
  31261. BABYLON.serializeAsTexture("refractionTexture")
  31262. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31263. __decorate([
  31264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31265. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31266. __decorate([
  31267. BABYLON.serializeAsColor3("ambient")
  31268. ], StandardMaterial.prototype, "ambientColor", void 0);
  31269. __decorate([
  31270. BABYLON.serializeAsColor3("diffuse")
  31271. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31272. __decorate([
  31273. BABYLON.serializeAsColor3("specular")
  31274. ], StandardMaterial.prototype, "specularColor", void 0);
  31275. __decorate([
  31276. BABYLON.serializeAsColor3("emissive")
  31277. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31278. __decorate([
  31279. BABYLON.serialize()
  31280. ], StandardMaterial.prototype, "specularPower", void 0);
  31281. __decorate([
  31282. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31283. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31284. __decorate([
  31285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31286. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31287. __decorate([
  31288. BABYLON.serialize("useEmissiveAsIllumination")
  31289. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31290. __decorate([
  31291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31292. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31293. __decorate([
  31294. BABYLON.serialize("linkEmissiveWithDiffuse")
  31295. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31296. __decorate([
  31297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31298. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31299. __decorate([
  31300. BABYLON.serialize("useSpecularOverAlpha")
  31301. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31302. __decorate([
  31303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31304. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31305. __decorate([
  31306. BABYLON.serialize("useReflectionOverAlpha")
  31307. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31308. __decorate([
  31309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31310. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31311. __decorate([
  31312. BABYLON.serialize("disableLighting")
  31313. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31314. __decorate([
  31315. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31316. ], StandardMaterial.prototype, "disableLighting", void 0);
  31317. __decorate([
  31318. BABYLON.serialize("useParallax")
  31319. ], StandardMaterial.prototype, "_useParallax", void 0);
  31320. __decorate([
  31321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31322. ], StandardMaterial.prototype, "useParallax", void 0);
  31323. __decorate([
  31324. BABYLON.serialize("useParallaxOcclusion")
  31325. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31326. __decorate([
  31327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31328. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31329. __decorate([
  31330. BABYLON.serialize()
  31331. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31332. __decorate([
  31333. BABYLON.serialize("roughness")
  31334. ], StandardMaterial.prototype, "_roughness", void 0);
  31335. __decorate([
  31336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31337. ], StandardMaterial.prototype, "roughness", void 0);
  31338. __decorate([
  31339. BABYLON.serialize()
  31340. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31341. __decorate([
  31342. BABYLON.serialize()
  31343. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31344. __decorate([
  31345. BABYLON.serialize("useLightmapAsShadowmap")
  31346. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31347. __decorate([
  31348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31349. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31350. __decorate([
  31351. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31352. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31353. __decorate([
  31354. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31355. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31356. __decorate([
  31357. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31358. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31359. __decorate([
  31360. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31361. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31362. __decorate([
  31363. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31364. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31365. __decorate([
  31366. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31367. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31368. __decorate([
  31369. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31370. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31371. __decorate([
  31372. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31373. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31374. __decorate([
  31375. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31376. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31377. __decorate([
  31378. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31379. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31380. __decorate([
  31381. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31382. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31383. __decorate([
  31384. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31385. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31386. __decorate([
  31387. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31388. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31389. __decorate([
  31390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31391. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31392. __decorate([
  31393. BABYLON.serialize("maxSimultaneousLights")
  31394. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31395. __decorate([
  31396. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31397. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31398. __decorate([
  31399. BABYLON.serialize("invertNormalMapX")
  31400. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31401. __decorate([
  31402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31403. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31404. __decorate([
  31405. BABYLON.serialize("invertNormalMapY")
  31406. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31407. __decorate([
  31408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31409. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31410. __decorate([
  31411. BABYLON.serialize("twoSidedLighting")
  31412. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31413. __decorate([
  31414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31415. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31416. __decorate([
  31417. BABYLON.serialize()
  31418. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31419. return StandardMaterial;
  31420. }(BABYLON.PushMaterial));
  31421. BABYLON.StandardMaterial = StandardMaterial;
  31422. })(BABYLON || (BABYLON = {}));
  31423. //# sourceMappingURL=babylon.standardMaterial.js.map
  31424. var BABYLON;
  31425. (function (BABYLON) {
  31426. var PBRMaterialDefines = (function (_super) {
  31427. __extends(PBRMaterialDefines, _super);
  31428. function PBRMaterialDefines() {
  31429. var _this = _super.call(this) || this;
  31430. _this.PBR = true;
  31431. _this.MAINUV1 = false;
  31432. _this.MAINUV2 = false;
  31433. _this.UV1 = false;
  31434. _this.UV2 = false;
  31435. _this.ALBEDO = false;
  31436. _this.ALBEDODIRECTUV = 0;
  31437. _this.VERTEXCOLOR = false;
  31438. _this.AMBIENT = false;
  31439. _this.AMBIENTDIRECTUV = 0;
  31440. _this.AMBIENTINGRAYSCALE = false;
  31441. _this.OPACITY = false;
  31442. _this.VERTEXALPHA = false;
  31443. _this.OPACITYDIRECTUV = 0;
  31444. _this.OPACITYRGB = false;
  31445. _this.ALPHATEST = false;
  31446. _this.ALPHABLEND = false;
  31447. _this.ALPHAFROMALBEDO = false;
  31448. _this.ALPHATESTVALUE = 0.5;
  31449. _this.SPECULAROVERALPHA = false;
  31450. _this.RADIANCEOVERALPHA = false;
  31451. _this.ALPHAFRESNEL = false;
  31452. _this.PREMULTIPLYALPHA = false;
  31453. _this.EMISSIVE = false;
  31454. _this.EMISSIVEDIRECTUV = 0;
  31455. _this.REFLECTIVITY = false;
  31456. _this.REFLECTIVITYDIRECTUV = 0;
  31457. _this.SPECULARTERM = false;
  31458. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31459. _this.MICROSURFACEAUTOMATIC = false;
  31460. _this.LODBASEDMICROSFURACE = false;
  31461. _this.MICROSURFACEMAP = false;
  31462. _this.MICROSURFACEMAPDIRECTUV = 0;
  31463. _this.METALLICWORKFLOW = false;
  31464. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31465. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31466. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31467. _this.AOSTOREINMETALMAPRED = false;
  31468. _this.ENVIRONMENTBRDF = false;
  31469. _this.NORMAL = false;
  31470. _this.TANGENT = false;
  31471. _this.BUMP = false;
  31472. _this.BUMPDIRECTUV = 0;
  31473. _this.PARALLAX = false;
  31474. _this.PARALLAXOCCLUSION = false;
  31475. _this.NORMALXYSCALE = true;
  31476. _this.LIGHTMAP = false;
  31477. _this.LIGHTMAPDIRECTUV = 0;
  31478. _this.USELIGHTMAPASSHADOWMAP = false;
  31479. _this.REFLECTION = false;
  31480. _this.REFLECTIONMAP_3D = false;
  31481. _this.REFLECTIONMAP_SPHERICAL = false;
  31482. _this.REFLECTIONMAP_PLANAR = false;
  31483. _this.REFLECTIONMAP_CUBIC = false;
  31484. _this.REFLECTIONMAP_PROJECTION = false;
  31485. _this.REFLECTIONMAP_SKYBOX = false;
  31486. _this.REFLECTIONMAP_EXPLICIT = false;
  31487. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31488. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31489. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31490. _this.INVERTCUBICMAP = false;
  31491. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31492. _this.USESPHERICALINFRAGMENT = false;
  31493. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31494. _this.LODINREFLECTIONALPHA = false;
  31495. _this.GAMMAREFLECTION = false;
  31496. _this.REFRACTION = false;
  31497. _this.REFRACTIONMAP_3D = false;
  31498. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31499. _this.LODINREFRACTIONALPHA = false;
  31500. _this.GAMMAREFRACTION = false;
  31501. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31502. _this.INSTANCES = false;
  31503. _this.NUM_BONE_INFLUENCERS = 0;
  31504. _this.BonesPerMesh = 0;
  31505. _this.MORPHTARGETS = false;
  31506. _this.MORPHTARGETS_NORMAL = false;
  31507. _this.MORPHTARGETS_TANGENT = false;
  31508. _this.NUM_MORPH_INFLUENCERS = 0;
  31509. _this.IMAGEPROCESSING = false;
  31510. _this.VIGNETTE = false;
  31511. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  31512. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31513. _this.TONEMAPPING = false;
  31514. _this.CONTRAST = false;
  31515. _this.COLORCURVES = false;
  31516. _this.COLORGRADING = false;
  31517. _this.SAMPLER3DGREENDEPTH = false;
  31518. _this.SAMPLER3DBGRMAP = false;
  31519. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31520. _this.EXPOSURE = false;
  31521. _this.USEPHYSICALLIGHTFALLOFF = false;
  31522. _this.TWOSIDEDLIGHTING = false;
  31523. _this.SHADOWFLOAT = false;
  31524. _this.USERIGHTHANDEDSYSTEM = false;
  31525. _this.CLIPPLANE = false;
  31526. _this.POINTSIZE = false;
  31527. _this.FOG = false;
  31528. _this.LOGARITHMICDEPTH = false;
  31529. _this.FORCENORMALFORWARD = false;
  31530. _this.rebuild();
  31531. return _this;
  31532. }
  31533. PBRMaterialDefines.prototype.reset = function () {
  31534. _super.prototype.reset.call(this);
  31535. this.ALPHATESTVALUE = 0.5;
  31536. this.PBR = true;
  31537. };
  31538. return PBRMaterialDefines;
  31539. }(BABYLON.MaterialDefines));
  31540. /**
  31541. * The Physically based material base class of BJS.
  31542. *
  31543. * This offers the main features of a standard PBR material.
  31544. * For more information, please refer to the documentation :
  31545. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31546. */
  31547. var PBRBaseMaterial = (function (_super) {
  31548. __extends(PBRBaseMaterial, _super);
  31549. /**
  31550. * Instantiates a new PBRMaterial instance.
  31551. *
  31552. * @param name The material name
  31553. * @param scene The scene the material will be use in.
  31554. */
  31555. function PBRBaseMaterial(name, scene) {
  31556. var _this = _super.call(this, name, scene) || this;
  31557. /**
  31558. * Intensity of the direct lights e.g. the four lights available in your scene.
  31559. * This impacts both the direct diffuse and specular highlights.
  31560. */
  31561. _this._directIntensity = 1.0;
  31562. /**
  31563. * Intensity of the emissive part of the material.
  31564. * This helps controlling the emissive effect without modifying the emissive color.
  31565. */
  31566. _this._emissiveIntensity = 1.0;
  31567. /**
  31568. * Intensity of the environment e.g. how much the environment will light the object
  31569. * either through harmonics for rough material or through the refelction for shiny ones.
  31570. */
  31571. _this._environmentIntensity = 1.0;
  31572. /**
  31573. * This is a special control allowing the reduction of the specular highlights coming from the
  31574. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31575. */
  31576. _this._specularIntensity = 1.0;
  31577. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  31578. /**
  31579. * Debug Control allowing disabling the bump map on this material.
  31580. */
  31581. _this._disableBumpMap = false;
  31582. /**
  31583. * AKA Occlusion Texture Intensity in other nomenclature.
  31584. */
  31585. _this._ambientTextureStrength = 1.0;
  31586. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  31587. /**
  31588. * AKA Diffuse Color in other nomenclature.
  31589. */
  31590. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  31591. /**
  31592. * AKA Specular Color in other nomenclature.
  31593. */
  31594. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31595. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  31596. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  31597. /**
  31598. * AKA Glossiness in other nomenclature.
  31599. */
  31600. _this._microSurface = 0.9;
  31601. /**
  31602. * source material index of refraction (IOR)' / 'destination material IOR.
  31603. */
  31604. _this._indexOfRefraction = 0.66;
  31605. /**
  31606. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31607. */
  31608. _this._invertRefractionY = false;
  31609. /**
  31610. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31611. * Materials half opaque for instance using refraction could benefit from this control.
  31612. */
  31613. _this._linkRefractionWithTransparency = false;
  31614. _this._useLightmapAsShadowmap = false;
  31615. /**
  31616. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31617. */
  31618. _this._useAlphaFromAlbedoTexture = false;
  31619. /**
  31620. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31621. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31622. */
  31623. _this._useSpecularOverAlpha = true;
  31624. /**
  31625. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31626. */
  31627. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  31628. /**
  31629. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31630. */
  31631. _this._useRoughnessFromMetallicTextureAlpha = true;
  31632. /**
  31633. * Specifies if the metallic texture contains the roughness information in its green channel.
  31634. */
  31635. _this._useRoughnessFromMetallicTextureGreen = false;
  31636. /**
  31637. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31638. */
  31639. _this._useMetallnessFromMetallicTextureBlue = false;
  31640. /**
  31641. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31642. */
  31643. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  31644. /**
  31645. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31646. */
  31647. _this._useAmbientInGrayScale = false;
  31648. /**
  31649. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31650. * The material will try to infer what glossiness each pixel should be.
  31651. */
  31652. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  31653. /**
  31654. * BJS is using an harcoded light falloff based on a manually sets up range.
  31655. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31656. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31657. */
  31658. _this._usePhysicalLightFalloff = true;
  31659. /**
  31660. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31661. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31662. */
  31663. _this._useRadianceOverAlpha = true;
  31664. /**
  31665. * Allows using the bump map in parallax mode.
  31666. */
  31667. _this._useParallax = false;
  31668. /**
  31669. * Allows using the bump map in parallax occlusion mode.
  31670. */
  31671. _this._useParallaxOcclusion = false;
  31672. /**
  31673. * Controls the scale bias of the parallax mode.
  31674. */
  31675. _this._parallaxScaleBias = 0.05;
  31676. /**
  31677. * If sets to true, disables all the lights affecting the material.
  31678. */
  31679. _this._disableLighting = false;
  31680. /**
  31681. * Number of Simultaneous lights allowed on the material.
  31682. */
  31683. _this._maxSimultaneousLights = 4;
  31684. /**
  31685. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  31686. */
  31687. _this._invertNormalMapX = false;
  31688. /**
  31689. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  31690. */
  31691. _this._invertNormalMapY = false;
  31692. /**
  31693. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31694. */
  31695. _this._twoSidedLighting = false;
  31696. /**
  31697. * Defines the alpha limits in alpha test mode.
  31698. */
  31699. _this._alphaCutOff = 0.4;
  31700. /**
  31701. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  31702. */
  31703. _this._forceAlphaTest = false;
  31704. /**
  31705. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31706. * in your scene composition.
  31707. */
  31708. _this._preMultiplyAlpha = false;
  31709. /**
  31710. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31711. * And/Or occlude the blended part.
  31712. */
  31713. _this._useAlphaFresnel = false;
  31714. /**
  31715. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  31716. * from cos thetav and roughness:
  31717. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  31718. */
  31719. _this._environmentBRDFTexture = null;
  31720. /**
  31721. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  31722. */
  31723. _this._forceIrradianceInFragment = false;
  31724. /**
  31725. * Force normal to face away from face.
  31726. * (Temporary internal fix to remove before 3.1)
  31727. */
  31728. _this._forceNormalForward = false;
  31729. _this._renderTargets = new BABYLON.SmartArray(16);
  31730. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  31731. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  31732. _this._tempColor = new BABYLON.Color3();
  31733. // Setup the default processing configuration to the scene.
  31734. _this._attachImageProcessingConfiguration(null);
  31735. _this.getRenderTargetTextures = function () {
  31736. _this._renderTargets.reset();
  31737. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  31738. _this._renderTargets.push(_this._reflectionTexture);
  31739. }
  31740. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  31741. _this._renderTargets.push(_this._refractionTexture);
  31742. }
  31743. return _this._renderTargets;
  31744. };
  31745. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  31746. return _this;
  31747. }
  31748. /**
  31749. * Attaches a new image processing configuration to the PBR Material.
  31750. * @param configuration
  31751. */
  31752. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  31753. var _this = this;
  31754. if (configuration === this._imageProcessingConfiguration) {
  31755. return;
  31756. }
  31757. // Detaches observer.
  31758. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31759. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31760. }
  31761. // Pick the scene configuration if needed.
  31762. if (!configuration) {
  31763. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  31764. }
  31765. else {
  31766. this._imageProcessingConfiguration = configuration;
  31767. }
  31768. // Attaches observer.
  31769. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  31770. _this._markAllSubMeshesAsImageProcessingDirty();
  31771. });
  31772. };
  31773. PBRBaseMaterial.prototype.getClassName = function () {
  31774. return "PBRBaseMaterial";
  31775. };
  31776. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  31777. get: function () {
  31778. return this._useLogarithmicDepth;
  31779. },
  31780. set: function (value) {
  31781. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  31782. },
  31783. enumerable: true,
  31784. configurable: true
  31785. });
  31786. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  31787. if (this._linkRefractionWithTransparency) {
  31788. return false;
  31789. }
  31790. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  31791. };
  31792. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  31793. if (this._forceAlphaTest) {
  31794. return true;
  31795. }
  31796. if (this._linkRefractionWithTransparency) {
  31797. return false;
  31798. }
  31799. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  31800. };
  31801. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  31802. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  31803. };
  31804. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  31805. return this._albedoTexture;
  31806. };
  31807. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31808. if (this.isFrozen) {
  31809. if (this._wasPreviouslyReady) {
  31810. return true;
  31811. }
  31812. }
  31813. if (!subMesh._materialDefines) {
  31814. subMesh._materialDefines = new PBRMaterialDefines();
  31815. }
  31816. var scene = this.getScene();
  31817. var defines = subMesh._materialDefines;
  31818. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31819. if (defines._renderId === scene.getRenderId()) {
  31820. return true;
  31821. }
  31822. }
  31823. var engine = scene.getEngine();
  31824. // Lights
  31825. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  31826. defines._needNormals = true;
  31827. // Textures
  31828. if (defines._areTexturesDirty) {
  31829. defines._needUVs = false;
  31830. if (scene.texturesEnabled) {
  31831. if (scene.getEngine().getCaps().textureLOD) {
  31832. defines.LODBASEDMICROSFURACE = true;
  31833. }
  31834. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31835. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  31836. return false;
  31837. }
  31838. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  31839. }
  31840. else {
  31841. defines.ALBEDO = false;
  31842. }
  31843. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31844. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  31845. return false;
  31846. }
  31847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  31848. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  31849. }
  31850. else {
  31851. defines.AMBIENT = false;
  31852. }
  31853. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31854. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  31855. return false;
  31856. }
  31857. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  31858. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31859. }
  31860. else {
  31861. defines.OPACITY = false;
  31862. }
  31863. var reflectionTexture = this._getReflectionTexture();
  31864. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31865. if (!reflectionTexture.isReadyOrNotBlocking()) {
  31866. return false;
  31867. }
  31868. defines.REFLECTION = true;
  31869. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  31870. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  31871. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31872. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  31873. defines.INVERTCUBICMAP = true;
  31874. }
  31875. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  31876. switch (reflectionTexture.coordinatesMode) {
  31877. case BABYLON.Texture.CUBIC_MODE:
  31878. case BABYLON.Texture.INVCUBIC_MODE:
  31879. defines.REFLECTIONMAP_CUBIC = true;
  31880. break;
  31881. case BABYLON.Texture.EXPLICIT_MODE:
  31882. defines.REFLECTIONMAP_EXPLICIT = true;
  31883. break;
  31884. case BABYLON.Texture.PLANAR_MODE:
  31885. defines.REFLECTIONMAP_PLANAR = true;
  31886. break;
  31887. case BABYLON.Texture.PROJECTION_MODE:
  31888. defines.REFLECTIONMAP_PROJECTION = true;
  31889. break;
  31890. case BABYLON.Texture.SKYBOX_MODE:
  31891. defines.REFLECTIONMAP_SKYBOX = true;
  31892. break;
  31893. case BABYLON.Texture.SPHERICAL_MODE:
  31894. defines.REFLECTIONMAP_SPHERICAL = true;
  31895. break;
  31896. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31897. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  31898. break;
  31899. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31900. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  31901. break;
  31902. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31903. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  31904. break;
  31905. }
  31906. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  31907. if (reflectionTexture.sphericalPolynomial) {
  31908. defines.USESPHERICALFROMREFLECTIONMAP = true;
  31909. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  31910. defines.USESPHERICALINFRAGMENT = true;
  31911. }
  31912. }
  31913. }
  31914. }
  31915. else {
  31916. defines.REFLECTION = false;
  31917. defines.REFLECTIONMAP_3D = false;
  31918. defines.REFLECTIONMAP_SPHERICAL = false;
  31919. defines.REFLECTIONMAP_PLANAR = false;
  31920. defines.REFLECTIONMAP_CUBIC = false;
  31921. defines.REFLECTIONMAP_PROJECTION = false;
  31922. defines.REFLECTIONMAP_SKYBOX = false;
  31923. defines.REFLECTIONMAP_EXPLICIT = false;
  31924. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31925. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31926. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31927. defines.INVERTCUBICMAP = false;
  31928. defines.USESPHERICALFROMREFLECTIONMAP = false;
  31929. defines.USESPHERICALINFRAGMENT = false;
  31930. defines.REFLECTIONMAP_OPPOSITEZ = false;
  31931. defines.LODINREFLECTIONALPHA = false;
  31932. defines.GAMMAREFLECTION = false;
  31933. }
  31934. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31935. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  31936. return false;
  31937. }
  31938. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  31939. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31940. }
  31941. else {
  31942. defines.LIGHTMAP = false;
  31943. }
  31944. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31945. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  31946. return false;
  31947. }
  31948. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  31949. }
  31950. else {
  31951. defines.EMISSIVE = false;
  31952. }
  31953. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31954. if (this._metallicTexture) {
  31955. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  31956. return false;
  31957. }
  31958. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  31959. defines.METALLICWORKFLOW = true;
  31960. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  31961. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  31962. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  31963. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  31964. }
  31965. else if (this._reflectivityTexture) {
  31966. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  31967. return false;
  31968. }
  31969. defines.METALLICWORKFLOW = false;
  31970. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  31971. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  31972. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  31973. }
  31974. else {
  31975. defines.METALLICWORKFLOW = false;
  31976. defines.REFLECTIVITY = false;
  31977. }
  31978. if (this._microSurfaceTexture) {
  31979. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  31980. return false;
  31981. }
  31982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  31983. }
  31984. else {
  31985. defines.MICROSURFACEMAP = false;
  31986. }
  31987. }
  31988. else {
  31989. defines.REFLECTIVITY = false;
  31990. defines.MICROSURFACEMAP = false;
  31991. }
  31992. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31993. // Bump texure can not be none blocking.
  31994. if (!this._bumpTexture.isReady()) {
  31995. return false;
  31996. }
  31997. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  31998. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31999. defines.PARALLAX = true;
  32000. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32001. }
  32002. else {
  32003. defines.PARALLAX = false;
  32004. }
  32005. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  32006. }
  32007. else {
  32008. defines.BUMP = false;
  32009. }
  32010. var refractionTexture = this._getRefractionTexture();
  32011. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32012. if (!refractionTexture.isReadyOrNotBlocking()) {
  32013. return false;
  32014. }
  32015. defines.REFRACTION = true;
  32016. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32017. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32018. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32019. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32020. if (this._linkRefractionWithTransparency) {
  32021. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32022. }
  32023. }
  32024. else {
  32025. defines.REFRACTION = false;
  32026. }
  32027. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32028. // This is blocking.
  32029. if (!this._environmentBRDFTexture.isReady()) {
  32030. return false;
  32031. }
  32032. defines.ENVIRONMENTBRDF = true;
  32033. }
  32034. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32035. defines.ALPHAFROMALBEDO = true;
  32036. }
  32037. }
  32038. if (this._useSpecularOverAlpha) {
  32039. defines.SPECULAROVERALPHA = true;
  32040. }
  32041. if (this._usePhysicalLightFalloff) {
  32042. defines.USEPHYSICALLIGHTFALLOFF = true;
  32043. }
  32044. if (this._useRadianceOverAlpha) {
  32045. defines.RADIANCEOVERALPHA = true;
  32046. }
  32047. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32048. defines.METALLICWORKFLOW = true;
  32049. }
  32050. if (!this.backFaceCulling && this._twoSidedLighting) {
  32051. defines.TWOSIDEDLIGHTING = true;
  32052. }
  32053. defines.ALPHATESTVALUE = this._alphaCutOff;
  32054. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32055. defines.ALPHABLEND = this.needAlphaBlending();
  32056. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32057. }
  32058. if (defines._areImageProcessingDirty) {
  32059. if (!this._imageProcessingConfiguration.isReady()) {
  32060. return false;
  32061. }
  32062. this._imageProcessingConfiguration.prepareDefines(defines);
  32063. }
  32064. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32065. // Misc.
  32066. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32067. // Values that need to be evaluated on every frame
  32068. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32069. // Attribs
  32070. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32071. if (mesh) {
  32072. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32073. mesh.createNormals(true);
  32074. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32075. }
  32076. }
  32077. }
  32078. // Get correct effect
  32079. if (defines.isDirty) {
  32080. defines.markAsProcessed();
  32081. scene.resetCachedMaterial();
  32082. // Fallbacks
  32083. var fallbacks = new BABYLON.EffectFallbacks();
  32084. if (defines.ENVIRONMENTBRDF) {
  32085. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32086. }
  32087. if (defines.REFLECTION) {
  32088. fallbacks.addFallback(0, "REFLECTION");
  32089. }
  32090. if (defines.REFRACTION) {
  32091. fallbacks.addFallback(0, "REFRACTION");
  32092. }
  32093. if (defines.REFLECTIVITY) {
  32094. fallbacks.addFallback(0, "REFLECTIVITY");
  32095. }
  32096. if (defines.BUMP) {
  32097. fallbacks.addFallback(0, "BUMP");
  32098. }
  32099. if (defines.PARALLAX) {
  32100. fallbacks.addFallback(1, "PARALLAX");
  32101. }
  32102. if (defines.PARALLAXOCCLUSION) {
  32103. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32104. }
  32105. if (defines.SPECULAROVERALPHA) {
  32106. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32107. }
  32108. if (defines.FOG) {
  32109. fallbacks.addFallback(1, "FOG");
  32110. }
  32111. if (defines.POINTSIZE) {
  32112. fallbacks.addFallback(0, "POINTSIZE");
  32113. }
  32114. if (defines.LOGARITHMICDEPTH) {
  32115. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32116. }
  32117. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32118. if (defines.SPECULARTERM) {
  32119. fallbacks.addFallback(0, "SPECULARTERM");
  32120. }
  32121. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32122. fallbacks.addCPUSkinningFallback(0, mesh);
  32123. }
  32124. //Attributes
  32125. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32126. if (defines.NORMAL) {
  32127. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32128. }
  32129. if (defines.TANGENT) {
  32130. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32131. }
  32132. if (defines.UV1) {
  32133. attribs.push(BABYLON.VertexBuffer.UVKind);
  32134. }
  32135. if (defines.UV2) {
  32136. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32137. }
  32138. if (defines.VERTEXCOLOR) {
  32139. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32140. }
  32141. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32142. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32143. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32144. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32145. "vFogInfos", "vFogColor", "pointSize",
  32146. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32147. "mBones",
  32148. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32149. "vLightingIntensity",
  32150. "logarithmicDepthConstant",
  32151. "vSphericalX", "vSphericalY", "vSphericalZ",
  32152. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32153. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32154. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32155. "vNormalReoderParams"
  32156. ];
  32157. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32158. "bumpSampler", "lightmapSampler", "opacitySampler",
  32159. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32160. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32161. "microSurfaceSampler", "environmentBrdfSampler"];
  32162. var uniformBuffers = ["Material", "Scene"];
  32163. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32164. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32165. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32166. uniformsNames: uniforms,
  32167. uniformBuffersNames: uniformBuffers,
  32168. samplers: samplers,
  32169. defines: defines,
  32170. maxSimultaneousLights: this._maxSimultaneousLights
  32171. });
  32172. var onCompiled = function (effect) {
  32173. if (this.onCompiled) {
  32174. this.onCompiled(effect);
  32175. }
  32176. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32177. }.bind(this);
  32178. var join = defines.toString();
  32179. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32180. attributes: attribs,
  32181. uniformsNames: uniforms,
  32182. uniformBuffersNames: uniformBuffers,
  32183. samplers: samplers,
  32184. defines: join,
  32185. fallbacks: fallbacks,
  32186. onCompiled: onCompiled,
  32187. onError: this.onError,
  32188. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32189. }, engine), defines);
  32190. this.buildUniformLayout();
  32191. }
  32192. if (!subMesh.effect.isReady()) {
  32193. return false;
  32194. }
  32195. defines._renderId = scene.getRenderId();
  32196. this._wasPreviouslyReady = true;
  32197. return true;
  32198. };
  32199. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32200. // Order is important !
  32201. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32202. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32203. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32204. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32205. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32206. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32207. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32208. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32209. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32210. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32211. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32212. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32213. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32214. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32215. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32216. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32217. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32218. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32219. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  32220. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32221. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32222. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32223. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32224. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32225. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32226. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32227. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32228. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32229. this._uniformBuffer.addUniform("pointSize", 1);
  32230. this._uniformBuffer.create();
  32231. };
  32232. PBRBaseMaterial.prototype.unbind = function () {
  32233. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32234. this._uniformBuffer.setTexture("reflectionSampler", null);
  32235. }
  32236. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32237. this._uniformBuffer.setTexture("refractionSampler", null);
  32238. }
  32239. _super.prototype.unbind.call(this);
  32240. };
  32241. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32242. this._activeEffect.setMatrix("world", world);
  32243. };
  32244. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32245. var scene = this.getScene();
  32246. var defines = subMesh._materialDefines;
  32247. if (!defines) {
  32248. return;
  32249. }
  32250. var effect = subMesh.effect;
  32251. this._activeEffect = effect;
  32252. // Matrices
  32253. this.bindOnlyWorldMatrix(world);
  32254. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32255. // Bones
  32256. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32257. if (mustRebind) {
  32258. this._uniformBuffer.bindToEffect(effect, "Material");
  32259. this.bindViewProjection(effect);
  32260. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32261. // Texture uniforms
  32262. if (scene.texturesEnabled) {
  32263. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32264. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32265. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32266. }
  32267. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32268. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32269. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32270. }
  32271. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32272. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32273. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32274. }
  32275. var reflectionTexture = this._getReflectionTexture();
  32276. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32277. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32278. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32279. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32280. var polynomials = reflectionTexture.sphericalPolynomial;
  32281. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32282. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32283. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32284. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32285. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32286. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32287. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32288. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32289. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32290. }
  32291. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32292. }
  32293. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32294. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32295. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32296. }
  32297. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32298. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32299. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32300. }
  32301. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32302. if (this._metallicTexture) {
  32303. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32304. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32305. }
  32306. else if (this._reflectivityTexture) {
  32307. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32308. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32309. }
  32310. if (this._microSurfaceTexture) {
  32311. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32312. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32313. }
  32314. }
  32315. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32316. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32317. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32318. if (scene._mirroredCameraPosition) {
  32319. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 0 : 1.0, this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 0 : 1.0, this._invertNormalMapY ? 1.0 : -1.0);
  32320. }
  32321. else {
  32322. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 1.0 : 0, this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? 1.0 : 0, this._invertNormalMapY ? -1.0 : 1.0);
  32323. }
  32324. }
  32325. var refractionTexture = this._getRefractionTexture();
  32326. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32327. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32328. var depth = 1.0;
  32329. if (!refractionTexture.isCube) {
  32330. if (refractionTexture.depth) {
  32331. depth = refractionTexture.depth;
  32332. }
  32333. }
  32334. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32335. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32336. }
  32337. }
  32338. // Point size
  32339. if (this.pointsCloud) {
  32340. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32341. }
  32342. // Colors
  32343. if (defines.METALLICWORKFLOW) {
  32344. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32345. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32346. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32347. }
  32348. else {
  32349. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32350. }
  32351. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32352. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32353. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32354. // Misc
  32355. this._lightingInfos.x = this._directIntensity;
  32356. this._lightingInfos.y = this._emissiveIntensity;
  32357. this._lightingInfos.z = this._environmentIntensity;
  32358. this._lightingInfos.w = this._specularIntensity;
  32359. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32360. }
  32361. // Textures
  32362. if (scene.texturesEnabled) {
  32363. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32364. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32365. }
  32366. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32367. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32368. }
  32369. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32370. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32371. }
  32372. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32373. if (defines.LODBASEDMICROSFURACE) {
  32374. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32375. }
  32376. else {
  32377. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32378. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32379. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32380. }
  32381. }
  32382. if (defines.ENVIRONMENTBRDF) {
  32383. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32384. }
  32385. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32386. if (defines.LODBASEDMICROSFURACE) {
  32387. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32388. }
  32389. else {
  32390. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32391. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32392. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32393. }
  32394. }
  32395. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32396. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32397. }
  32398. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32399. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32400. }
  32401. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32402. if (this._metallicTexture) {
  32403. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32404. }
  32405. else if (this._reflectivityTexture) {
  32406. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  32407. }
  32408. if (this._microSurfaceTexture) {
  32409. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  32410. }
  32411. }
  32412. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32413. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32414. }
  32415. }
  32416. // Clip plane
  32417. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32418. // Colors
  32419. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32420. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32421. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32422. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32423. }
  32424. if (mustRebind || !this.isFrozen) {
  32425. // Lights
  32426. if (scene.lightsEnabled && !this._disableLighting) {
  32427. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32428. }
  32429. // View
  32430. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32431. this.bindView(effect);
  32432. }
  32433. // Fog
  32434. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32435. // Morph targets
  32436. if (defines.NUM_MORPH_INFLUENCERS) {
  32437. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32438. }
  32439. // image processing
  32440. this._imageProcessingConfiguration.bind(this._activeEffect);
  32441. // Log. depth
  32442. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32443. }
  32444. this._uniformBuffer.update();
  32445. this._afterBind(mesh);
  32446. scene = null;
  32447. };
  32448. PBRBaseMaterial.prototype.getAnimatables = function () {
  32449. var results = [];
  32450. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32451. results.push(this._albedoTexture);
  32452. }
  32453. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32454. results.push(this._ambientTexture);
  32455. }
  32456. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32457. results.push(this._opacityTexture);
  32458. }
  32459. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32460. results.push(this._reflectionTexture);
  32461. }
  32462. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32463. results.push(this._emissiveTexture);
  32464. }
  32465. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32466. results.push(this._metallicTexture);
  32467. }
  32468. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32469. results.push(this._reflectivityTexture);
  32470. }
  32471. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32472. results.push(this._bumpTexture);
  32473. }
  32474. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32475. results.push(this._lightmapTexture);
  32476. }
  32477. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32478. results.push(this._refractionTexture);
  32479. }
  32480. return results;
  32481. };
  32482. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32483. if (this._reflectionTexture) {
  32484. return this._reflectionTexture;
  32485. }
  32486. return this.getScene().environmentTexture;
  32487. };
  32488. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32489. if (this._refractionTexture) {
  32490. return this._refractionTexture;
  32491. }
  32492. if (this._linkRefractionWithTransparency) {
  32493. return this.getScene().environmentTexture;
  32494. }
  32495. return null;
  32496. };
  32497. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32498. if (forceDisposeTextures) {
  32499. if (this._albedoTexture) {
  32500. this._albedoTexture.dispose();
  32501. }
  32502. if (this._ambientTexture) {
  32503. this._ambientTexture.dispose();
  32504. }
  32505. if (this._opacityTexture) {
  32506. this._opacityTexture.dispose();
  32507. }
  32508. if (this._reflectionTexture) {
  32509. this._reflectionTexture.dispose();
  32510. }
  32511. if (this._environmentBRDFTexture) {
  32512. this._environmentBRDFTexture.dispose();
  32513. }
  32514. if (this._emissiveTexture) {
  32515. this._emissiveTexture.dispose();
  32516. }
  32517. if (this._metallicTexture) {
  32518. this._metallicTexture.dispose();
  32519. }
  32520. if (this._reflectivityTexture) {
  32521. this._reflectivityTexture.dispose();
  32522. }
  32523. if (this._bumpTexture) {
  32524. this._bumpTexture.dispose();
  32525. }
  32526. if (this._lightmapTexture) {
  32527. this._lightmapTexture.dispose();
  32528. }
  32529. if (this._refractionTexture) {
  32530. this._refractionTexture.dispose();
  32531. }
  32532. }
  32533. this._renderTargets.dispose();
  32534. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32535. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32536. }
  32537. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32538. };
  32539. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32540. __decorate([
  32541. BABYLON.serializeAsImageProcessingConfiguration()
  32542. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32543. __decorate([
  32544. BABYLON.serialize()
  32545. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32546. return PBRBaseMaterial;
  32547. }(BABYLON.PushMaterial));
  32548. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  32549. })(BABYLON || (BABYLON = {}));
  32550. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  32551. var BABYLON;
  32552. (function (BABYLON) {
  32553. var Internals;
  32554. (function (Internals) {
  32555. /**
  32556. * The Physically based simple base material of BJS.
  32557. *
  32558. * This enables better naming and convention enforcements on top of the pbrMaterial.
  32559. * It is used as the base class for both the specGloss and metalRough conventions.
  32560. */
  32561. var PBRBaseSimpleMaterial = (function (_super) {
  32562. __extends(PBRBaseSimpleMaterial, _super);
  32563. /**
  32564. * Instantiates a new PBRMaterial instance.
  32565. *
  32566. * @param name The material name
  32567. * @param scene The scene the material will be use in.
  32568. */
  32569. function PBRBaseSimpleMaterial(name, scene) {
  32570. var _this = _super.call(this, name, scene) || this;
  32571. /**
  32572. * Number of Simultaneous lights allowed on the material.
  32573. */
  32574. _this.maxSimultaneousLights = 4;
  32575. /**
  32576. * If sets to true, disables all the lights affecting the material.
  32577. */
  32578. _this.disableLighting = false;
  32579. /**
  32580. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32581. */
  32582. _this.invertNormalMapX = false;
  32583. /**
  32584. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32585. */
  32586. _this.invertNormalMapY = false;
  32587. /**
  32588. * Emissivie color used to self-illuminate the model.
  32589. */
  32590. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32591. /**
  32592. * Occlusion Channel Strenght.
  32593. */
  32594. _this.occlusionStrength = 1.0;
  32595. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32596. _this._useAmbientInGrayScale = true;
  32597. return _this;
  32598. }
  32599. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  32600. /**
  32601. * Gets the current transparency mode.
  32602. */
  32603. get: function () {
  32604. return this._transparencyMode;
  32605. },
  32606. /**
  32607. * Sets the transparency mode of the material.
  32608. */
  32609. set: function (value) {
  32610. if (this._transparencyMode === value) {
  32611. return;
  32612. }
  32613. this._transparencyMode = value;
  32614. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  32615. this._forceAlphaTest = true;
  32616. }
  32617. else {
  32618. this._forceAlphaTest = false;
  32619. }
  32620. this._markAllSubMeshesAsTexturesDirty();
  32621. },
  32622. enumerable: true,
  32623. configurable: true
  32624. });
  32625. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  32626. /**
  32627. * Gets the current double sided mode.
  32628. */
  32629. get: function () {
  32630. return this._twoSidedLighting;
  32631. },
  32632. /**
  32633. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32634. */
  32635. set: function (value) {
  32636. if (this._twoSidedLighting === value) {
  32637. return;
  32638. }
  32639. this._twoSidedLighting = value;
  32640. this.backFaceCulling = !value;
  32641. this._markAllSubMeshesAsTexturesDirty();
  32642. },
  32643. enumerable: true,
  32644. configurable: true
  32645. });
  32646. /**
  32647. * Specifies wether or not the alpha value of the albedo texture should be used.
  32648. */
  32649. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32650. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32651. };
  32652. /**
  32653. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  32654. */
  32655. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  32656. if (this._linkRefractionWithTransparency) {
  32657. return false;
  32658. }
  32659. return (this.alpha < 1.0) ||
  32660. (this._shouldUseAlphaFromAlbedoTexture() &&
  32661. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  32662. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  32663. };
  32664. /**
  32665. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  32666. */
  32667. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  32668. if (this._linkRefractionWithTransparency) {
  32669. return false;
  32670. }
  32671. return this._shouldUseAlphaFromAlbedoTexture() &&
  32672. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  32673. };
  32674. /**
  32675. * Return the active textures of the material.
  32676. */
  32677. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  32678. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32679. if (this.environmentTexture) {
  32680. activeTextures.push(this.environmentTexture);
  32681. }
  32682. if (this.normalTexture) {
  32683. activeTextures.push(this.normalTexture);
  32684. }
  32685. if (this.emissiveTexture) {
  32686. activeTextures.push(this.emissiveTexture);
  32687. }
  32688. if (this.occlusionTexture) {
  32689. activeTextures.push(this.occlusionTexture);
  32690. }
  32691. return activeTextures;
  32692. };
  32693. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  32694. return "PBRBaseSimpleMaterial";
  32695. };
  32696. __decorate([
  32697. BABYLON.serialize(),
  32698. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32699. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  32700. __decorate([
  32701. BABYLON.serialize(),
  32702. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32703. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  32704. __decorate([
  32705. BABYLON.serializeAsTexture(),
  32706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  32707. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  32708. __decorate([
  32709. BABYLON.serialize(),
  32710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32711. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  32712. __decorate([
  32713. BABYLON.serialize(),
  32714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32715. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  32716. __decorate([
  32717. BABYLON.serializeAsTexture(),
  32718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  32719. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  32720. __decorate([
  32721. BABYLON.serializeAsColor3("emissive"),
  32722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32723. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  32724. __decorate([
  32725. BABYLON.serializeAsTexture(),
  32726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32727. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  32728. __decorate([
  32729. BABYLON.serialize(),
  32730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  32731. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  32732. __decorate([
  32733. BABYLON.serializeAsTexture(),
  32734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  32735. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  32736. __decorate([
  32737. BABYLON.serialize(),
  32738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  32739. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  32740. __decorate([
  32741. BABYLON.serialize()
  32742. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  32743. __decorate([
  32744. BABYLON.serialize()
  32745. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  32746. return PBRBaseSimpleMaterial;
  32747. }(BABYLON.PBRBaseMaterial));
  32748. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  32749. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32750. })(BABYLON || (BABYLON = {}));
  32751. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  32752. var BABYLON;
  32753. (function (BABYLON) {
  32754. /**
  32755. * The Physically based material of BJS.
  32756. *
  32757. * This offers the main features of a standard PBR material.
  32758. * For more information, please refer to the documentation :
  32759. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32760. */
  32761. var PBRMaterial = (function (_super) {
  32762. __extends(PBRMaterial, _super);
  32763. /**
  32764. * Instantiates a new PBRMaterial instance.
  32765. *
  32766. * @param name The material name
  32767. * @param scene The scene the material will be use in.
  32768. */
  32769. function PBRMaterial(name, scene) {
  32770. var _this = _super.call(this, name, scene) || this;
  32771. /**
  32772. * Intensity of the direct lights e.g. the four lights available in your scene.
  32773. * This impacts both the direct diffuse and specular highlights.
  32774. */
  32775. _this.directIntensity = 1.0;
  32776. /**
  32777. * Intensity of the emissive part of the material.
  32778. * This helps controlling the emissive effect without modifying the emissive color.
  32779. */
  32780. _this.emissiveIntensity = 1.0;
  32781. /**
  32782. * Intensity of the environment e.g. how much the environment will light the object
  32783. * either through harmonics for rough material or through the refelction for shiny ones.
  32784. */
  32785. _this.environmentIntensity = 1.0;
  32786. /**
  32787. * This is a special control allowing the reduction of the specular highlights coming from the
  32788. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32789. */
  32790. _this.specularIntensity = 1.0;
  32791. /**
  32792. * Debug Control allowing disabling the bump map on this material.
  32793. */
  32794. _this.disableBumpMap = false;
  32795. /**
  32796. * AKA Occlusion Texture Intensity in other nomenclature.
  32797. */
  32798. _this.ambientTextureStrength = 1.0;
  32799. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32800. /**
  32801. * AKA Diffuse Color in other nomenclature.
  32802. */
  32803. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  32804. /**
  32805. * AKA Specular Color in other nomenclature.
  32806. */
  32807. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32808. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  32809. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32810. /**
  32811. * AKA Glossiness in other nomenclature.
  32812. */
  32813. _this.microSurface = 1.0;
  32814. /**
  32815. * source material index of refraction (IOR)' / 'destination material IOR.
  32816. */
  32817. _this.indexOfRefraction = 0.66;
  32818. /**
  32819. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32820. */
  32821. _this.invertRefractionY = false;
  32822. /**
  32823. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32824. * Materials half opaque for instance using refraction could benefit from this control.
  32825. */
  32826. _this.linkRefractionWithTransparency = false;
  32827. _this.useLightmapAsShadowmap = false;
  32828. /**
  32829. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32830. */
  32831. _this.useAlphaFromAlbedoTexture = false;
  32832. /**
  32833. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32834. */
  32835. _this.forceAlphaTest = false;
  32836. /**
  32837. * Defines the alpha limits in alpha test mode.
  32838. */
  32839. _this.alphaCutOff = 0.4;
  32840. /**
  32841. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32842. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32843. */
  32844. _this.useSpecularOverAlpha = true;
  32845. /**
  32846. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32847. */
  32848. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  32849. /**
  32850. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32851. */
  32852. _this.useRoughnessFromMetallicTextureAlpha = true;
  32853. /**
  32854. * Specifies if the metallic texture contains the roughness information in its green channel.
  32855. */
  32856. _this.useRoughnessFromMetallicTextureGreen = false;
  32857. /**
  32858. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32859. */
  32860. _this.useMetallnessFromMetallicTextureBlue = false;
  32861. /**
  32862. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32863. */
  32864. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  32865. /**
  32866. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32867. */
  32868. _this.useAmbientInGrayScale = false;
  32869. /**
  32870. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32871. * The material will try to infer what glossiness each pixel should be.
  32872. */
  32873. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  32874. /**
  32875. * BJS is using an harcoded light falloff based on a manually sets up range.
  32876. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32877. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32878. */
  32879. _this.usePhysicalLightFalloff = true;
  32880. /**
  32881. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32882. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32883. */
  32884. _this.useRadianceOverAlpha = true;
  32885. /**
  32886. * Allows using the bump map in parallax mode.
  32887. */
  32888. _this.useParallax = false;
  32889. /**
  32890. * Allows using the bump map in parallax occlusion mode.
  32891. */
  32892. _this.useParallaxOcclusion = false;
  32893. /**
  32894. * Controls the scale bias of the parallax mode.
  32895. */
  32896. _this.parallaxScaleBias = 0.05;
  32897. /**
  32898. * If sets to true, disables all the lights affecting the material.
  32899. */
  32900. _this.disableLighting = false;
  32901. /**
  32902. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32903. */
  32904. _this.forceIrradianceInFragment = false;
  32905. /**
  32906. * Number of Simultaneous lights allowed on the material.
  32907. */
  32908. _this.maxSimultaneousLights = 4;
  32909. /**
  32910. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32911. */
  32912. _this.invertNormalMapX = false;
  32913. /**
  32914. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32915. */
  32916. _this.invertNormalMapY = false;
  32917. /**
  32918. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32919. */
  32920. _this.twoSidedLighting = false;
  32921. /**
  32922. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32923. * in your scene composition.
  32924. */
  32925. _this.preMultiplyAlpha = false;
  32926. /**
  32927. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32928. * And/Or occlude the blended part.
  32929. */
  32930. _this.useAlphaFresnel = false;
  32931. /**
  32932. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32933. * And/Or occlude the blended part.
  32934. */
  32935. _this.environmentBRDFTexture = null;
  32936. /**
  32937. * Force normal to face away from face.
  32938. * (Temporary internal fix to remove before 3.1)
  32939. */
  32940. _this.forceNormalForward = false;
  32941. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32942. return _this;
  32943. }
  32944. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  32945. /**
  32946. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  32947. */
  32948. get: function () {
  32949. return this._PBRMATERIAL_OPAQUE;
  32950. },
  32951. enumerable: true,
  32952. configurable: true
  32953. });
  32954. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  32955. /**
  32956. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  32957. */
  32958. get: function () {
  32959. return this._PBRMATERIAL_ALPHATEST;
  32960. },
  32961. enumerable: true,
  32962. configurable: true
  32963. });
  32964. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  32965. /**
  32966. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32967. */
  32968. get: function () {
  32969. return this._PBRMATERIAL_ALPHABLEND;
  32970. },
  32971. enumerable: true,
  32972. configurable: true
  32973. });
  32974. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  32975. /**
  32976. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32977. * They are also discarded below the alpha cutoff threshold to improve performances.
  32978. */
  32979. get: function () {
  32980. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  32981. },
  32982. enumerable: true,
  32983. configurable: true
  32984. });
  32985. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  32986. /**
  32987. * Gets the image processing configuration used either in this material.
  32988. */
  32989. get: function () {
  32990. return this._imageProcessingConfiguration;
  32991. },
  32992. /**
  32993. * Sets the Default image processing configuration used either in the this material.
  32994. *
  32995. * If sets to null, the scene one is in use.
  32996. */
  32997. set: function (value) {
  32998. this._attachImageProcessingConfiguration(value);
  32999. // Ensure the effect will be rebuilt.
  33000. this._markAllSubMeshesAsTexturesDirty();
  33001. },
  33002. enumerable: true,
  33003. configurable: true
  33004. });
  33005. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33006. /**
  33007. * Gets wether the color curves effect is enabled.
  33008. */
  33009. get: function () {
  33010. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33011. },
  33012. /**
  33013. * Sets wether the color curves effect is enabled.
  33014. */
  33015. set: function (value) {
  33016. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33017. },
  33018. enumerable: true,
  33019. configurable: true
  33020. });
  33021. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33022. /**
  33023. * Gets wether the color grading effect is enabled.
  33024. */
  33025. get: function () {
  33026. return this.imageProcessingConfiguration.colorGradingEnabled;
  33027. },
  33028. /**
  33029. * Gets wether the color grading effect is enabled.
  33030. */
  33031. set: function (value) {
  33032. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33033. },
  33034. enumerable: true,
  33035. configurable: true
  33036. });
  33037. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33038. /**
  33039. * Gets wether tonemapping is enabled or not.
  33040. */
  33041. get: function () {
  33042. return this._imageProcessingConfiguration.toneMappingEnabled;
  33043. },
  33044. /**
  33045. * Sets wether tonemapping is enabled or not
  33046. */
  33047. set: function (value) {
  33048. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33049. },
  33050. enumerable: true,
  33051. configurable: true
  33052. });
  33053. ;
  33054. ;
  33055. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33056. /**
  33057. * The camera exposure used on this material.
  33058. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33059. * This corresponds to a photographic exposure.
  33060. */
  33061. get: function () {
  33062. return this._imageProcessingConfiguration.exposure;
  33063. },
  33064. /**
  33065. * The camera exposure used on this material.
  33066. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33067. * This corresponds to a photographic exposure.
  33068. */
  33069. set: function (value) {
  33070. this._imageProcessingConfiguration.exposure = value;
  33071. },
  33072. enumerable: true,
  33073. configurable: true
  33074. });
  33075. ;
  33076. ;
  33077. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33078. /**
  33079. * Gets The camera contrast used on this material.
  33080. */
  33081. get: function () {
  33082. return this._imageProcessingConfiguration.contrast;
  33083. },
  33084. /**
  33085. * Sets The camera contrast used on this material.
  33086. */
  33087. set: function (value) {
  33088. this._imageProcessingConfiguration.contrast = value;
  33089. },
  33090. enumerable: true,
  33091. configurable: true
  33092. });
  33093. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33094. /**
  33095. * Gets the Color Grading 2D Lookup Texture.
  33096. */
  33097. get: function () {
  33098. return this._imageProcessingConfiguration.colorGradingTexture;
  33099. },
  33100. /**
  33101. * Sets the Color Grading 2D Lookup Texture.
  33102. */
  33103. set: function (value) {
  33104. this._imageProcessingConfiguration.colorGradingTexture = value;
  33105. },
  33106. enumerable: true,
  33107. configurable: true
  33108. });
  33109. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33110. /**
  33111. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33112. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33113. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  33114. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33115. */
  33116. get: function () {
  33117. return this._imageProcessingConfiguration.colorCurves;
  33118. },
  33119. /**
  33120. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33121. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33122. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  33123. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33124. */
  33125. set: function (value) {
  33126. this._imageProcessingConfiguration.colorCurves = value;
  33127. },
  33128. enumerable: true,
  33129. configurable: true
  33130. });
  33131. PBRMaterial.prototype.getClassName = function () {
  33132. return "PBRMaterial";
  33133. };
  33134. PBRMaterial.prototype.getActiveTextures = function () {
  33135. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33136. if (this._albedoTexture) {
  33137. activeTextures.push(this._albedoTexture);
  33138. }
  33139. if (this._ambientTexture) {
  33140. activeTextures.push(this._ambientTexture);
  33141. }
  33142. if (this._opacityTexture) {
  33143. activeTextures.push(this._opacityTexture);
  33144. }
  33145. if (this._reflectionTexture) {
  33146. activeTextures.push(this._reflectionTexture);
  33147. }
  33148. if (this._emissiveTexture) {
  33149. activeTextures.push(this._emissiveTexture);
  33150. }
  33151. if (this._reflectivityTexture) {
  33152. activeTextures.push(this._reflectivityTexture);
  33153. }
  33154. if (this._metallicTexture) {
  33155. activeTextures.push(this._metallicTexture);
  33156. }
  33157. if (this._microSurfaceTexture) {
  33158. activeTextures.push(this._microSurfaceTexture);
  33159. }
  33160. if (this._bumpTexture) {
  33161. activeTextures.push(this._bumpTexture);
  33162. }
  33163. if (this._lightmapTexture) {
  33164. activeTextures.push(this._lightmapTexture);
  33165. }
  33166. if (this._refractionTexture) {
  33167. activeTextures.push(this._refractionTexture);
  33168. }
  33169. return activeTextures;
  33170. };
  33171. PBRMaterial.prototype.hasTexture = function (texture) {
  33172. if (_super.prototype.hasTexture.call(this, texture)) {
  33173. return true;
  33174. }
  33175. if (this._albedoTexture === texture) {
  33176. return true;
  33177. }
  33178. if (this._ambientTexture === texture) {
  33179. return true;
  33180. }
  33181. if (this._opacityTexture === texture) {
  33182. return true;
  33183. }
  33184. if (this._reflectionTexture === texture) {
  33185. return true;
  33186. }
  33187. if (this._reflectivityTexture === texture) {
  33188. return true;
  33189. }
  33190. if (this._metallicTexture === texture) {
  33191. return true;
  33192. }
  33193. if (this._microSurfaceTexture === texture) {
  33194. return true;
  33195. }
  33196. if (this._bumpTexture === texture) {
  33197. return true;
  33198. }
  33199. if (this._lightmapTexture === texture) {
  33200. return true;
  33201. }
  33202. if (this._refractionTexture === texture) {
  33203. return true;
  33204. }
  33205. return false;
  33206. };
  33207. PBRMaterial.prototype.clone = function (name) {
  33208. var _this = this;
  33209. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33210. };
  33211. PBRMaterial.prototype.serialize = function () {
  33212. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33213. serializationObject.customType = "BABYLON.PBRMaterial";
  33214. return serializationObject;
  33215. };
  33216. // Statics
  33217. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33218. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33219. };
  33220. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33221. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33222. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33223. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33224. __decorate([
  33225. BABYLON.serialize(),
  33226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33227. ], PBRMaterial.prototype, "directIntensity", void 0);
  33228. __decorate([
  33229. BABYLON.serialize(),
  33230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33231. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33232. __decorate([
  33233. BABYLON.serialize(),
  33234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33235. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33236. __decorate([
  33237. BABYLON.serialize(),
  33238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33239. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33240. __decorate([
  33241. BABYLON.serialize(),
  33242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33243. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33244. __decorate([
  33245. BABYLON.serializeAsTexture(),
  33246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33247. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33248. __decorate([
  33249. BABYLON.serializeAsTexture(),
  33250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33251. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33252. __decorate([
  33253. BABYLON.serialize(),
  33254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33255. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33256. __decorate([
  33257. BABYLON.serializeAsTexture(),
  33258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33259. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33260. __decorate([
  33261. BABYLON.serializeAsTexture(),
  33262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33263. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33264. __decorate([
  33265. BABYLON.serializeAsTexture(),
  33266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33267. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33268. __decorate([
  33269. BABYLON.serializeAsTexture(),
  33270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33271. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33272. __decorate([
  33273. BABYLON.serializeAsTexture(),
  33274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33275. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33276. __decorate([
  33277. BABYLON.serialize(),
  33278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33279. ], PBRMaterial.prototype, "metallic", void 0);
  33280. __decorate([
  33281. BABYLON.serialize(),
  33282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33283. ], PBRMaterial.prototype, "roughness", void 0);
  33284. __decorate([
  33285. BABYLON.serializeAsTexture(),
  33286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33287. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33288. __decorate([
  33289. BABYLON.serializeAsTexture(),
  33290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33291. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33292. __decorate([
  33293. BABYLON.serializeAsTexture(),
  33294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33295. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33296. __decorate([
  33297. BABYLON.serializeAsTexture(),
  33298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33299. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33300. __decorate([
  33301. BABYLON.serializeAsColor3("ambient"),
  33302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33303. ], PBRMaterial.prototype, "ambientColor", void 0);
  33304. __decorate([
  33305. BABYLON.serializeAsColor3("albedo"),
  33306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33307. ], PBRMaterial.prototype, "albedoColor", void 0);
  33308. __decorate([
  33309. BABYLON.serializeAsColor3("reflectivity"),
  33310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33311. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33312. __decorate([
  33313. BABYLON.serializeAsColor3("reflection"),
  33314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33315. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33316. __decorate([
  33317. BABYLON.serializeAsColor3("emissive"),
  33318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33319. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33320. __decorate([
  33321. BABYLON.serialize(),
  33322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33323. ], PBRMaterial.prototype, "microSurface", void 0);
  33324. __decorate([
  33325. BABYLON.serialize(),
  33326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33327. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33328. __decorate([
  33329. BABYLON.serialize(),
  33330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33331. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33332. __decorate([
  33333. BABYLON.serialize(),
  33334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33335. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33336. __decorate([
  33337. BABYLON.serialize(),
  33338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33339. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33340. __decorate([
  33341. BABYLON.serialize(),
  33342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33343. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33344. __decorate([
  33345. BABYLON.serialize(),
  33346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33347. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33348. __decorate([
  33349. BABYLON.serialize(),
  33350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33351. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33352. __decorate([
  33353. BABYLON.serialize(),
  33354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33355. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33356. __decorate([
  33357. BABYLON.serialize(),
  33358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33359. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33360. __decorate([
  33361. BABYLON.serialize(),
  33362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33363. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33364. __decorate([
  33365. BABYLON.serialize(),
  33366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33367. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33368. __decorate([
  33369. BABYLON.serialize(),
  33370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33371. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33372. __decorate([
  33373. BABYLON.serialize(),
  33374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33375. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33376. __decorate([
  33377. BABYLON.serialize(),
  33378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33379. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33380. __decorate([
  33381. BABYLON.serialize(),
  33382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33383. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33384. __decorate([
  33385. BABYLON.serialize(),
  33386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33387. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33388. __decorate([
  33389. BABYLON.serialize(),
  33390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33391. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33392. __decorate([
  33393. BABYLON.serialize(),
  33394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33395. ], PBRMaterial.prototype, "useParallax", void 0);
  33396. __decorate([
  33397. BABYLON.serialize(),
  33398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33399. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33400. __decorate([
  33401. BABYLON.serialize(),
  33402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33403. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  33404. __decorate([
  33405. BABYLON.serialize(),
  33406. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33407. ], PBRMaterial.prototype, "disableLighting", void 0);
  33408. __decorate([
  33409. BABYLON.serialize(),
  33410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33411. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  33412. __decorate([
  33413. BABYLON.serialize(),
  33414. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33415. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33416. __decorate([
  33417. BABYLON.serialize(),
  33418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33419. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33420. __decorate([
  33421. BABYLON.serialize(),
  33422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33423. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33424. __decorate([
  33425. BABYLON.serialize(),
  33426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33427. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33428. __decorate([
  33429. BABYLON.serialize(),
  33430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33431. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33432. __decorate([
  33433. BABYLON.serialize(),
  33434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33435. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33436. __decorate([
  33437. BABYLON.serializeAsTexture(),
  33438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33439. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33440. __decorate([
  33441. BABYLON.serialize(),
  33442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33443. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33444. return PBRMaterial;
  33445. }(BABYLON.PBRBaseMaterial));
  33446. BABYLON.PBRMaterial = PBRMaterial;
  33447. })(BABYLON || (BABYLON = {}));
  33448. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33449. var BABYLON;
  33450. (function (BABYLON) {
  33451. /**
  33452. * The PBR material of BJS following the metal roughness convention.
  33453. *
  33454. * This fits to the PBR convention in the GLTF definition:
  33455. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33456. */
  33457. var PBRMetallicRoughnessMaterial = (function (_super) {
  33458. __extends(PBRMetallicRoughnessMaterial, _super);
  33459. /**
  33460. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33461. *
  33462. * @param name The material name
  33463. * @param scene The scene the material will be use in.
  33464. */
  33465. function PBRMetallicRoughnessMaterial(name, scene) {
  33466. var _this = _super.call(this, name, scene) || this;
  33467. _this._useRoughnessFromMetallicTextureAlpha = false;
  33468. _this._useRoughnessFromMetallicTextureGreen = true;
  33469. _this._useMetallnessFromMetallicTextureBlue = true;
  33470. return _this;
  33471. }
  33472. /**
  33473. * Return the currrent class name of the material.
  33474. */
  33475. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33476. return "PBRMetallicRoughnessMaterial";
  33477. };
  33478. /**
  33479. * Return the active textures of the material.
  33480. */
  33481. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33482. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33483. if (this.baseTexture) {
  33484. activeTextures.push(this.baseTexture);
  33485. }
  33486. if (this.metallicRoughnessTexture) {
  33487. activeTextures.push(this.metallicRoughnessTexture);
  33488. }
  33489. return activeTextures;
  33490. };
  33491. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33492. if (_super.prototype.hasTexture.call(this, texture)) {
  33493. return true;
  33494. }
  33495. if (this.baseTexture === texture) {
  33496. return true;
  33497. }
  33498. if (this.metallicRoughnessTexture === texture) {
  33499. return true;
  33500. }
  33501. return false;
  33502. };
  33503. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33504. var _this = this;
  33505. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33506. };
  33507. /**
  33508. * Serialize the material to a parsable JSON object.
  33509. */
  33510. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  33511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33512. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  33513. return serializationObject;
  33514. };
  33515. /**
  33516. * Parses a JSON object correponding to the serialize function.
  33517. */
  33518. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33519. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33520. };
  33521. __decorate([
  33522. BABYLON.serializeAsColor3(),
  33523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33524. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33525. __decorate([
  33526. BABYLON.serializeAsTexture(),
  33527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33528. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33529. __decorate([
  33530. BABYLON.serialize(),
  33531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33532. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33533. __decorate([
  33534. BABYLON.serialize(),
  33535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33536. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33537. __decorate([
  33538. BABYLON.serializeAsTexture(),
  33539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33540. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33541. return PBRMetallicRoughnessMaterial;
  33542. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33543. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33544. })(BABYLON || (BABYLON = {}));
  33545. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33546. var BABYLON;
  33547. (function (BABYLON) {
  33548. /**
  33549. * The PBR material of BJS following the specular glossiness convention.
  33550. *
  33551. * This fits to the PBR convention in the GLTF definition:
  33552. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  33553. */
  33554. var PBRSpecularGlossinessMaterial = (function (_super) {
  33555. __extends(PBRSpecularGlossinessMaterial, _super);
  33556. /**
  33557. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  33558. *
  33559. * @param name The material name
  33560. * @param scene The scene the material will be use in.
  33561. */
  33562. function PBRSpecularGlossinessMaterial(name, scene) {
  33563. var _this = _super.call(this, name, scene) || this;
  33564. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  33565. return _this;
  33566. }
  33567. /**
  33568. * Return the currrent class name of the material.
  33569. */
  33570. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  33571. return "PBRSpecularGlossinessMaterial";
  33572. };
  33573. /**
  33574. * Return the active textures of the material.
  33575. */
  33576. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  33577. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33578. if (this.diffuseTexture) {
  33579. activeTextures.push(this.diffuseTexture);
  33580. }
  33581. if (this.specularGlossinessTexture) {
  33582. activeTextures.push(this.specularGlossinessTexture);
  33583. }
  33584. return activeTextures;
  33585. };
  33586. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  33587. if (_super.prototype.hasTexture.call(this, texture)) {
  33588. return true;
  33589. }
  33590. if (this.diffuseTexture === texture) {
  33591. return true;
  33592. }
  33593. if (this.specularGlossinessTexture === texture) {
  33594. return true;
  33595. }
  33596. return false;
  33597. };
  33598. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  33599. var _this = this;
  33600. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  33601. };
  33602. /**
  33603. * Serialize the material to a parsable JSON object.
  33604. */
  33605. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  33606. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33607. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  33608. return serializationObject;
  33609. };
  33610. /**
  33611. * Parses a JSON object correponding to the serialize function.
  33612. */
  33613. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  33614. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  33615. };
  33616. __decorate([
  33617. BABYLON.serializeAsColor3("diffuse"),
  33618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33619. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  33620. __decorate([
  33621. BABYLON.serializeAsTexture(),
  33622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33623. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  33624. __decorate([
  33625. BABYLON.serializeAsColor3("specular"),
  33626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  33627. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  33628. __decorate([
  33629. BABYLON.serialize(),
  33630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  33631. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  33632. __decorate([
  33633. BABYLON.serializeAsTexture(),
  33634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  33635. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  33636. return PBRSpecularGlossinessMaterial;
  33637. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33638. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  33639. })(BABYLON || (BABYLON = {}));
  33640. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  33641. var BABYLON;
  33642. (function (BABYLON) {
  33643. BABYLON.CameraInputTypes = {};
  33644. var CameraInputsManager = (function () {
  33645. function CameraInputsManager(camera) {
  33646. this.attached = {};
  33647. this.camera = camera;
  33648. this.checkInputs = function () { };
  33649. }
  33650. CameraInputsManager.prototype.add = function (input) {
  33651. var type = input.getSimpleName();
  33652. if (this.attached[type]) {
  33653. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  33654. return;
  33655. }
  33656. this.attached[type] = input;
  33657. input.camera = this.camera;
  33658. //for checkInputs, we are dynamically creating a function
  33659. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  33660. if (input.checkInputs) {
  33661. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33662. }
  33663. if (this.attachedElement) {
  33664. input.attachControl(this.attachedElement);
  33665. }
  33666. };
  33667. CameraInputsManager.prototype.remove = function (inputToRemove) {
  33668. for (var cam in this.attached) {
  33669. var input = this.attached[cam];
  33670. if (input === inputToRemove) {
  33671. input.detachControl(this.attachedElement);
  33672. input.camera = null;
  33673. delete this.attached[cam];
  33674. this.rebuildInputCheck();
  33675. }
  33676. }
  33677. };
  33678. CameraInputsManager.prototype.removeByType = function (inputType) {
  33679. for (var cam in this.attached) {
  33680. var input = this.attached[cam];
  33681. if (input.getClassName() === inputType) {
  33682. input.detachControl(this.attachedElement);
  33683. input.camera = null;
  33684. delete this.attached[cam];
  33685. this.rebuildInputCheck();
  33686. }
  33687. }
  33688. };
  33689. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  33690. var current = this.checkInputs;
  33691. return function () {
  33692. current();
  33693. fn();
  33694. };
  33695. };
  33696. CameraInputsManager.prototype.attachInput = function (input) {
  33697. input.attachControl(this.attachedElement, this.noPreventDefault);
  33698. };
  33699. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  33700. if (this.attachedElement) {
  33701. return;
  33702. }
  33703. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33704. this.attachedElement = element;
  33705. this.noPreventDefault = noPreventDefault;
  33706. for (var cam in this.attached) {
  33707. var input = this.attached[cam];
  33708. this.attached[cam].attachControl(element, noPreventDefault);
  33709. }
  33710. };
  33711. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  33712. if (disconnect === void 0) { disconnect = false; }
  33713. if (this.attachedElement !== element) {
  33714. return;
  33715. }
  33716. for (var cam in this.attached) {
  33717. var input = this.attached[cam];
  33718. this.attached[cam].detachControl(element);
  33719. if (disconnect) {
  33720. this.attached[cam].camera = null;
  33721. }
  33722. }
  33723. this.attachedElement = null;
  33724. };
  33725. CameraInputsManager.prototype.rebuildInputCheck = function () {
  33726. this.checkInputs = function () { };
  33727. for (var cam in this.attached) {
  33728. var input = this.attached[cam];
  33729. if (input.checkInputs) {
  33730. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33731. }
  33732. }
  33733. };
  33734. CameraInputsManager.prototype.clear = function () {
  33735. if (this.attachedElement) {
  33736. this.detachElement(this.attachedElement, true);
  33737. }
  33738. this.attached = {};
  33739. this.attachedElement = null;
  33740. this.checkInputs = function () { };
  33741. };
  33742. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  33743. var inputs = {};
  33744. for (var cam in this.attached) {
  33745. var input = this.attached[cam];
  33746. var res = BABYLON.SerializationHelper.Serialize(input);
  33747. inputs[input.getClassName()] = res;
  33748. }
  33749. serializedCamera.inputsmgr = inputs;
  33750. };
  33751. CameraInputsManager.prototype.parse = function (parsedCamera) {
  33752. var parsedInputs = parsedCamera.inputsmgr;
  33753. if (parsedInputs) {
  33754. this.clear();
  33755. for (var n in parsedInputs) {
  33756. var construct = BABYLON.CameraInputTypes[n];
  33757. if (construct) {
  33758. var parsedinput = parsedInputs[n];
  33759. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  33760. this.add(input);
  33761. }
  33762. }
  33763. }
  33764. else {
  33765. //2016-03-08 this part is for managing backward compatibility
  33766. for (var n in this.attached) {
  33767. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  33768. if (construct) {
  33769. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  33770. this.remove(this.attached[n]);
  33771. this.add(input);
  33772. }
  33773. }
  33774. }
  33775. };
  33776. return CameraInputsManager;
  33777. }());
  33778. BABYLON.CameraInputsManager = CameraInputsManager;
  33779. })(BABYLON || (BABYLON = {}));
  33780. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  33781. var BABYLON;
  33782. (function (BABYLON) {
  33783. var FreeCameraMouseInput = (function () {
  33784. function FreeCameraMouseInput(touchEnabled) {
  33785. if (touchEnabled === void 0) { touchEnabled = true; }
  33786. this.touchEnabled = touchEnabled;
  33787. this.buttons = [0, 1, 2];
  33788. this.angularSensibility = 2000.0;
  33789. }
  33790. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  33791. var _this = this;
  33792. var engine = this.camera.getEngine();
  33793. if (!this._pointerInput) {
  33794. this._pointerInput = function (p, s) {
  33795. var evt = p.event;
  33796. if (!_this.touchEnabled && evt.pointerType === "touch") {
  33797. return;
  33798. }
  33799. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  33800. return;
  33801. }
  33802. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  33803. try {
  33804. evt.srcElement.setPointerCapture(evt.pointerId);
  33805. }
  33806. catch (e) {
  33807. //Nothing to do with the error. Execution will continue.
  33808. }
  33809. _this.previousPosition = {
  33810. x: evt.clientX,
  33811. y: evt.clientY
  33812. };
  33813. if (!noPreventDefault) {
  33814. evt.preventDefault();
  33815. element.focus();
  33816. }
  33817. }
  33818. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  33819. try {
  33820. evt.srcElement.releasePointerCapture(evt.pointerId);
  33821. }
  33822. catch (e) {
  33823. //Nothing to do with the error.
  33824. }
  33825. _this.previousPosition = null;
  33826. if (!noPreventDefault) {
  33827. evt.preventDefault();
  33828. }
  33829. }
  33830. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  33831. if (!_this.previousPosition || engine.isPointerLock) {
  33832. return;
  33833. }
  33834. var offsetX = evt.clientX - _this.previousPosition.x;
  33835. var offsetY = evt.clientY - _this.previousPosition.y;
  33836. if (_this.camera.getScene().useRightHandedSystem) {
  33837. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33838. }
  33839. else {
  33840. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33841. }
  33842. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33843. _this.previousPosition = {
  33844. x: evt.clientX,
  33845. y: evt.clientY
  33846. };
  33847. if (!noPreventDefault) {
  33848. evt.preventDefault();
  33849. }
  33850. }
  33851. };
  33852. }
  33853. this._onMouseMove = function (evt) {
  33854. if (!engine.isPointerLock) {
  33855. return;
  33856. }
  33857. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  33858. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  33859. if (_this.camera.getScene().useRightHandedSystem) {
  33860. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33861. }
  33862. else {
  33863. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33864. }
  33865. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33866. _this.previousPosition = null;
  33867. if (!noPreventDefault) {
  33868. evt.preventDefault();
  33869. }
  33870. };
  33871. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  33872. element.addEventListener("mousemove", this._onMouseMove, false);
  33873. };
  33874. FreeCameraMouseInput.prototype.detachControl = function (element) {
  33875. if (this._observer && element) {
  33876. this.camera.getScene().onPointerObservable.remove(this._observer);
  33877. element.removeEventListener("mousemove", this._onMouseMove);
  33878. this._observer = null;
  33879. this._onMouseMove = null;
  33880. this.previousPosition = null;
  33881. }
  33882. };
  33883. FreeCameraMouseInput.prototype.getClassName = function () {
  33884. return "FreeCameraMouseInput";
  33885. };
  33886. FreeCameraMouseInput.prototype.getSimpleName = function () {
  33887. return "mouse";
  33888. };
  33889. __decorate([
  33890. BABYLON.serialize()
  33891. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  33892. __decorate([
  33893. BABYLON.serialize()
  33894. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  33895. return FreeCameraMouseInput;
  33896. }());
  33897. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  33898. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  33899. })(BABYLON || (BABYLON = {}));
  33900. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  33901. var BABYLON;
  33902. (function (BABYLON) {
  33903. var FreeCameraKeyboardMoveInput = (function () {
  33904. function FreeCameraKeyboardMoveInput() {
  33905. this._keys = [];
  33906. this.keysUp = [38];
  33907. this.keysDown = [40];
  33908. this.keysLeft = [37];
  33909. this.keysRight = [39];
  33910. }
  33911. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  33912. var _this = this;
  33913. if (!this._onKeyDown) {
  33914. element.tabIndex = 1;
  33915. this._onKeyDown = function (evt) {
  33916. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33917. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33918. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33919. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33920. var index = _this._keys.indexOf(evt.keyCode);
  33921. if (index === -1) {
  33922. _this._keys.push(evt.keyCode);
  33923. }
  33924. if (!noPreventDefault) {
  33925. evt.preventDefault();
  33926. }
  33927. }
  33928. };
  33929. this._onKeyUp = function (evt) {
  33930. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33931. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33932. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33933. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33934. var index = _this._keys.indexOf(evt.keyCode);
  33935. if (index >= 0) {
  33936. _this._keys.splice(index, 1);
  33937. }
  33938. if (!noPreventDefault) {
  33939. evt.preventDefault();
  33940. }
  33941. }
  33942. };
  33943. element.addEventListener("keydown", this._onKeyDown, false);
  33944. element.addEventListener("keyup", this._onKeyUp, false);
  33945. BABYLON.Tools.RegisterTopRootEvents([
  33946. { name: "blur", handler: this._onLostFocus }
  33947. ]);
  33948. }
  33949. };
  33950. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  33951. if (this._onKeyDown) {
  33952. element.removeEventListener("keydown", this._onKeyDown);
  33953. element.removeEventListener("keyup", this._onKeyUp);
  33954. BABYLON.Tools.UnregisterTopRootEvents([
  33955. { name: "blur", handler: this._onLostFocus }
  33956. ]);
  33957. this._keys = [];
  33958. this._onKeyDown = null;
  33959. this._onKeyUp = null;
  33960. }
  33961. };
  33962. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  33963. if (this._onKeyDown) {
  33964. var camera = this.camera;
  33965. // Keyboard
  33966. for (var index = 0; index < this._keys.length; index++) {
  33967. var keyCode = this._keys[index];
  33968. var speed = camera._computeLocalCameraSpeed();
  33969. if (this.keysLeft.indexOf(keyCode) !== -1) {
  33970. camera._localDirection.copyFromFloats(-speed, 0, 0);
  33971. }
  33972. else if (this.keysUp.indexOf(keyCode) !== -1) {
  33973. camera._localDirection.copyFromFloats(0, 0, speed);
  33974. }
  33975. else if (this.keysRight.indexOf(keyCode) !== -1) {
  33976. camera._localDirection.copyFromFloats(speed, 0, 0);
  33977. }
  33978. else if (this.keysDown.indexOf(keyCode) !== -1) {
  33979. camera._localDirection.copyFromFloats(0, 0, -speed);
  33980. }
  33981. if (camera.getScene().useRightHandedSystem) {
  33982. camera._localDirection.z *= -1;
  33983. }
  33984. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  33985. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  33986. camera.cameraDirection.addInPlace(camera._transformedDirection);
  33987. }
  33988. }
  33989. };
  33990. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  33991. return "FreeCameraKeyboardMoveInput";
  33992. };
  33993. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  33994. this._keys = [];
  33995. };
  33996. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  33997. return "keyboard";
  33998. };
  33999. __decorate([
  34000. BABYLON.serialize()
  34001. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34002. __decorate([
  34003. BABYLON.serialize()
  34004. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34005. __decorate([
  34006. BABYLON.serialize()
  34007. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34008. __decorate([
  34009. BABYLON.serialize()
  34010. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34011. return FreeCameraKeyboardMoveInput;
  34012. }());
  34013. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34014. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34015. })(BABYLON || (BABYLON = {}));
  34016. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34017. var BABYLON;
  34018. (function (BABYLON) {
  34019. var FreeCameraInputsManager = (function (_super) {
  34020. __extends(FreeCameraInputsManager, _super);
  34021. function FreeCameraInputsManager(camera) {
  34022. return _super.call(this, camera) || this;
  34023. }
  34024. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34025. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34026. return this;
  34027. };
  34028. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34029. if (touchEnabled === void 0) { touchEnabled = true; }
  34030. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34031. return this;
  34032. };
  34033. FreeCameraInputsManager.prototype.addGamepad = function () {
  34034. this.add(new BABYLON.FreeCameraGamepadInput());
  34035. return this;
  34036. };
  34037. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34038. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34039. return this;
  34040. };
  34041. FreeCameraInputsManager.prototype.addTouch = function () {
  34042. this.add(new BABYLON.FreeCameraTouchInput());
  34043. return this;
  34044. };
  34045. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34046. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34047. return this;
  34048. };
  34049. return FreeCameraInputsManager;
  34050. }(BABYLON.CameraInputsManager));
  34051. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34052. })(BABYLON || (BABYLON = {}));
  34053. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34054. /// <reference path="babylon.camera.ts" />
  34055. var BABYLON;
  34056. (function (BABYLON) {
  34057. var TargetCamera = (function (_super) {
  34058. __extends(TargetCamera, _super);
  34059. function TargetCamera(name, position, scene) {
  34060. var _this = _super.call(this, name, position, scene) || this;
  34061. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34062. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34063. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34064. _this.speed = 2.0;
  34065. _this.noRotationConstraint = false;
  34066. _this.lockedTarget = null;
  34067. _this._currentTarget = BABYLON.Vector3.Zero();
  34068. _this._viewMatrix = BABYLON.Matrix.Zero();
  34069. _this._camMatrix = BABYLON.Matrix.Zero();
  34070. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34071. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34072. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34073. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34074. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34075. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34076. _this._tempMatrix = BABYLON.Matrix.Zero();
  34077. return _this;
  34078. }
  34079. TargetCamera.prototype.getFrontPosition = function (distance) {
  34080. var direction = this.getTarget().subtract(this.position);
  34081. direction.normalize();
  34082. direction.scaleInPlace(distance);
  34083. return this.globalPosition.add(direction);
  34084. };
  34085. TargetCamera.prototype._getLockedTargetPosition = function () {
  34086. if (!this.lockedTarget) {
  34087. return null;
  34088. }
  34089. if (this.lockedTarget.absolutePosition) {
  34090. this.lockedTarget.computeWorldMatrix();
  34091. }
  34092. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34093. };
  34094. // Cache
  34095. TargetCamera.prototype._initCache = function () {
  34096. _super.prototype._initCache.call(this);
  34097. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34098. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34099. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34100. };
  34101. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34102. if (!ignoreParentClass) {
  34103. _super.prototype._updateCache.call(this);
  34104. }
  34105. var lockedTargetPosition = this._getLockedTargetPosition();
  34106. if (!lockedTargetPosition) {
  34107. this._cache.lockedTarget = null;
  34108. }
  34109. else {
  34110. if (!this._cache.lockedTarget) {
  34111. this._cache.lockedTarget = lockedTargetPosition.clone();
  34112. }
  34113. else {
  34114. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34115. }
  34116. }
  34117. this._cache.rotation.copyFrom(this.rotation);
  34118. if (this.rotationQuaternion)
  34119. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34120. };
  34121. // Synchronized
  34122. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34123. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34124. return false;
  34125. }
  34126. var lockedTargetPosition = this._getLockedTargetPosition();
  34127. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34128. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34129. };
  34130. // Methods
  34131. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34132. var engine = this.getEngine();
  34133. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34134. };
  34135. // Target
  34136. TargetCamera.prototype.setTarget = function (target) {
  34137. this.upVector.normalize();
  34138. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34139. this._camMatrix.invert();
  34140. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34141. var vDir = target.subtract(this.position);
  34142. if (vDir.x >= 0.0) {
  34143. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34144. }
  34145. else {
  34146. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34147. }
  34148. this.rotation.z = 0;
  34149. if (isNaN(this.rotation.x)) {
  34150. this.rotation.x = 0;
  34151. }
  34152. if (isNaN(this.rotation.y)) {
  34153. this.rotation.y = 0;
  34154. }
  34155. if (isNaN(this.rotation.z)) {
  34156. this.rotation.z = 0;
  34157. }
  34158. if (this.rotationQuaternion) {
  34159. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34160. }
  34161. };
  34162. /**
  34163. * Return the current target position of the camera. This value is expressed in local space.
  34164. */
  34165. TargetCamera.prototype.getTarget = function () {
  34166. return this._currentTarget;
  34167. };
  34168. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34169. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34170. };
  34171. TargetCamera.prototype._updatePosition = function () {
  34172. if (this.parent) {
  34173. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34174. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34175. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34176. return;
  34177. }
  34178. this.position.addInPlace(this.cameraDirection);
  34179. };
  34180. TargetCamera.prototype._checkInputs = function () {
  34181. var needToMove = this._decideIfNeedsToMove();
  34182. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34183. // Move
  34184. if (needToMove) {
  34185. this._updatePosition();
  34186. }
  34187. // Rotate
  34188. if (needToRotate) {
  34189. this.rotation.x += this.cameraRotation.x;
  34190. this.rotation.y += this.cameraRotation.y;
  34191. //rotate, if quaternion is set and rotation was used
  34192. if (this.rotationQuaternion) {
  34193. var len = this.rotation.lengthSquared();
  34194. if (len) {
  34195. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34196. }
  34197. }
  34198. if (!this.noRotationConstraint) {
  34199. var limit = (Math.PI / 2) * 0.95;
  34200. if (this.rotation.x > limit)
  34201. this.rotation.x = limit;
  34202. if (this.rotation.x < -limit)
  34203. this.rotation.x = -limit;
  34204. }
  34205. }
  34206. // Inertia
  34207. if (needToMove) {
  34208. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34209. this.cameraDirection.x = 0;
  34210. }
  34211. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34212. this.cameraDirection.y = 0;
  34213. }
  34214. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34215. this.cameraDirection.z = 0;
  34216. }
  34217. this.cameraDirection.scaleInPlace(this.inertia);
  34218. }
  34219. if (needToRotate) {
  34220. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34221. this.cameraRotation.x = 0;
  34222. }
  34223. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34224. this.cameraRotation.y = 0;
  34225. }
  34226. this.cameraRotation.scaleInPlace(this.inertia);
  34227. }
  34228. _super.prototype._checkInputs.call(this);
  34229. };
  34230. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34231. if (this.rotationQuaternion) {
  34232. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34233. //update the up vector!
  34234. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34235. }
  34236. else {
  34237. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34238. }
  34239. };
  34240. TargetCamera.prototype._getViewMatrix = function () {
  34241. if (!this.lockedTarget) {
  34242. // Compute
  34243. this._updateCameraRotationMatrix();
  34244. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34245. // Computing target and final matrix
  34246. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34247. }
  34248. else {
  34249. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34250. }
  34251. if (this.getScene().useRightHandedSystem) {
  34252. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34253. }
  34254. else {
  34255. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34256. }
  34257. return this._viewMatrix;
  34258. };
  34259. /**
  34260. * @override
  34261. * Override Camera.createRigCamera
  34262. */
  34263. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34264. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34265. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34266. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34267. if (!this.rotationQuaternion) {
  34268. this.rotationQuaternion = new BABYLON.Quaternion();
  34269. }
  34270. rigCamera._cameraRigParams = {};
  34271. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34272. }
  34273. return rigCamera;
  34274. }
  34275. return null;
  34276. };
  34277. /**
  34278. * @override
  34279. * Override Camera._updateRigCameras
  34280. */
  34281. TargetCamera.prototype._updateRigCameras = function () {
  34282. var camLeft = this._rigCameras[0];
  34283. var camRight = this._rigCameras[1];
  34284. switch (this.cameraRigMode) {
  34285. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34286. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34287. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34288. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34289. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34290. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34291. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34292. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34293. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34294. camLeft.setTarget(this.getTarget());
  34295. camRight.setTarget(this.getTarget());
  34296. break;
  34297. case BABYLON.Camera.RIG_MODE_VR:
  34298. if (camLeft.rotationQuaternion) {
  34299. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34300. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34301. }
  34302. else {
  34303. camLeft.rotation.copyFrom(this.rotation);
  34304. camRight.rotation.copyFrom(this.rotation);
  34305. }
  34306. camLeft.position.copyFrom(this.position);
  34307. camRight.position.copyFrom(this.position);
  34308. break;
  34309. }
  34310. _super.prototype._updateRigCameras.call(this);
  34311. };
  34312. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34313. if (!this._rigCamTransformMatrix) {
  34314. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34315. }
  34316. var target = this.getTarget();
  34317. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34318. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34319. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34320. };
  34321. TargetCamera.prototype.getClassName = function () {
  34322. return "TargetCamera";
  34323. };
  34324. __decorate([
  34325. BABYLON.serializeAsVector3()
  34326. ], TargetCamera.prototype, "rotation", void 0);
  34327. __decorate([
  34328. BABYLON.serialize()
  34329. ], TargetCamera.prototype, "speed", void 0);
  34330. __decorate([
  34331. BABYLON.serializeAsMeshReference("lockedTargetId")
  34332. ], TargetCamera.prototype, "lockedTarget", void 0);
  34333. return TargetCamera;
  34334. }(BABYLON.Camera));
  34335. BABYLON.TargetCamera = TargetCamera;
  34336. })(BABYLON || (BABYLON = {}));
  34337. //# sourceMappingURL=babylon.targetCamera.js.map
  34338. var BABYLON;
  34339. (function (BABYLON) {
  34340. var FreeCamera = (function (_super) {
  34341. __extends(FreeCamera, _super);
  34342. function FreeCamera(name, position, scene) {
  34343. var _this = _super.call(this, name, position, scene) || this;
  34344. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34345. _this.checkCollisions = false;
  34346. _this.applyGravity = false;
  34347. _this._needMoveForGravity = false;
  34348. _this._oldPosition = BABYLON.Vector3.Zero();
  34349. _this._diffPosition = BABYLON.Vector3.Zero();
  34350. _this._newPosition = BABYLON.Vector3.Zero();
  34351. // Collisions
  34352. _this._collisionMask = -1;
  34353. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34354. if (collidedMesh === void 0) { collidedMesh = null; }
  34355. //TODO move this to the collision coordinator!
  34356. if (_this.getScene().workerCollisions)
  34357. newPosition.multiplyInPlace(_this._collider.radius);
  34358. var updatePosition = function (newPos) {
  34359. _this._newPosition.copyFrom(newPos);
  34360. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34361. var oldPosition = _this.position.clone();
  34362. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34363. _this.position.addInPlace(_this._diffPosition);
  34364. if (_this.onCollide && collidedMesh) {
  34365. _this.onCollide(collidedMesh);
  34366. }
  34367. }
  34368. };
  34369. updatePosition(newPosition);
  34370. };
  34371. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34372. _this.inputs.addKeyboard().addMouse();
  34373. return _this;
  34374. }
  34375. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  34376. //-- begin properties for backward compatibility for inputs
  34377. get: function () {
  34378. var mouse = this.inputs.attached["mouse"];
  34379. if (mouse)
  34380. return mouse.angularSensibility;
  34381. },
  34382. set: function (value) {
  34383. var mouse = this.inputs.attached["mouse"];
  34384. if (mouse)
  34385. mouse.angularSensibility = value;
  34386. },
  34387. enumerable: true,
  34388. configurable: true
  34389. });
  34390. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  34391. get: function () {
  34392. var keyboard = this.inputs.attached["keyboard"];
  34393. if (keyboard)
  34394. return keyboard.keysUp;
  34395. },
  34396. set: function (value) {
  34397. var keyboard = this.inputs.attached["keyboard"];
  34398. if (keyboard)
  34399. keyboard.keysUp = value;
  34400. },
  34401. enumerable: true,
  34402. configurable: true
  34403. });
  34404. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  34405. get: function () {
  34406. var keyboard = this.inputs.attached["keyboard"];
  34407. if (keyboard)
  34408. return keyboard.keysDown;
  34409. },
  34410. set: function (value) {
  34411. var keyboard = this.inputs.attached["keyboard"];
  34412. if (keyboard)
  34413. keyboard.keysDown = value;
  34414. },
  34415. enumerable: true,
  34416. configurable: true
  34417. });
  34418. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34419. get: function () {
  34420. var keyboard = this.inputs.attached["keyboard"];
  34421. if (keyboard)
  34422. return keyboard.keysLeft;
  34423. },
  34424. set: function (value) {
  34425. var keyboard = this.inputs.attached["keyboard"];
  34426. if (keyboard)
  34427. keyboard.keysLeft = value;
  34428. },
  34429. enumerable: true,
  34430. configurable: true
  34431. });
  34432. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34433. get: function () {
  34434. var keyboard = this.inputs.attached["keyboard"];
  34435. if (keyboard)
  34436. return keyboard.keysRight;
  34437. },
  34438. set: function (value) {
  34439. var keyboard = this.inputs.attached["keyboard"];
  34440. if (keyboard)
  34441. keyboard.keysRight = value;
  34442. },
  34443. enumerable: true,
  34444. configurable: true
  34445. });
  34446. // Controls
  34447. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34448. this.inputs.attachElement(element, noPreventDefault);
  34449. };
  34450. FreeCamera.prototype.detachControl = function (element) {
  34451. this.inputs.detachElement(element);
  34452. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34453. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34454. };
  34455. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34456. get: function () {
  34457. return this._collisionMask;
  34458. },
  34459. set: function (mask) {
  34460. this._collisionMask = !isNaN(mask) ? mask : -1;
  34461. },
  34462. enumerable: true,
  34463. configurable: true
  34464. });
  34465. FreeCamera.prototype._collideWithWorld = function (direction) {
  34466. var globalPosition;
  34467. if (this.parent) {
  34468. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34469. }
  34470. else {
  34471. globalPosition = this.position;
  34472. }
  34473. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34474. if (!this._collider) {
  34475. this._collider = new BABYLON.Collider();
  34476. }
  34477. this._collider.radius = this.ellipsoid;
  34478. this._collider.collisionMask = this._collisionMask;
  34479. //no need for clone, as long as gravity is not on.
  34480. var actualDirection = direction;
  34481. //add gravity to the direction to prevent the dual-collision checking
  34482. if (this.applyGravity) {
  34483. //this prevents mending with cameraDirection, a global variable of the free camera class.
  34484. actualDirection = direction.add(this.getScene().gravity);
  34485. }
  34486. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDirection, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34487. };
  34488. FreeCamera.prototype._checkInputs = function () {
  34489. if (!this._localDirection) {
  34490. this._localDirection = BABYLON.Vector3.Zero();
  34491. this._transformedDirection = BABYLON.Vector3.Zero();
  34492. }
  34493. this.inputs.checkInputs();
  34494. _super.prototype._checkInputs.call(this);
  34495. };
  34496. FreeCamera.prototype._decideIfNeedsToMove = function () {
  34497. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34498. };
  34499. FreeCamera.prototype._updatePosition = function () {
  34500. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  34501. this._collideWithWorld(this.cameraDirection);
  34502. }
  34503. else {
  34504. _super.prototype._updatePosition.call(this);
  34505. }
  34506. };
  34507. FreeCamera.prototype.dispose = function () {
  34508. this.inputs.clear();
  34509. _super.prototype.dispose.call(this);
  34510. };
  34511. FreeCamera.prototype.getClassName = function () {
  34512. return "FreeCamera";
  34513. };
  34514. __decorate([
  34515. BABYLON.serializeAsVector3()
  34516. ], FreeCamera.prototype, "ellipsoid", void 0);
  34517. __decorate([
  34518. BABYLON.serialize()
  34519. ], FreeCamera.prototype, "checkCollisions", void 0);
  34520. __decorate([
  34521. BABYLON.serialize()
  34522. ], FreeCamera.prototype, "applyGravity", void 0);
  34523. return FreeCamera;
  34524. }(BABYLON.TargetCamera));
  34525. BABYLON.FreeCamera = FreeCamera;
  34526. })(BABYLON || (BABYLON = {}));
  34527. //# sourceMappingURL=babylon.freeCamera.js.map
  34528. var BABYLON;
  34529. (function (BABYLON) {
  34530. var ArcRotateCameraKeyboardMoveInput = (function () {
  34531. function ArcRotateCameraKeyboardMoveInput() {
  34532. this._keys = [];
  34533. this.keysUp = [38];
  34534. this.keysDown = [40];
  34535. this.keysLeft = [37];
  34536. this.keysRight = [39];
  34537. }
  34538. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34539. var _this = this;
  34540. element.tabIndex = 1;
  34541. this._onKeyDown = function (evt) {
  34542. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34543. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34544. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34545. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34546. var index = _this._keys.indexOf(evt.keyCode);
  34547. if (index === -1) {
  34548. _this._keys.push(evt.keyCode);
  34549. }
  34550. if (evt.preventDefault) {
  34551. if (!noPreventDefault) {
  34552. evt.preventDefault();
  34553. }
  34554. }
  34555. }
  34556. };
  34557. this._onKeyUp = function (evt) {
  34558. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34559. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34560. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34561. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34562. var index = _this._keys.indexOf(evt.keyCode);
  34563. if (index >= 0) {
  34564. _this._keys.splice(index, 1);
  34565. }
  34566. if (evt.preventDefault) {
  34567. if (!noPreventDefault) {
  34568. evt.preventDefault();
  34569. }
  34570. }
  34571. }
  34572. };
  34573. this._onLostFocus = function () {
  34574. _this._keys = [];
  34575. };
  34576. this._onFocus = function () {
  34577. element.addEventListener("keydown", _this._onKeyDown, false);
  34578. element.addEventListener("keyup", _this._onKeyUp, false);
  34579. };
  34580. this._onBlur = function () {
  34581. element.removeEventListener("keydown", _this._onKeyDown);
  34582. element.removeEventListener("keyup", _this._onKeyUp);
  34583. };
  34584. element.addEventListener("focus", this._onFocus);
  34585. element.addEventListener("blur", this._onBlur);
  34586. BABYLON.Tools.RegisterTopRootEvents([
  34587. { name: "blur", handler: this._onLostFocus }
  34588. ]);
  34589. };
  34590. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34591. if (element && this._onBlur) {
  34592. this._onBlur();
  34593. element.removeEventListener("focus", this._onFocus);
  34594. element.removeEventListener("blur", this._onBlur);
  34595. }
  34596. BABYLON.Tools.UnregisterTopRootEvents([
  34597. { name: "blur", handler: this._onLostFocus }
  34598. ]);
  34599. this._keys = [];
  34600. this._onKeyDown = null;
  34601. this._onKeyUp = null;
  34602. this._onLostFocus = null;
  34603. this._onBlur = null;
  34604. this._onFocus = null;
  34605. };
  34606. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34607. if (this._onKeyDown) {
  34608. var camera = this.camera;
  34609. for (var index = 0; index < this._keys.length; index++) {
  34610. var keyCode = this._keys[index];
  34611. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34612. camera.inertialAlphaOffset -= 0.01;
  34613. }
  34614. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34615. camera.inertialBetaOffset -= 0.01;
  34616. }
  34617. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34618. camera.inertialAlphaOffset += 0.01;
  34619. }
  34620. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34621. camera.inertialBetaOffset += 0.01;
  34622. }
  34623. }
  34624. }
  34625. };
  34626. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  34627. return "ArcRotateCameraKeyboardMoveInput";
  34628. };
  34629. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34630. return "keyboard";
  34631. };
  34632. __decorate([
  34633. BABYLON.serialize()
  34634. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34635. __decorate([
  34636. BABYLON.serialize()
  34637. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34638. __decorate([
  34639. BABYLON.serialize()
  34640. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34641. __decorate([
  34642. BABYLON.serialize()
  34643. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34644. return ArcRotateCameraKeyboardMoveInput;
  34645. }());
  34646. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  34647. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  34648. })(BABYLON || (BABYLON = {}));
  34649. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  34650. var BABYLON;
  34651. (function (BABYLON) {
  34652. var ArcRotateCameraMouseWheelInput = (function () {
  34653. function ArcRotateCameraMouseWheelInput() {
  34654. this.wheelPrecision = 3.0;
  34655. }
  34656. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  34657. var _this = this;
  34658. this._wheel = function (p, s) {
  34659. //sanity check - this should be a PointerWheel event.
  34660. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  34661. return;
  34662. var event = p.event;
  34663. var delta = 0;
  34664. if (event.wheelDelta) {
  34665. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  34666. }
  34667. else if (event.detail) {
  34668. delta = -event.detail / _this.wheelPrecision;
  34669. }
  34670. if (delta)
  34671. _this.camera.inertialRadiusOffset += delta;
  34672. if (event.preventDefault) {
  34673. if (!noPreventDefault) {
  34674. event.preventDefault();
  34675. }
  34676. }
  34677. };
  34678. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  34679. };
  34680. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  34681. if (this._observer && element) {
  34682. this.camera.getScene().onPointerObservable.remove(this._observer);
  34683. this._observer = null;
  34684. this._wheel = null;
  34685. }
  34686. };
  34687. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  34688. return "ArcRotateCameraMouseWheelInput";
  34689. };
  34690. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  34691. return "mousewheel";
  34692. };
  34693. __decorate([
  34694. BABYLON.serialize()
  34695. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  34696. return ArcRotateCameraMouseWheelInput;
  34697. }());
  34698. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  34699. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  34700. })(BABYLON || (BABYLON = {}));
  34701. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  34702. var BABYLON;
  34703. (function (BABYLON) {
  34704. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  34705. var ArcRotateCameraPointersInput = (function () {
  34706. function ArcRotateCameraPointersInput() {
  34707. this.buttons = [0, 1, 2];
  34708. this.angularSensibilityX = 1000.0;
  34709. this.angularSensibilityY = 1000.0;
  34710. this.pinchPrecision = 6.0;
  34711. this.panningSensibility = 50.0;
  34712. this._isPanClick = false;
  34713. this.pinchInwards = true;
  34714. }
  34715. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  34716. var _this = this;
  34717. var engine = this.camera.getEngine();
  34718. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  34719. var pointA, pointB;
  34720. var previousPinchDistance = 0;
  34721. this._pointerInput = function (p, s) {
  34722. var evt = p.event;
  34723. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34724. return;
  34725. }
  34726. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34727. try {
  34728. evt.srcElement.setPointerCapture(evt.pointerId);
  34729. }
  34730. catch (e) {
  34731. //Nothing to do with the error. Execution will continue.
  34732. }
  34733. // Manage panning with pan button click
  34734. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  34735. // manage pointers
  34736. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  34737. if (pointA === undefined) {
  34738. pointA = cacheSoloPointer;
  34739. }
  34740. else if (pointB === undefined) {
  34741. pointB = cacheSoloPointer;
  34742. }
  34743. if (!noPreventDefault) {
  34744. evt.preventDefault();
  34745. element.focus();
  34746. }
  34747. }
  34748. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34749. try {
  34750. evt.srcElement.releasePointerCapture(evt.pointerId);
  34751. }
  34752. catch (e) {
  34753. //Nothing to do with the error.
  34754. }
  34755. cacheSoloPointer = null;
  34756. previousPinchDistance = 0;
  34757. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  34758. //but emptying completly pointers collection is required to fix a bug on iPhone :
  34759. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  34760. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  34761. pointA = pointB = undefined;
  34762. if (!noPreventDefault) {
  34763. evt.preventDefault();
  34764. }
  34765. }
  34766. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34767. if (!noPreventDefault) {
  34768. evt.preventDefault();
  34769. }
  34770. // One button down
  34771. if (pointA && pointB === undefined) {
  34772. if (_this.panningSensibility !== 0 &&
  34773. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  34774. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  34775. _this.camera
  34776. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  34777. _this.camera
  34778. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  34779. }
  34780. else {
  34781. var offsetX = evt.clientX - cacheSoloPointer.x;
  34782. var offsetY = evt.clientY - cacheSoloPointer.y;
  34783. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34784. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34785. }
  34786. cacheSoloPointer.x = evt.clientX;
  34787. cacheSoloPointer.y = evt.clientY;
  34788. }
  34789. else if (pointA && pointB) {
  34790. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  34791. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  34792. ed.x = evt.clientX;
  34793. ed.y = evt.clientY;
  34794. var direction = _this.pinchInwards ? 1 : -1;
  34795. var distX = pointA.x - pointB.x;
  34796. var distY = pointA.y - pointB.y;
  34797. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  34798. if (previousPinchDistance === 0) {
  34799. previousPinchDistance = pinchSquaredDistance;
  34800. return;
  34801. }
  34802. if (pinchSquaredDistance !== previousPinchDistance) {
  34803. _this.camera
  34804. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  34805. (_this.pinchPrecision *
  34806. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  34807. direction);
  34808. previousPinchDistance = pinchSquaredDistance;
  34809. }
  34810. }
  34811. }
  34812. };
  34813. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34814. this._onContextMenu = function (evt) {
  34815. evt.preventDefault();
  34816. };
  34817. if (!this.camera._useCtrlForPanning) {
  34818. element.addEventListener("contextmenu", this._onContextMenu, false);
  34819. }
  34820. this._onLostFocus = function () {
  34821. //this._keys = [];
  34822. pointA = pointB = undefined;
  34823. previousPinchDistance = 0;
  34824. cacheSoloPointer = null;
  34825. };
  34826. this._onMouseMove = function (evt) {
  34827. if (!engine.isPointerLock) {
  34828. return;
  34829. }
  34830. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34831. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34832. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34833. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34834. if (!noPreventDefault) {
  34835. evt.preventDefault();
  34836. }
  34837. };
  34838. this._onGestureStart = function (e) {
  34839. if (window.MSGesture === undefined) {
  34840. return;
  34841. }
  34842. if (!_this._MSGestureHandler) {
  34843. _this._MSGestureHandler = new MSGesture();
  34844. _this._MSGestureHandler.target = element;
  34845. }
  34846. _this._MSGestureHandler.addPointer(e.pointerId);
  34847. };
  34848. this._onGesture = function (e) {
  34849. _this.camera.radius *= e.scale;
  34850. if (e.preventDefault) {
  34851. if (!noPreventDefault) {
  34852. e.stopPropagation();
  34853. e.preventDefault();
  34854. }
  34855. }
  34856. };
  34857. element.addEventListener("mousemove", this._onMouseMove, false);
  34858. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  34859. element.addEventListener("MSGestureChange", this._onGesture, false);
  34860. BABYLON.Tools.RegisterTopRootEvents([
  34861. { name: "blur", handler: this._onLostFocus }
  34862. ]);
  34863. };
  34864. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  34865. BABYLON.Tools.UnregisterTopRootEvents([
  34866. { name: "blur", handler: this._onLostFocus }
  34867. ]);
  34868. if (element && this._observer) {
  34869. this.camera.getScene().onPointerObservable.remove(this._observer);
  34870. this._observer = null;
  34871. element.removeEventListener("contextmenu", this._onContextMenu);
  34872. element.removeEventListener("mousemove", this._onMouseMove);
  34873. element.removeEventListener("MSPointerDown", this._onGestureStart);
  34874. element.removeEventListener("MSGestureChange", this._onGesture);
  34875. this._isPanClick = false;
  34876. this.pinchInwards = true;
  34877. this._onMouseMove = null;
  34878. this._onGestureStart = null;
  34879. this._onGesture = null;
  34880. this._MSGestureHandler = null;
  34881. this._onLostFocus = null;
  34882. this._onContextMenu = null;
  34883. }
  34884. };
  34885. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  34886. return "ArcRotateCameraPointersInput";
  34887. };
  34888. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  34889. return "pointers";
  34890. };
  34891. __decorate([
  34892. BABYLON.serialize()
  34893. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  34894. __decorate([
  34895. BABYLON.serialize()
  34896. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  34897. __decorate([
  34898. BABYLON.serialize()
  34899. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  34900. __decorate([
  34901. BABYLON.serialize()
  34902. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  34903. __decorate([
  34904. BABYLON.serialize()
  34905. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  34906. return ArcRotateCameraPointersInput;
  34907. }());
  34908. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  34909. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  34910. })(BABYLON || (BABYLON = {}));
  34911. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  34912. /// <reference path="babylon.targetCamera.ts" />
  34913. /// <reference path="..\Tools\babylon.tools.ts" />
  34914. var BABYLON;
  34915. (function (BABYLON) {
  34916. var ArcRotateCamera = (function (_super) {
  34917. __extends(ArcRotateCamera, _super);
  34918. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  34919. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  34920. _this.inertialAlphaOffset = 0;
  34921. _this.inertialBetaOffset = 0;
  34922. _this.inertialRadiusOffset = 0;
  34923. _this.lowerAlphaLimit = null;
  34924. _this.upperAlphaLimit = null;
  34925. _this.lowerBetaLimit = 0.01;
  34926. _this.upperBetaLimit = Math.PI;
  34927. _this.lowerRadiusLimit = null;
  34928. _this.upperRadiusLimit = null;
  34929. _this.inertialPanningX = 0;
  34930. _this.inertialPanningY = 0;
  34931. _this.panningInertia = 0.9;
  34932. //-- end properties for backward compatibility for inputs
  34933. _this.zoomOnFactor = 1;
  34934. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  34935. _this.allowUpsideDown = true;
  34936. _this._viewMatrix = new BABYLON.Matrix();
  34937. // Panning
  34938. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  34939. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  34940. _this.checkCollisions = false;
  34941. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  34942. _this._previousPosition = BABYLON.Vector3.Zero();
  34943. _this._collisionVelocity = BABYLON.Vector3.Zero();
  34944. _this._newPosition = BABYLON.Vector3.Zero();
  34945. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34946. if (collidedMesh === void 0) { collidedMesh = null; }
  34947. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  34948. newPosition.multiplyInPlace(_this._collider.radius);
  34949. }
  34950. if (!collidedMesh) {
  34951. _this._previousPosition.copyFrom(_this.position);
  34952. }
  34953. else {
  34954. _this.setPosition(newPosition);
  34955. if (_this.onCollide) {
  34956. _this.onCollide(collidedMesh);
  34957. }
  34958. }
  34959. // Recompute because of constraints
  34960. var cosa = Math.cos(_this.alpha);
  34961. var sina = Math.sin(_this.alpha);
  34962. var cosb = Math.cos(_this.beta);
  34963. var sinb = Math.sin(_this.beta);
  34964. if (sinb === 0) {
  34965. sinb = 0.0001;
  34966. }
  34967. var target = _this._getTargetPosition();
  34968. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  34969. _this.position.copyFrom(_this._newPosition);
  34970. var up = _this.upVector;
  34971. if (_this.allowUpsideDown && _this.beta < 0) {
  34972. up = up.clone();
  34973. up = up.negate();
  34974. }
  34975. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  34976. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  34977. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  34978. _this._collisionTriggered = false;
  34979. };
  34980. _this._target = BABYLON.Vector3.Zero();
  34981. if (target) {
  34982. _this.setTarget(target);
  34983. }
  34984. _this.alpha = alpha;
  34985. _this.beta = beta;
  34986. _this.radius = radius;
  34987. _this.getViewMatrix();
  34988. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  34989. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  34990. return _this;
  34991. }
  34992. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  34993. get: function () {
  34994. return this._target;
  34995. },
  34996. set: function (value) {
  34997. this.setTarget(value);
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35003. //-- begin properties for backward compatibility for inputs
  35004. get: function () {
  35005. var pointers = this.inputs.attached["pointers"];
  35006. if (pointers)
  35007. return pointers.angularSensibilityX;
  35008. },
  35009. set: function (value) {
  35010. var pointers = this.inputs.attached["pointers"];
  35011. if (pointers) {
  35012. pointers.angularSensibilityX = value;
  35013. }
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35019. get: function () {
  35020. var pointers = this.inputs.attached["pointers"];
  35021. if (pointers)
  35022. return pointers.angularSensibilityY;
  35023. },
  35024. set: function (value) {
  35025. var pointers = this.inputs.attached["pointers"];
  35026. if (pointers) {
  35027. pointers.angularSensibilityY = value;
  35028. }
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35034. get: function () {
  35035. var pointers = this.inputs.attached["pointers"];
  35036. if (pointers)
  35037. return pointers.pinchPrecision;
  35038. },
  35039. set: function (value) {
  35040. var pointers = this.inputs.attached["pointers"];
  35041. if (pointers) {
  35042. pointers.pinchPrecision = value;
  35043. }
  35044. },
  35045. enumerable: true,
  35046. configurable: true
  35047. });
  35048. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35049. get: function () {
  35050. var pointers = this.inputs.attached["pointers"];
  35051. if (pointers)
  35052. return pointers.panningSensibility;
  35053. },
  35054. set: function (value) {
  35055. var pointers = this.inputs.attached["pointers"];
  35056. if (pointers) {
  35057. pointers.panningSensibility = value;
  35058. }
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35064. get: function () {
  35065. var keyboard = this.inputs.attached["keyboard"];
  35066. if (keyboard)
  35067. return keyboard.keysUp;
  35068. },
  35069. set: function (value) {
  35070. var keyboard = this.inputs.attached["keyboard"];
  35071. if (keyboard)
  35072. keyboard.keysUp = value;
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35078. get: function () {
  35079. var keyboard = this.inputs.attached["keyboard"];
  35080. if (keyboard)
  35081. return keyboard.keysDown;
  35082. },
  35083. set: function (value) {
  35084. var keyboard = this.inputs.attached["keyboard"];
  35085. if (keyboard)
  35086. keyboard.keysDown = value;
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35092. get: function () {
  35093. var keyboard = this.inputs.attached["keyboard"];
  35094. if (keyboard)
  35095. return keyboard.keysLeft;
  35096. },
  35097. set: function (value) {
  35098. var keyboard = this.inputs.attached["keyboard"];
  35099. if (keyboard)
  35100. keyboard.keysLeft = value;
  35101. },
  35102. enumerable: true,
  35103. configurable: true
  35104. });
  35105. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35106. get: function () {
  35107. var keyboard = this.inputs.attached["keyboard"];
  35108. if (keyboard)
  35109. return keyboard.keysRight;
  35110. },
  35111. set: function (value) {
  35112. var keyboard = this.inputs.attached["keyboard"];
  35113. if (keyboard)
  35114. keyboard.keysRight = value;
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35120. get: function () {
  35121. var mousewheel = this.inputs.attached["mousewheel"];
  35122. if (mousewheel)
  35123. return mousewheel.wheelPrecision;
  35124. },
  35125. set: function (value) {
  35126. var mousewheel = this.inputs.attached["mousewheel"];
  35127. if (mousewheel)
  35128. mousewheel.wheelPrecision = value;
  35129. },
  35130. enumerable: true,
  35131. configurable: true
  35132. });
  35133. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35134. get: function () {
  35135. return this._bouncingBehavior;
  35136. },
  35137. enumerable: true,
  35138. configurable: true
  35139. });
  35140. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35141. get: function () {
  35142. return this._bouncingBehavior != null;
  35143. },
  35144. set: function (value) {
  35145. if (value === this.useBouncingBehavior) {
  35146. return;
  35147. }
  35148. if (value) {
  35149. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35150. this.addBehavior(this._bouncingBehavior);
  35151. }
  35152. else {
  35153. this.removeBehavior(this._bouncingBehavior);
  35154. this._bouncingBehavior = null;
  35155. }
  35156. },
  35157. enumerable: true,
  35158. configurable: true
  35159. });
  35160. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35161. get: function () {
  35162. return this._framingBehavior;
  35163. },
  35164. enumerable: true,
  35165. configurable: true
  35166. });
  35167. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35168. get: function () {
  35169. return this._framingBehavior != null;
  35170. },
  35171. set: function (value) {
  35172. if (value === this.useFramingBehavior) {
  35173. return;
  35174. }
  35175. if (value) {
  35176. this._framingBehavior = new BABYLON.FramingBehavior();
  35177. this.addBehavior(this._framingBehavior);
  35178. }
  35179. else {
  35180. this.removeBehavior(this._framingBehavior);
  35181. this._framingBehavior = null;
  35182. }
  35183. },
  35184. enumerable: true,
  35185. configurable: true
  35186. });
  35187. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35188. get: function () {
  35189. return this._autoRotationBehavior;
  35190. },
  35191. enumerable: true,
  35192. configurable: true
  35193. });
  35194. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35195. get: function () {
  35196. return this._autoRotationBehavior != null;
  35197. },
  35198. set: function (value) {
  35199. if (value === this.useAutoRotationBehavior) {
  35200. return;
  35201. }
  35202. if (value) {
  35203. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35204. this.addBehavior(this._autoRotationBehavior);
  35205. }
  35206. else {
  35207. this.removeBehavior(this._autoRotationBehavior);
  35208. this._autoRotationBehavior = null;
  35209. }
  35210. },
  35211. enumerable: true,
  35212. configurable: true
  35213. });
  35214. // Cache
  35215. ArcRotateCamera.prototype._initCache = function () {
  35216. _super.prototype._initCache.call(this);
  35217. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35218. this._cache.alpha = undefined;
  35219. this._cache.beta = undefined;
  35220. this._cache.radius = undefined;
  35221. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35222. };
  35223. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35224. if (!ignoreParentClass) {
  35225. _super.prototype._updateCache.call(this);
  35226. }
  35227. this._cache._target.copyFrom(this._getTargetPosition());
  35228. this._cache.alpha = this.alpha;
  35229. this._cache.beta = this.beta;
  35230. this._cache.radius = this.radius;
  35231. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35232. };
  35233. ArcRotateCamera.prototype._getTargetPosition = function () {
  35234. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35235. var pos = this._targetHost.getAbsolutePosition();
  35236. if (this._targetBoundingCenter) {
  35237. pos.addToRef(this._targetBoundingCenter, this._target);
  35238. }
  35239. else {
  35240. this._target.copyFrom(pos);
  35241. }
  35242. }
  35243. var lockedTargetPosition = this._getLockedTargetPosition();
  35244. if (lockedTargetPosition) {
  35245. return lockedTargetPosition;
  35246. }
  35247. return this._target;
  35248. };
  35249. // Synchronized
  35250. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  35251. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  35252. return false;
  35253. return this._cache._target.equals(this._getTargetPosition())
  35254. && this._cache.alpha === this.alpha
  35255. && this._cache.beta === this.beta
  35256. && this._cache.radius === this.radius
  35257. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  35258. };
  35259. // Methods
  35260. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  35261. var _this = this;
  35262. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  35263. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  35264. this._useCtrlForPanning = useCtrlForPanning;
  35265. this._panningMouseButton = panningMouseButton;
  35266. this.inputs.attachElement(element, noPreventDefault);
  35267. this._reset = function () {
  35268. _this.inertialAlphaOffset = 0;
  35269. _this.inertialBetaOffset = 0;
  35270. _this.inertialRadiusOffset = 0;
  35271. };
  35272. };
  35273. ArcRotateCamera.prototype.detachControl = function (element) {
  35274. this.inputs.detachElement(element);
  35275. if (this._reset) {
  35276. this._reset();
  35277. }
  35278. };
  35279. ArcRotateCamera.prototype._checkInputs = function () {
  35280. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  35281. if (this._collisionTriggered) {
  35282. return;
  35283. }
  35284. this.inputs.checkInputs();
  35285. // Inertia
  35286. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  35287. if (this.getScene().useRightHandedSystem) {
  35288. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35289. }
  35290. else {
  35291. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35292. }
  35293. this.beta += this.inertialBetaOffset;
  35294. this.radius -= this.inertialRadiusOffset;
  35295. this.inertialAlphaOffset *= this.inertia;
  35296. this.inertialBetaOffset *= this.inertia;
  35297. this.inertialRadiusOffset *= this.inertia;
  35298. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  35299. this.inertialAlphaOffset = 0;
  35300. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  35301. this.inertialBetaOffset = 0;
  35302. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  35303. this.inertialRadiusOffset = 0;
  35304. }
  35305. // Panning inertia
  35306. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  35307. if (!this._localDirection) {
  35308. this._localDirection = BABYLON.Vector3.Zero();
  35309. this._transformedDirection = BABYLON.Vector3.Zero();
  35310. }
  35311. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  35312. this._localDirection.multiplyInPlace(this.panningAxis);
  35313. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  35314. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  35315. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  35316. if (!this.panningAxis.y) {
  35317. this._transformedDirection.y = 0;
  35318. }
  35319. if (!this._targetHost) {
  35320. this._target.addInPlace(this._transformedDirection);
  35321. }
  35322. this.inertialPanningX *= this.panningInertia;
  35323. this.inertialPanningY *= this.panningInertia;
  35324. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  35325. this.inertialPanningX = 0;
  35326. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  35327. this.inertialPanningY = 0;
  35328. }
  35329. // Limits
  35330. this._checkLimits();
  35331. _super.prototype._checkInputs.call(this);
  35332. };
  35333. ArcRotateCamera.prototype._checkLimits = function () {
  35334. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  35335. if (this.allowUpsideDown && this.beta > Math.PI) {
  35336. this.beta = this.beta - (2 * Math.PI);
  35337. }
  35338. }
  35339. else {
  35340. if (this.beta < this.lowerBetaLimit) {
  35341. this.beta = this.lowerBetaLimit;
  35342. }
  35343. }
  35344. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  35345. if (this.allowUpsideDown && this.beta < -Math.PI) {
  35346. this.beta = this.beta + (2 * Math.PI);
  35347. }
  35348. }
  35349. else {
  35350. if (this.beta > this.upperBetaLimit) {
  35351. this.beta = this.upperBetaLimit;
  35352. }
  35353. }
  35354. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  35355. this.alpha = this.lowerAlphaLimit;
  35356. }
  35357. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  35358. this.alpha = this.upperAlphaLimit;
  35359. }
  35360. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  35361. this.radius = this.lowerRadiusLimit;
  35362. }
  35363. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  35364. this.radius = this.upperRadiusLimit;
  35365. }
  35366. };
  35367. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  35368. var radiusv3 = this.position.subtract(this._getTargetPosition());
  35369. this.radius = radiusv3.length();
  35370. if (this.radius === 0) {
  35371. this.radius = 0.0001; // Just to avoid division by zero
  35372. }
  35373. // Alpha
  35374. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  35375. if (radiusv3.z < 0) {
  35376. this.alpha = 2 * Math.PI - this.alpha;
  35377. }
  35378. // Beta
  35379. this.beta = Math.acos(radiusv3.y / this.radius);
  35380. this._checkLimits();
  35381. };
  35382. ArcRotateCamera.prototype.setPosition = function (position) {
  35383. if (this.position.equals(position)) {
  35384. return;
  35385. }
  35386. this.position.copyFrom(position);
  35387. this.rebuildAnglesAndRadius();
  35388. };
  35389. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  35390. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  35391. if (allowSamePosition === void 0) { allowSamePosition = false; }
  35392. if (target.getBoundingInfo) {
  35393. if (toBoundingCenter) {
  35394. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  35395. }
  35396. else {
  35397. this._targetBoundingCenter = null;
  35398. }
  35399. this._targetHost = target;
  35400. this._target = this._getTargetPosition();
  35401. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  35402. }
  35403. else {
  35404. var newTarget = target;
  35405. var currentTarget = this._getTargetPosition();
  35406. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  35407. return;
  35408. }
  35409. this._targetHost = null;
  35410. this._target = newTarget;
  35411. this._targetBoundingCenter = null;
  35412. this.onMeshTargetChangedObservable.notifyObservers(null);
  35413. }
  35414. this.rebuildAnglesAndRadius();
  35415. };
  35416. ArcRotateCamera.prototype._getViewMatrix = function () {
  35417. // Compute
  35418. var cosa = Math.cos(this.alpha);
  35419. var sina = Math.sin(this.alpha);
  35420. var cosb = Math.cos(this.beta);
  35421. var sinb = Math.sin(this.beta);
  35422. if (sinb === 0) {
  35423. sinb = 0.0001;
  35424. }
  35425. var target = this._getTargetPosition();
  35426. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  35427. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  35428. if (!this._collider) {
  35429. this._collider = new BABYLON.Collider();
  35430. }
  35431. this._collider.radius = this.collisionRadius;
  35432. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  35433. this._collisionTriggered = true;
  35434. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35435. }
  35436. else {
  35437. this.position.copyFrom(this._newPosition);
  35438. var up = this.upVector;
  35439. if (this.allowUpsideDown && sinb < 0) {
  35440. up = up.clone();
  35441. up = up.negate();
  35442. }
  35443. if (this.getScene().useRightHandedSystem) {
  35444. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  35445. }
  35446. else {
  35447. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  35448. }
  35449. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  35450. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  35451. }
  35452. this._currentTarget = target;
  35453. return this._viewMatrix;
  35454. };
  35455. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  35456. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35457. meshes = meshes || this.getScene().meshes;
  35458. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  35459. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  35460. this.radius = distance * this.zoomOnFactor;
  35461. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  35462. };
  35463. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  35464. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35465. var meshesOrMinMaxVector;
  35466. var distance;
  35467. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  35468. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  35469. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  35470. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  35471. }
  35472. else {
  35473. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  35474. distance = meshesOrMinMaxVectorAndDistance.distance;
  35475. }
  35476. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  35477. if (!doNotUpdateMaxZ) {
  35478. this.maxZ = distance * 2;
  35479. }
  35480. };
  35481. /**
  35482. * @override
  35483. * Override Camera.createRigCamera
  35484. */
  35485. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  35486. var alphaShift;
  35487. switch (this.cameraRigMode) {
  35488. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35489. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35490. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35491. case BABYLON.Camera.RIG_MODE_VR:
  35492. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  35493. break;
  35494. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35495. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  35496. break;
  35497. }
  35498. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  35499. rigCam._cameraRigParams = {};
  35500. return rigCam;
  35501. };
  35502. /**
  35503. * @override
  35504. * Override Camera._updateRigCameras
  35505. */
  35506. ArcRotateCamera.prototype._updateRigCameras = function () {
  35507. var camLeft = this._rigCameras[0];
  35508. var camRight = this._rigCameras[1];
  35509. camLeft.beta = camRight.beta = this.beta;
  35510. camLeft.radius = camRight.radius = this.radius;
  35511. switch (this.cameraRigMode) {
  35512. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35513. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35514. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35515. case BABYLON.Camera.RIG_MODE_VR:
  35516. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35517. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35518. break;
  35519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35520. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35521. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35522. break;
  35523. }
  35524. _super.prototype._updateRigCameras.call(this);
  35525. };
  35526. ArcRotateCamera.prototype.dispose = function () {
  35527. this.inputs.clear();
  35528. _super.prototype.dispose.call(this);
  35529. };
  35530. ArcRotateCamera.prototype.getClassName = function () {
  35531. return "ArcRotateCamera";
  35532. };
  35533. __decorate([
  35534. BABYLON.serialize()
  35535. ], ArcRotateCamera.prototype, "alpha", void 0);
  35536. __decorate([
  35537. BABYLON.serialize()
  35538. ], ArcRotateCamera.prototype, "beta", void 0);
  35539. __decorate([
  35540. BABYLON.serialize()
  35541. ], ArcRotateCamera.prototype, "radius", void 0);
  35542. __decorate([
  35543. BABYLON.serializeAsVector3("target")
  35544. ], ArcRotateCamera.prototype, "_target", void 0);
  35545. __decorate([
  35546. BABYLON.serialize()
  35547. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  35548. __decorate([
  35549. BABYLON.serialize()
  35550. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  35551. __decorate([
  35552. BABYLON.serialize()
  35553. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  35554. __decorate([
  35555. BABYLON.serialize()
  35556. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  35557. __decorate([
  35558. BABYLON.serialize()
  35559. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  35560. __decorate([
  35561. BABYLON.serialize()
  35562. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  35563. __decorate([
  35564. BABYLON.serialize()
  35565. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  35566. __decorate([
  35567. BABYLON.serialize()
  35568. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  35569. __decorate([
  35570. BABYLON.serialize()
  35571. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  35572. __decorate([
  35573. BABYLON.serialize()
  35574. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  35575. __decorate([
  35576. BABYLON.serialize()
  35577. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  35578. __decorate([
  35579. BABYLON.serialize()
  35580. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  35581. __decorate([
  35582. BABYLON.serialize()
  35583. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  35584. __decorate([
  35585. BABYLON.serialize()
  35586. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  35587. return ArcRotateCamera;
  35588. }(BABYLON.TargetCamera));
  35589. BABYLON.ArcRotateCamera = ArcRotateCamera;
  35590. })(BABYLON || (BABYLON = {}));
  35591. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  35592. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  35593. var BABYLON;
  35594. (function (BABYLON) {
  35595. var ArcRotateCameraInputsManager = (function (_super) {
  35596. __extends(ArcRotateCameraInputsManager, _super);
  35597. function ArcRotateCameraInputsManager(camera) {
  35598. return _super.call(this, camera) || this;
  35599. }
  35600. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  35601. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  35602. return this;
  35603. };
  35604. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  35605. this.add(new BABYLON.ArcRotateCameraPointersInput());
  35606. return this;
  35607. };
  35608. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  35609. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  35610. return this;
  35611. };
  35612. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  35613. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  35614. return this;
  35615. };
  35616. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  35617. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  35618. return this;
  35619. };
  35620. return ArcRotateCameraInputsManager;
  35621. }(BABYLON.CameraInputsManager));
  35622. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  35623. })(BABYLON || (BABYLON = {}));
  35624. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  35625. var BABYLON;
  35626. (function (BABYLON) {
  35627. var HemisphericLight = (function (_super) {
  35628. __extends(HemisphericLight, _super);
  35629. /**
  35630. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  35631. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  35632. * The HemisphericLight can't cast shadows.
  35633. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35634. */
  35635. function HemisphericLight(name, direction, scene) {
  35636. var _this = _super.call(this, name, scene) || this;
  35637. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35638. _this.direction = direction || BABYLON.Vector3.Up();
  35639. return _this;
  35640. }
  35641. HemisphericLight.prototype._buildUniformLayout = function () {
  35642. this._uniformBuffer.addUniform("vLightData", 4);
  35643. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35644. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35645. this._uniformBuffer.addUniform("vLightGround", 3);
  35646. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35647. this._uniformBuffer.addUniform("depthValues", 2);
  35648. this._uniformBuffer.create();
  35649. };
  35650. /**
  35651. * Returns the string "HemisphericLight".
  35652. */
  35653. HemisphericLight.prototype.getClassName = function () {
  35654. return "HemisphericLight";
  35655. };
  35656. /**
  35657. * Sets the HemisphericLight direction towards the passed target (Vector3).
  35658. * Returns the updated direction.
  35659. */
  35660. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  35661. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  35662. return this.direction;
  35663. };
  35664. HemisphericLight.prototype.getShadowGenerator = function () {
  35665. return null;
  35666. };
  35667. /**
  35668. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  35669. * Returns the HemisphericLight.
  35670. */
  35671. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  35672. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35673. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  35674. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  35675. return this;
  35676. };
  35677. HemisphericLight.prototype._getWorldMatrix = function () {
  35678. if (!this._worldMatrix) {
  35679. this._worldMatrix = BABYLON.Matrix.Identity();
  35680. }
  35681. return this._worldMatrix;
  35682. };
  35683. /**
  35684. * Returns the integer 3.
  35685. */
  35686. HemisphericLight.prototype.getTypeID = function () {
  35687. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  35688. };
  35689. __decorate([
  35690. BABYLON.serializeAsColor3()
  35691. ], HemisphericLight.prototype, "groundColor", void 0);
  35692. __decorate([
  35693. BABYLON.serializeAsVector3()
  35694. ], HemisphericLight.prototype, "direction", void 0);
  35695. return HemisphericLight;
  35696. }(BABYLON.Light));
  35697. BABYLON.HemisphericLight = HemisphericLight;
  35698. })(BABYLON || (BABYLON = {}));
  35699. //# sourceMappingURL=babylon.hemisphericLight.js.map
  35700. var BABYLON;
  35701. (function (BABYLON) {
  35702. var ShadowLight = (function (_super) {
  35703. __extends(ShadowLight, _super);
  35704. function ShadowLight() {
  35705. var _this = _super !== null && _super.apply(this, arguments) || this;
  35706. _this._needProjectionMatrixCompute = true;
  35707. return _this;
  35708. }
  35709. Object.defineProperty(ShadowLight.prototype, "direction", {
  35710. get: function () {
  35711. return this._direction;
  35712. },
  35713. set: function (value) {
  35714. this._direction = value;
  35715. },
  35716. enumerable: true,
  35717. configurable: true
  35718. });
  35719. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  35720. get: function () {
  35721. return this._shadowMinZ;
  35722. },
  35723. set: function (value) {
  35724. this._shadowMinZ = value;
  35725. this.forceProjectionMatrixCompute();
  35726. },
  35727. enumerable: true,
  35728. configurable: true
  35729. });
  35730. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  35731. get: function () {
  35732. return this._shadowMaxZ;
  35733. },
  35734. set: function (value) {
  35735. this._shadowMaxZ = value;
  35736. this.forceProjectionMatrixCompute();
  35737. },
  35738. enumerable: true,
  35739. configurable: true
  35740. });
  35741. /**
  35742. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  35743. */
  35744. ShadowLight.prototype.computeTransformedInformation = function () {
  35745. if (this.parent && this.parent.getWorldMatrix) {
  35746. if (!this.transformedPosition) {
  35747. this.transformedPosition = BABYLON.Vector3.Zero();
  35748. }
  35749. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  35750. // In case the direction is present.
  35751. if (this.direction) {
  35752. if (!this.transformedDirection) {
  35753. this.transformedDirection = BABYLON.Vector3.Zero();
  35754. }
  35755. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  35756. }
  35757. return true;
  35758. }
  35759. return false;
  35760. };
  35761. /**
  35762. * Return the depth scale used for the shadow map.
  35763. */
  35764. ShadowLight.prototype.getDepthScale = function () {
  35765. return 50.0;
  35766. };
  35767. /**
  35768. * Returns the light direction (Vector3) for any passed face index.
  35769. */
  35770. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  35771. return this.transformedDirection ? this.transformedDirection : this.direction;
  35772. };
  35773. /**
  35774. * Returns the DirectionalLight absolute position in the World.
  35775. */
  35776. ShadowLight.prototype.getAbsolutePosition = function () {
  35777. return this.transformedPosition ? this.transformedPosition : this.position;
  35778. };
  35779. /**
  35780. * Sets the DirectionalLight direction toward the passed target (Vector3).
  35781. * Returns the updated DirectionalLight direction (Vector3).
  35782. */
  35783. ShadowLight.prototype.setDirectionToTarget = function (target) {
  35784. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  35785. return this.direction;
  35786. };
  35787. /**
  35788. * Returns the light rotation (Vector3).
  35789. */
  35790. ShadowLight.prototype.getRotation = function () {
  35791. this.direction.normalize();
  35792. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  35793. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  35794. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  35795. };
  35796. /**
  35797. * Boolean : false by default.
  35798. */
  35799. ShadowLight.prototype.needCube = function () {
  35800. return false;
  35801. };
  35802. /**
  35803. * Specifies wether or not the projection matrix should be recomputed this frame.
  35804. */
  35805. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  35806. return this._needProjectionMatrixCompute;
  35807. };
  35808. /**
  35809. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  35810. */
  35811. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  35812. this._needProjectionMatrixCompute = true;
  35813. };
  35814. /**
  35815. * Get the world matrix of the sahdow lights.
  35816. */
  35817. ShadowLight.prototype._getWorldMatrix = function () {
  35818. if (!this._worldMatrix) {
  35819. this._worldMatrix = BABYLON.Matrix.Identity();
  35820. }
  35821. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  35822. return this._worldMatrix;
  35823. };
  35824. /**
  35825. * Gets the minZ used for shadow according to both the scene and the light.
  35826. * @param activeCamera
  35827. */
  35828. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  35829. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  35830. };
  35831. /**
  35832. * Gets the maxZ used for shadow according to both the scene and the light.
  35833. * @param activeCamera
  35834. */
  35835. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  35836. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  35837. };
  35838. /**
  35839. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  35840. * Returns the light.
  35841. */
  35842. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35843. if (this.customProjectionMatrixBuilder) {
  35844. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  35845. }
  35846. else {
  35847. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35848. }
  35849. return this;
  35850. };
  35851. __decorate([
  35852. BABYLON.serializeAsVector3()
  35853. ], ShadowLight.prototype, "position", void 0);
  35854. __decorate([
  35855. BABYLON.serializeAsVector3()
  35856. ], ShadowLight.prototype, "direction", null);
  35857. __decorate([
  35858. BABYLON.serialize()
  35859. ], ShadowLight.prototype, "shadowMinZ", null);
  35860. __decorate([
  35861. BABYLON.serialize()
  35862. ], ShadowLight.prototype, "shadowMaxZ", null);
  35863. return ShadowLight;
  35864. }(BABYLON.Light));
  35865. BABYLON.ShadowLight = ShadowLight;
  35866. })(BABYLON || (BABYLON = {}));
  35867. //# sourceMappingURL=babylon.shadowLight.js.map
  35868. var BABYLON;
  35869. (function (BABYLON) {
  35870. var PointLight = (function (_super) {
  35871. __extends(PointLight, _super);
  35872. /**
  35873. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  35874. * A PointLight emits the light in every direction.
  35875. * It can cast shadows.
  35876. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  35877. * ```javascript
  35878. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  35879. * ```
  35880. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35881. */
  35882. function PointLight(name, position, scene) {
  35883. var _this = _super.call(this, name, scene) || this;
  35884. _this._shadowAngle = Math.PI / 2;
  35885. _this.position = position;
  35886. return _this;
  35887. }
  35888. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  35889. /**
  35890. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35891. * This specifies what angle the shadow will use to be created.
  35892. *
  35893. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35894. */
  35895. get: function () {
  35896. return this._shadowAngle;
  35897. },
  35898. /**
  35899. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35900. * This specifies what angle the shadow will use to be created.
  35901. *
  35902. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35903. */
  35904. set: function (value) {
  35905. this._shadowAngle = value;
  35906. this.forceProjectionMatrixCompute();
  35907. },
  35908. enumerable: true,
  35909. configurable: true
  35910. });
  35911. Object.defineProperty(PointLight.prototype, "direction", {
  35912. get: function () {
  35913. return this._direction;
  35914. },
  35915. /**
  35916. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35917. */
  35918. set: function (value) {
  35919. var previousNeedCube = this.needCube();
  35920. this._direction = value;
  35921. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  35922. this._shadowGenerator.recreateShadowMap();
  35923. }
  35924. },
  35925. enumerable: true,
  35926. configurable: true
  35927. });
  35928. /**
  35929. * Returns the string "PointLight"
  35930. */
  35931. PointLight.prototype.getClassName = function () {
  35932. return "PointLight";
  35933. };
  35934. /**
  35935. * Returns the integer 0.
  35936. */
  35937. PointLight.prototype.getTypeID = function () {
  35938. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  35939. };
  35940. /**
  35941. * Specifies wether or not the shadowmap should be a cube texture.
  35942. */
  35943. PointLight.prototype.needCube = function () {
  35944. return !this.direction;
  35945. };
  35946. /**
  35947. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  35948. */
  35949. PointLight.prototype.getShadowDirection = function (faceIndex) {
  35950. if (this.direction) {
  35951. return _super.prototype.getShadowDirection.call(this, faceIndex);
  35952. }
  35953. else {
  35954. switch (faceIndex) {
  35955. case 0:
  35956. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  35957. case 1:
  35958. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  35959. case 2:
  35960. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  35961. case 3:
  35962. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  35963. case 4:
  35964. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  35965. case 5:
  35966. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  35967. }
  35968. }
  35969. return BABYLON.Vector3.Zero();
  35970. };
  35971. /**
  35972. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  35973. * - fov = PI / 2
  35974. * - aspect ratio : 1.0
  35975. * - z-near and far equal to the active camera minZ and maxZ.
  35976. * Returns the PointLight.
  35977. */
  35978. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35979. var activeCamera = this.getScene().activeCamera;
  35980. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35981. };
  35982. PointLight.prototype._buildUniformLayout = function () {
  35983. this._uniformBuffer.addUniform("vLightData", 4);
  35984. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35985. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35986. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35987. this._uniformBuffer.addUniform("depthValues", 2);
  35988. this._uniformBuffer.create();
  35989. };
  35990. /**
  35991. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  35992. * Returns the PointLight.
  35993. */
  35994. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  35995. if (this.computeTransformedInformation()) {
  35996. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  35997. return this;
  35998. }
  35999. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36000. return this;
  36001. };
  36002. __decorate([
  36003. BABYLON.serialize()
  36004. ], PointLight.prototype, "shadowAngle", null);
  36005. return PointLight;
  36006. }(BABYLON.ShadowLight));
  36007. BABYLON.PointLight = PointLight;
  36008. })(BABYLON || (BABYLON = {}));
  36009. //# sourceMappingURL=babylon.pointLight.js.map
  36010. /// <reference path="babylon.light.ts" />
  36011. var BABYLON;
  36012. (function (BABYLON) {
  36013. var DirectionalLight = (function (_super) {
  36014. __extends(DirectionalLight, _super);
  36015. /**
  36016. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36017. * The directional light is emitted from everywhere in the given direction.
  36018. * It can cast shawdows.
  36019. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36020. */
  36021. function DirectionalLight(name, direction, scene) {
  36022. var _this = _super.call(this, name, scene) || this;
  36023. _this._shadowFrustumSize = 0;
  36024. _this._shadowOrthoScale = 0.5;
  36025. _this.autoUpdateExtends = true;
  36026. // Cache
  36027. _this._orthoLeft = Number.MAX_VALUE;
  36028. _this._orthoRight = Number.MIN_VALUE;
  36029. _this._orthoTop = Number.MIN_VALUE;
  36030. _this._orthoBottom = Number.MAX_VALUE;
  36031. _this.position = direction.scale(-1.0);
  36032. _this.direction = direction;
  36033. return _this;
  36034. }
  36035. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36036. /**
  36037. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36038. */
  36039. get: function () {
  36040. return this._shadowFrustumSize;
  36041. },
  36042. /**
  36043. * Specifies a fix frustum size for the shadow generation.
  36044. */
  36045. set: function (value) {
  36046. this._shadowFrustumSize = value;
  36047. this.forceProjectionMatrixCompute();
  36048. },
  36049. enumerable: true,
  36050. configurable: true
  36051. });
  36052. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36053. get: function () {
  36054. return this._shadowOrthoScale;
  36055. },
  36056. set: function (value) {
  36057. this._shadowOrthoScale = value;
  36058. this.forceProjectionMatrixCompute();
  36059. },
  36060. enumerable: true,
  36061. configurable: true
  36062. });
  36063. /**
  36064. * Returns the string "DirectionalLight".
  36065. */
  36066. DirectionalLight.prototype.getClassName = function () {
  36067. return "DirectionalLight";
  36068. };
  36069. /**
  36070. * Returns the integer 1.
  36071. */
  36072. DirectionalLight.prototype.getTypeID = function () {
  36073. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36074. };
  36075. /**
  36076. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36077. * Returns the DirectionalLight Shadow projection matrix.
  36078. */
  36079. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36080. if (this.shadowFrustumSize > 0) {
  36081. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36082. }
  36083. else {
  36084. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36085. }
  36086. };
  36087. /**
  36088. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36089. * Returns the DirectionalLight Shadow projection matrix.
  36090. */
  36091. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36092. var activeCamera = this.getScene().activeCamera;
  36093. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36094. };
  36095. /**
  36096. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36097. * Returns the DirectionalLight Shadow projection matrix.
  36098. */
  36099. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36100. var activeCamera = this.getScene().activeCamera;
  36101. // Check extends
  36102. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36103. var tempVector3 = BABYLON.Vector3.Zero();
  36104. this._orthoLeft = Number.MAX_VALUE;
  36105. this._orthoRight = Number.MIN_VALUE;
  36106. this._orthoTop = Number.MIN_VALUE;
  36107. this._orthoBottom = Number.MAX_VALUE;
  36108. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36109. var mesh = renderList[meshIndex];
  36110. if (!mesh) {
  36111. continue;
  36112. }
  36113. var boundingInfo = mesh.getBoundingInfo();
  36114. if (!boundingInfo) {
  36115. continue;
  36116. }
  36117. var boundingBox = boundingInfo.boundingBox;
  36118. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36119. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36120. if (tempVector3.x < this._orthoLeft)
  36121. this._orthoLeft = tempVector3.x;
  36122. if (tempVector3.y < this._orthoBottom)
  36123. this._orthoBottom = tempVector3.y;
  36124. if (tempVector3.x > this._orthoRight)
  36125. this._orthoRight = tempVector3.x;
  36126. if (tempVector3.y > this._orthoTop)
  36127. this._orthoTop = tempVector3.y;
  36128. }
  36129. }
  36130. }
  36131. var xOffset = this._orthoRight - this._orthoLeft;
  36132. var yOffset = this._orthoTop - this._orthoBottom;
  36133. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36134. };
  36135. DirectionalLight.prototype._buildUniformLayout = function () {
  36136. this._uniformBuffer.addUniform("vLightData", 4);
  36137. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36138. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36139. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36140. this._uniformBuffer.addUniform("depthValues", 2);
  36141. this._uniformBuffer.create();
  36142. };
  36143. /**
  36144. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36145. * Returns the DirectionalLight.
  36146. */
  36147. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36148. if (this.computeTransformedInformation()) {
  36149. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36150. return this;
  36151. }
  36152. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36153. return this;
  36154. };
  36155. /**
  36156. * Gets the minZ used for shadow according to both the scene and the light.
  36157. *
  36158. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36159. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36160. * @param activeCamera
  36161. */
  36162. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36163. return 1;
  36164. };
  36165. /**
  36166. * Gets the maxZ used for shadow according to both the scene and the light.
  36167. *
  36168. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36169. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36170. * @param activeCamera
  36171. */
  36172. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36173. return 1;
  36174. };
  36175. __decorate([
  36176. BABYLON.serialize()
  36177. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36178. __decorate([
  36179. BABYLON.serialize()
  36180. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36181. __decorate([
  36182. BABYLON.serialize()
  36183. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36184. return DirectionalLight;
  36185. }(BABYLON.ShadowLight));
  36186. BABYLON.DirectionalLight = DirectionalLight;
  36187. })(BABYLON || (BABYLON = {}));
  36188. //# sourceMappingURL=babylon.directionalLight.js.map
  36189. var BABYLON;
  36190. (function (BABYLON) {
  36191. var SpotLight = (function (_super) {
  36192. __extends(SpotLight, _super);
  36193. /**
  36194. * Creates a SpotLight object in the scene with the passed parameters :
  36195. * - `position` (Vector3) is the initial SpotLight position,
  36196. * - `direction` (Vector3) is the initial SpotLight direction,
  36197. * - `angle` (float, in radians) is the spot light cone angle,
  36198. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36199. * A spot light is a simply light oriented cone.
  36200. * It can cast shadows.
  36201. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36202. */
  36203. function SpotLight(name, position, direction, angle, exponent, scene) {
  36204. var _this = _super.call(this, name, scene) || this;
  36205. _this.position = position;
  36206. _this.direction = direction;
  36207. _this.angle = angle;
  36208. _this.exponent = exponent;
  36209. return _this;
  36210. }
  36211. Object.defineProperty(SpotLight.prototype, "angle", {
  36212. get: function () {
  36213. return this._angle;
  36214. },
  36215. set: function (value) {
  36216. this._angle = value;
  36217. this.forceProjectionMatrixCompute();
  36218. },
  36219. enumerable: true,
  36220. configurable: true
  36221. });
  36222. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36223. get: function () {
  36224. return this._shadowAngleScale;
  36225. },
  36226. /**
  36227. * Allows scaling the angle of the light for shadow generation only.
  36228. */
  36229. set: function (value) {
  36230. this._shadowAngleScale = value;
  36231. this.forceProjectionMatrixCompute();
  36232. },
  36233. enumerable: true,
  36234. configurable: true
  36235. });
  36236. /**
  36237. * Returns the string "SpotLight".
  36238. */
  36239. SpotLight.prototype.getClassName = function () {
  36240. return "SpotLight";
  36241. };
  36242. /**
  36243. * Returns the integer 2.
  36244. */
  36245. SpotLight.prototype.getTypeID = function () {
  36246. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36247. };
  36248. /**
  36249. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  36250. * Returns the SpotLight.
  36251. */
  36252. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36253. var activeCamera = this.getScene().activeCamera;
  36254. this._shadowAngleScale = this._shadowAngleScale || 1;
  36255. var angle = this._shadowAngleScale * this._angle;
  36256. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36257. };
  36258. SpotLight.prototype._buildUniformLayout = function () {
  36259. this._uniformBuffer.addUniform("vLightData", 4);
  36260. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36261. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36262. this._uniformBuffer.addUniform("vLightDirection", 3);
  36263. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36264. this._uniformBuffer.addUniform("depthValues", 2);
  36265. this._uniformBuffer.create();
  36266. };
  36267. /**
  36268. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36269. * Return the SpotLight.
  36270. */
  36271. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36272. var normalizeDirection;
  36273. if (this.computeTransformedInformation()) {
  36274. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36275. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36276. }
  36277. else {
  36278. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36279. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36280. }
  36281. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36282. return this;
  36283. };
  36284. __decorate([
  36285. BABYLON.serialize()
  36286. ], SpotLight.prototype, "angle", null);
  36287. __decorate([
  36288. BABYLON.serialize()
  36289. /**
  36290. * Allows scaling the angle of the light for shadow generation only.
  36291. */
  36292. ], SpotLight.prototype, "shadowAngleScale", null);
  36293. __decorate([
  36294. BABYLON.serialize()
  36295. ], SpotLight.prototype, "exponent", void 0);
  36296. return SpotLight;
  36297. }(BABYLON.ShadowLight));
  36298. BABYLON.SpotLight = SpotLight;
  36299. })(BABYLON || (BABYLON = {}));
  36300. //# sourceMappingURL=babylon.spotLight.js.map
  36301. var BABYLON;
  36302. (function (BABYLON) {
  36303. var AnimationRange = (function () {
  36304. function AnimationRange(name, from, to) {
  36305. this.name = name;
  36306. this.from = from;
  36307. this.to = to;
  36308. }
  36309. AnimationRange.prototype.clone = function () {
  36310. return new AnimationRange(this.name, this.from, this.to);
  36311. };
  36312. return AnimationRange;
  36313. }());
  36314. BABYLON.AnimationRange = AnimationRange;
  36315. /**
  36316. * Composed of a frame, and an action function
  36317. */
  36318. var AnimationEvent = (function () {
  36319. function AnimationEvent(frame, action, onlyOnce) {
  36320. this.frame = frame;
  36321. this.action = action;
  36322. this.onlyOnce = onlyOnce;
  36323. this.isDone = false;
  36324. }
  36325. return AnimationEvent;
  36326. }());
  36327. BABYLON.AnimationEvent = AnimationEvent;
  36328. var PathCursor = (function () {
  36329. function PathCursor(path) {
  36330. this.path = path;
  36331. this._onchange = new Array();
  36332. this.value = 0;
  36333. this.animations = new Array();
  36334. }
  36335. PathCursor.prototype.getPoint = function () {
  36336. var point = this.path.getPointAtLengthPosition(this.value);
  36337. return new BABYLON.Vector3(point.x, 0, point.y);
  36338. };
  36339. PathCursor.prototype.moveAhead = function (step) {
  36340. if (step === void 0) { step = 0.002; }
  36341. this.move(step);
  36342. return this;
  36343. };
  36344. PathCursor.prototype.moveBack = function (step) {
  36345. if (step === void 0) { step = 0.002; }
  36346. this.move(-step);
  36347. return this;
  36348. };
  36349. PathCursor.prototype.move = function (step) {
  36350. if (Math.abs(step) > 1) {
  36351. throw "step size should be less than 1.";
  36352. }
  36353. this.value += step;
  36354. this.ensureLimits();
  36355. this.raiseOnChange();
  36356. return this;
  36357. };
  36358. PathCursor.prototype.ensureLimits = function () {
  36359. while (this.value > 1) {
  36360. this.value -= 1;
  36361. }
  36362. while (this.value < 0) {
  36363. this.value += 1;
  36364. }
  36365. return this;
  36366. };
  36367. // used by animation engine
  36368. PathCursor.prototype.markAsDirty = function (propertyName) {
  36369. this.ensureLimits();
  36370. this.raiseOnChange();
  36371. return this;
  36372. };
  36373. PathCursor.prototype.raiseOnChange = function () {
  36374. var _this = this;
  36375. this._onchange.forEach(function (f) { return f(_this); });
  36376. return this;
  36377. };
  36378. PathCursor.prototype.onchange = function (f) {
  36379. this._onchange.push(f);
  36380. return this;
  36381. };
  36382. return PathCursor;
  36383. }());
  36384. BABYLON.PathCursor = PathCursor;
  36385. var Animation = (function () {
  36386. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  36387. this.name = name;
  36388. this.targetProperty = targetProperty;
  36389. this.framePerSecond = framePerSecond;
  36390. this.dataType = dataType;
  36391. this.loopMode = loopMode;
  36392. this.enableBlending = enableBlending;
  36393. this._offsetsCache = {};
  36394. this._highLimitsCache = {};
  36395. this._stopped = false;
  36396. this._blendingFactor = 0;
  36397. // The set of event that will be linked to this animation
  36398. this._events = new Array();
  36399. this.allowMatricesInterpolation = false;
  36400. this.blendingSpeed = 0.01;
  36401. this._ranges = {};
  36402. this.targetPropertyPath = targetProperty.split(".");
  36403. this.dataType = dataType;
  36404. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  36405. }
  36406. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  36407. var dataType = undefined;
  36408. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  36409. dataType = Animation.ANIMATIONTYPE_FLOAT;
  36410. }
  36411. else if (from instanceof BABYLON.Quaternion) {
  36412. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  36413. }
  36414. else if (from instanceof BABYLON.Vector3) {
  36415. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  36416. }
  36417. else if (from instanceof BABYLON.Vector2) {
  36418. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  36419. }
  36420. else if (from instanceof BABYLON.Color3) {
  36421. dataType = Animation.ANIMATIONTYPE_COLOR3;
  36422. }
  36423. else if (from instanceof BABYLON.Size) {
  36424. dataType = Animation.ANIMATIONTYPE_SIZE;
  36425. }
  36426. if (dataType == undefined) {
  36427. return null;
  36428. }
  36429. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  36430. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  36431. animation.setKeys(keys);
  36432. if (easingFunction !== undefined) {
  36433. animation.setEasingFunction(easingFunction);
  36434. }
  36435. return animation;
  36436. };
  36437. /**
  36438. * Sets up an animation.
  36439. * @param property the property to animate
  36440. * @param animationType the animation type to apply
  36441. * @param easingFunction the easing function used in the animation
  36442. * @returns The created animation
  36443. */
  36444. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  36445. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36446. animation.setEasingFunction(easingFunction);
  36447. return animation;
  36448. };
  36449. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36450. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36451. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36452. };
  36453. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36454. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36455. node.animations.push(animation);
  36456. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36457. };
  36458. /**
  36459. * Transition property of the Camera to the target Value.
  36460. * @param property The property to transition
  36461. * @param targetValue The target Value of the property
  36462. * @param host The object where the property to animate belongs
  36463. * @param scene Scene used to run the animation
  36464. * @param frameRate Framerate (in frame/s) to use
  36465. * @param transition The transition type we want to use
  36466. * @param duration The duration of the animation, in milliseconds
  36467. * @param onAnimationEnd Call back trigger at the end of the animation.
  36468. */
  36469. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  36470. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  36471. if (duration <= 0) {
  36472. host[property] = targetValue;
  36473. if (onAnimationEnd) {
  36474. onAnimationEnd();
  36475. }
  36476. return;
  36477. }
  36478. var endFrame = frameRate * (duration / 1000);
  36479. transition.setKeys([{
  36480. frame: 0,
  36481. value: host[property].clone ? host[property].clone() : host[property]
  36482. },
  36483. {
  36484. frame: endFrame,
  36485. value: targetValue
  36486. }]);
  36487. if (!host.animations) {
  36488. host.animations = [];
  36489. }
  36490. host.animations.push(transition);
  36491. var animation = scene.beginAnimation(host, 0, endFrame, false);
  36492. animation.onAnimationEnd = onAnimationEnd;
  36493. return animation;
  36494. };
  36495. // Methods
  36496. /**
  36497. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  36498. */
  36499. Animation.prototype.toString = function (fullDetails) {
  36500. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  36501. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  36502. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  36503. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  36504. if (fullDetails) {
  36505. ret += ", Ranges: {";
  36506. var first = true;
  36507. for (var name in this._ranges) {
  36508. if (first) {
  36509. ret += ", ";
  36510. first = false;
  36511. }
  36512. ret += name;
  36513. }
  36514. ret += "}";
  36515. }
  36516. return ret;
  36517. };
  36518. /**
  36519. * Add an event to this animation.
  36520. */
  36521. Animation.prototype.addEvent = function (event) {
  36522. this._events.push(event);
  36523. };
  36524. /**
  36525. * Remove all events found at the given frame
  36526. * @param frame
  36527. */
  36528. Animation.prototype.removeEvents = function (frame) {
  36529. for (var index = 0; index < this._events.length; index++) {
  36530. if (this._events[index].frame === frame) {
  36531. this._events.splice(index, 1);
  36532. index--;
  36533. }
  36534. }
  36535. };
  36536. Animation.prototype.createRange = function (name, from, to) {
  36537. // check name not already in use; could happen for bones after serialized
  36538. if (!this._ranges[name]) {
  36539. this._ranges[name] = new AnimationRange(name, from, to);
  36540. }
  36541. };
  36542. Animation.prototype.deleteRange = function (name, deleteFrames) {
  36543. if (deleteFrames === void 0) { deleteFrames = true; }
  36544. if (this._ranges[name]) {
  36545. if (deleteFrames) {
  36546. var from = this._ranges[name].from;
  36547. var to = this._ranges[name].to;
  36548. // this loop MUST go high to low for multiple splices to work
  36549. for (var key = this._keys.length - 1; key >= 0; key--) {
  36550. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  36551. this._keys.splice(key, 1);
  36552. }
  36553. }
  36554. }
  36555. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  36556. }
  36557. };
  36558. Animation.prototype.getRange = function (name) {
  36559. return this._ranges[name];
  36560. };
  36561. Animation.prototype.reset = function () {
  36562. this._offsetsCache = {};
  36563. this._highLimitsCache = {};
  36564. this.currentFrame = 0;
  36565. this._blendingFactor = 0;
  36566. this._originalBlendValue = null;
  36567. };
  36568. Animation.prototype.isStopped = function () {
  36569. return this._stopped;
  36570. };
  36571. Animation.prototype.getKeys = function () {
  36572. return this._keys;
  36573. };
  36574. Animation.prototype.getHighestFrame = function () {
  36575. var ret = 0;
  36576. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  36577. if (ret < this._keys[key].frame) {
  36578. ret = this._keys[key].frame;
  36579. }
  36580. }
  36581. return ret;
  36582. };
  36583. Animation.prototype.getEasingFunction = function () {
  36584. return this._easingFunction;
  36585. };
  36586. Animation.prototype.setEasingFunction = function (easingFunction) {
  36587. this._easingFunction = easingFunction;
  36588. };
  36589. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  36590. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  36591. };
  36592. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36593. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36594. };
  36595. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  36596. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  36597. };
  36598. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36599. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  36600. };
  36601. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  36602. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  36603. };
  36604. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36605. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36606. };
  36607. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  36608. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  36609. };
  36610. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36611. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36612. };
  36613. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  36614. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  36615. };
  36616. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  36617. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  36618. };
  36619. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  36620. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  36621. };
  36622. Animation.prototype.clone = function () {
  36623. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  36624. clone.enableBlending = this.enableBlending;
  36625. clone.blendingSpeed = this.blendingSpeed;
  36626. if (this._keys) {
  36627. clone.setKeys(this._keys);
  36628. }
  36629. if (this._ranges) {
  36630. clone._ranges = {};
  36631. for (var name in this._ranges) {
  36632. clone._ranges[name] = this._ranges[name].clone();
  36633. }
  36634. }
  36635. return clone;
  36636. };
  36637. Animation.prototype.setKeys = function (values) {
  36638. this._keys = values.slice(0);
  36639. this._offsetsCache = {};
  36640. this._highLimitsCache = {};
  36641. };
  36642. Animation.prototype._getKeyValue = function (value) {
  36643. if (typeof value === "function") {
  36644. return value();
  36645. }
  36646. return value;
  36647. };
  36648. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  36649. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  36650. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  36651. }
  36652. this.currentFrame = currentFrame;
  36653. // Try to get a hash to find the right key
  36654. var startKeyIndex = 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));
  36655. if (this._keys[startKeyIndex].frame >= currentFrame) {
  36656. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  36657. startKeyIndex--;
  36658. }
  36659. }
  36660. for (var key = startKeyIndex; key < this._keys.length; key++) {
  36661. var endKey = this._keys[key + 1];
  36662. if (endKey.frame >= currentFrame) {
  36663. var startKey = this._keys[key];
  36664. var startValue = this._getKeyValue(startKey.value);
  36665. var endValue = this._getKeyValue(endKey.value);
  36666. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  36667. var frameDelta = endKey.frame - startKey.frame;
  36668. // gradient : percent of currentFrame between the frame inf and the frame sup
  36669. var gradient = (currentFrame - startKey.frame) / frameDelta;
  36670. // check for easingFunction and correction of gradient
  36671. if (this._easingFunction != null) {
  36672. gradient = this._easingFunction.ease(gradient);
  36673. }
  36674. switch (this.dataType) {
  36675. // Float
  36676. case Animation.ANIMATIONTYPE_FLOAT:
  36677. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  36678. switch (loopMode) {
  36679. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36680. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36681. return floatValue;
  36682. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36683. return offsetValue * repeatCount + floatValue;
  36684. }
  36685. break;
  36686. // Quaternion
  36687. case Animation.ANIMATIONTYPE_QUATERNION:
  36688. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  36689. switch (loopMode) {
  36690. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36691. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36692. return quatValue;
  36693. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36694. return quatValue.add(offsetValue.scale(repeatCount));
  36695. }
  36696. return quatValue;
  36697. // Vector3
  36698. case Animation.ANIMATIONTYPE_VECTOR3:
  36699. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  36700. switch (loopMode) {
  36701. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36702. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36703. return vec3Value;
  36704. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36705. return vec3Value.add(offsetValue.scale(repeatCount));
  36706. }
  36707. // Vector2
  36708. case Animation.ANIMATIONTYPE_VECTOR2:
  36709. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  36710. switch (loopMode) {
  36711. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36712. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36713. return vec2Value;
  36714. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36715. return vec2Value.add(offsetValue.scale(repeatCount));
  36716. }
  36717. // Size
  36718. case Animation.ANIMATIONTYPE_SIZE:
  36719. switch (loopMode) {
  36720. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36721. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36722. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  36723. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36724. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36725. }
  36726. // Color3
  36727. case Animation.ANIMATIONTYPE_COLOR3:
  36728. switch (loopMode) {
  36729. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36730. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36731. return this.color3InterpolateFunction(startValue, endValue, gradient);
  36732. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36733. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36734. }
  36735. // Matrix
  36736. case Animation.ANIMATIONTYPE_MATRIX:
  36737. switch (loopMode) {
  36738. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36739. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36740. if (this.allowMatricesInterpolation) {
  36741. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  36742. }
  36743. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36744. return startValue;
  36745. }
  36746. default:
  36747. break;
  36748. }
  36749. break;
  36750. }
  36751. }
  36752. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  36753. };
  36754. Animation.prototype.setValue = function (currentValue, blend) {
  36755. if (blend === void 0) { blend = false; }
  36756. // Set value
  36757. var path;
  36758. var destination;
  36759. if (this.targetPropertyPath.length > 1) {
  36760. var property = this._target[this.targetPropertyPath[0]];
  36761. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  36762. property = property[this.targetPropertyPath[index]];
  36763. }
  36764. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  36765. destination = property;
  36766. }
  36767. else {
  36768. path = this.targetPropertyPath[0];
  36769. destination = this._target;
  36770. }
  36771. // Blending
  36772. if (this.enableBlending && this._blendingFactor <= 1.0) {
  36773. if (!this._originalBlendValue) {
  36774. if (destination[path].clone) {
  36775. this._originalBlendValue = destination[path].clone();
  36776. }
  36777. else {
  36778. this._originalBlendValue = destination[path];
  36779. }
  36780. }
  36781. if (this._originalBlendValue.prototype) {
  36782. if (this._originalBlendValue.prototype.Lerp) {
  36783. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  36784. }
  36785. else {
  36786. destination[path] = currentValue;
  36787. }
  36788. }
  36789. else if (this._originalBlendValue.m) {
  36790. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  36791. }
  36792. else {
  36793. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  36794. }
  36795. this._blendingFactor += this.blendingSpeed;
  36796. }
  36797. else {
  36798. destination[path] = currentValue;
  36799. }
  36800. if (this._target.markAsDirty) {
  36801. this._target.markAsDirty(this.targetProperty);
  36802. }
  36803. };
  36804. Animation.prototype.goToFrame = function (frame) {
  36805. if (frame < this._keys[0].frame) {
  36806. frame = this._keys[0].frame;
  36807. }
  36808. else if (frame > this._keys[this._keys.length - 1].frame) {
  36809. frame = this._keys[this._keys.length - 1].frame;
  36810. }
  36811. var currentValue = this._interpolate(frame, 0, this.loopMode);
  36812. this.setValue(currentValue);
  36813. };
  36814. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  36815. if (blend === void 0) { blend = false; }
  36816. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  36817. this._stopped = true;
  36818. return false;
  36819. }
  36820. var returnValue = true;
  36821. // Adding a start key at frame 0 if missing
  36822. if (this._keys[0].frame !== 0) {
  36823. var newKey = { frame: 0, value: this._keys[0].value };
  36824. this._keys.splice(0, 0, newKey);
  36825. }
  36826. // Check limits
  36827. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  36828. from = this._keys[0].frame;
  36829. }
  36830. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  36831. to = this._keys[this._keys.length - 1].frame;
  36832. }
  36833. //to and from cannot be the same key
  36834. if (from === to) {
  36835. from++;
  36836. }
  36837. // Compute ratio
  36838. var range = to - from;
  36839. var offsetValue;
  36840. // ratio represents the frame delta between from and to
  36841. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  36842. var highLimitValue = 0;
  36843. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  36844. returnValue = false;
  36845. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  36846. }
  36847. else {
  36848. // Get max value if required
  36849. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  36850. var keyOffset = to.toString() + from.toString();
  36851. if (!this._offsetsCache[keyOffset]) {
  36852. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36853. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36854. switch (this.dataType) {
  36855. // Float
  36856. case Animation.ANIMATIONTYPE_FLOAT:
  36857. this._offsetsCache[keyOffset] = toValue - fromValue;
  36858. break;
  36859. // Quaternion
  36860. case Animation.ANIMATIONTYPE_QUATERNION:
  36861. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36862. break;
  36863. // Vector3
  36864. case Animation.ANIMATIONTYPE_VECTOR3:
  36865. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36866. // Vector2
  36867. case Animation.ANIMATIONTYPE_VECTOR2:
  36868. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36869. // Size
  36870. case Animation.ANIMATIONTYPE_SIZE:
  36871. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36872. // Color3
  36873. case Animation.ANIMATIONTYPE_COLOR3:
  36874. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36875. default:
  36876. break;
  36877. }
  36878. this._highLimitsCache[keyOffset] = toValue;
  36879. }
  36880. highLimitValue = this._highLimitsCache[keyOffset];
  36881. offsetValue = this._offsetsCache[keyOffset];
  36882. }
  36883. }
  36884. if (offsetValue === undefined) {
  36885. switch (this.dataType) {
  36886. // Float
  36887. case Animation.ANIMATIONTYPE_FLOAT:
  36888. offsetValue = 0;
  36889. break;
  36890. // Quaternion
  36891. case Animation.ANIMATIONTYPE_QUATERNION:
  36892. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  36893. break;
  36894. // Vector3
  36895. case Animation.ANIMATIONTYPE_VECTOR3:
  36896. offsetValue = BABYLON.Vector3.Zero();
  36897. break;
  36898. // Vector2
  36899. case Animation.ANIMATIONTYPE_VECTOR2:
  36900. offsetValue = BABYLON.Vector2.Zero();
  36901. break;
  36902. // Size
  36903. case Animation.ANIMATIONTYPE_SIZE:
  36904. offsetValue = BABYLON.Size.Zero();
  36905. break;
  36906. // Color3
  36907. case Animation.ANIMATIONTYPE_COLOR3:
  36908. offsetValue = BABYLON.Color3.Black();
  36909. }
  36910. }
  36911. // Compute value
  36912. var repeatCount = (ratio / range) >> 0;
  36913. var currentFrame = returnValue ? from + ratio % range : to;
  36914. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  36915. // Set value
  36916. this.setValue(currentValue);
  36917. // Check events
  36918. for (var index = 0; index < this._events.length; index++) {
  36919. // Make sure current frame has passed event frame and that event frame is within the current range
  36920. // Also, handle both forward and reverse animations
  36921. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  36922. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  36923. var event = this._events[index];
  36924. if (!event.isDone) {
  36925. // If event should be done only once, remove it.
  36926. if (event.onlyOnce) {
  36927. this._events.splice(index, 1);
  36928. index--;
  36929. }
  36930. event.isDone = true;
  36931. event.action();
  36932. } // Don't do anything if the event has already be done.
  36933. }
  36934. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  36935. // reset event, the animation is looping
  36936. this._events[index].isDone = false;
  36937. }
  36938. }
  36939. if (!returnValue) {
  36940. this._stopped = true;
  36941. }
  36942. return returnValue;
  36943. };
  36944. Animation.prototype.serialize = function () {
  36945. var serializationObject = {};
  36946. serializationObject.name = this.name;
  36947. serializationObject.property = this.targetProperty;
  36948. serializationObject.framePerSecond = this.framePerSecond;
  36949. serializationObject.dataType = this.dataType;
  36950. serializationObject.loopBehavior = this.loopMode;
  36951. serializationObject.enableBlending = this.enableBlending;
  36952. serializationObject.blendingSpeed = this.blendingSpeed;
  36953. var dataType = this.dataType;
  36954. serializationObject.keys = [];
  36955. var keys = this.getKeys();
  36956. for (var index = 0; index < keys.length; index++) {
  36957. var animationKey = keys[index];
  36958. var key = {};
  36959. key.frame = animationKey.frame;
  36960. switch (dataType) {
  36961. case Animation.ANIMATIONTYPE_FLOAT:
  36962. key.values = [animationKey.value];
  36963. break;
  36964. case Animation.ANIMATIONTYPE_QUATERNION:
  36965. case Animation.ANIMATIONTYPE_MATRIX:
  36966. case Animation.ANIMATIONTYPE_VECTOR3:
  36967. case Animation.ANIMATIONTYPE_COLOR3:
  36968. key.values = animationKey.value.asArray();
  36969. break;
  36970. }
  36971. serializationObject.keys.push(key);
  36972. }
  36973. serializationObject.ranges = [];
  36974. for (var name in this._ranges) {
  36975. var range = {};
  36976. range.name = name;
  36977. range.from = this._ranges[name].from;
  36978. range.to = this._ranges[name].to;
  36979. serializationObject.ranges.push(range);
  36980. }
  36981. return serializationObject;
  36982. };
  36983. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  36984. get: function () {
  36985. return Animation._ANIMATIONTYPE_FLOAT;
  36986. },
  36987. enumerable: true,
  36988. configurable: true
  36989. });
  36990. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  36991. get: function () {
  36992. return Animation._ANIMATIONTYPE_VECTOR3;
  36993. },
  36994. enumerable: true,
  36995. configurable: true
  36996. });
  36997. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  36998. get: function () {
  36999. return Animation._ANIMATIONTYPE_VECTOR2;
  37000. },
  37001. enumerable: true,
  37002. configurable: true
  37003. });
  37004. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37005. get: function () {
  37006. return Animation._ANIMATIONTYPE_SIZE;
  37007. },
  37008. enumerable: true,
  37009. configurable: true
  37010. });
  37011. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37012. get: function () {
  37013. return Animation._ANIMATIONTYPE_QUATERNION;
  37014. },
  37015. enumerable: true,
  37016. configurable: true
  37017. });
  37018. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37019. get: function () {
  37020. return Animation._ANIMATIONTYPE_MATRIX;
  37021. },
  37022. enumerable: true,
  37023. configurable: true
  37024. });
  37025. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37026. get: function () {
  37027. return Animation._ANIMATIONTYPE_COLOR3;
  37028. },
  37029. enumerable: true,
  37030. configurable: true
  37031. });
  37032. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37033. get: function () {
  37034. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37035. },
  37036. enumerable: true,
  37037. configurable: true
  37038. });
  37039. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37040. get: function () {
  37041. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37042. },
  37043. enumerable: true,
  37044. configurable: true
  37045. });
  37046. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37047. get: function () {
  37048. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37049. },
  37050. enumerable: true,
  37051. configurable: true
  37052. });
  37053. Animation.Parse = function (parsedAnimation) {
  37054. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37055. var dataType = parsedAnimation.dataType;
  37056. var keys = [];
  37057. var data;
  37058. var index;
  37059. if (parsedAnimation.enableBlending) {
  37060. animation.enableBlending = parsedAnimation.enableBlending;
  37061. }
  37062. if (parsedAnimation.blendingSpeed) {
  37063. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37064. }
  37065. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37066. var key = parsedAnimation.keys[index];
  37067. switch (dataType) {
  37068. case Animation.ANIMATIONTYPE_FLOAT:
  37069. data = key.values[0];
  37070. break;
  37071. case Animation.ANIMATIONTYPE_QUATERNION:
  37072. data = BABYLON.Quaternion.FromArray(key.values);
  37073. break;
  37074. case Animation.ANIMATIONTYPE_MATRIX:
  37075. data = BABYLON.Matrix.FromArray(key.values);
  37076. break;
  37077. case Animation.ANIMATIONTYPE_COLOR3:
  37078. data = BABYLON.Color3.FromArray(key.values);
  37079. break;
  37080. case Animation.ANIMATIONTYPE_VECTOR3:
  37081. default:
  37082. data = BABYLON.Vector3.FromArray(key.values);
  37083. break;
  37084. }
  37085. keys.push({
  37086. frame: key.frame,
  37087. value: data
  37088. });
  37089. }
  37090. animation.setKeys(keys);
  37091. if (parsedAnimation.ranges) {
  37092. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37093. data = parsedAnimation.ranges[index];
  37094. animation.createRange(data.name, data.from, data.to);
  37095. }
  37096. }
  37097. return animation;
  37098. };
  37099. Animation.AppendSerializedAnimations = function (source, destination) {
  37100. if (source.animations) {
  37101. destination.animations = [];
  37102. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37103. var animation = source.animations[animationIndex];
  37104. destination.animations.push(animation.serialize());
  37105. }
  37106. }
  37107. };
  37108. // Statics
  37109. Animation._ANIMATIONTYPE_FLOAT = 0;
  37110. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37111. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37112. Animation._ANIMATIONTYPE_MATRIX = 3;
  37113. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37114. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37115. Animation._ANIMATIONTYPE_SIZE = 6;
  37116. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37117. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37118. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37119. return Animation;
  37120. }());
  37121. BABYLON.Animation = Animation;
  37122. })(BABYLON || (BABYLON = {}));
  37123. //# sourceMappingURL=babylon.animation.js.map
  37124. var BABYLON;
  37125. (function (BABYLON) {
  37126. var Animatable = (function () {
  37127. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37128. if (fromFrame === void 0) { fromFrame = 0; }
  37129. if (toFrame === void 0) { toFrame = 100; }
  37130. if (loopAnimation === void 0) { loopAnimation = false; }
  37131. if (speedRatio === void 0) { speedRatio = 1.0; }
  37132. this.target = target;
  37133. this.fromFrame = fromFrame;
  37134. this.toFrame = toFrame;
  37135. this.loopAnimation = loopAnimation;
  37136. this.speedRatio = speedRatio;
  37137. this.onAnimationEnd = onAnimationEnd;
  37138. this._localDelayOffset = null;
  37139. this._pausedDelay = null;
  37140. this._animations = new Array();
  37141. this._paused = false;
  37142. this.animationStarted = false;
  37143. if (animations) {
  37144. this.appendAnimations(target, animations);
  37145. }
  37146. this._scene = scene;
  37147. scene._activeAnimatables.push(this);
  37148. }
  37149. // Methods
  37150. Animatable.prototype.getAnimations = function () {
  37151. return this._animations;
  37152. };
  37153. Animatable.prototype.appendAnimations = function (target, animations) {
  37154. for (var index = 0; index < animations.length; index++) {
  37155. var animation = animations[index];
  37156. animation._target = target;
  37157. this._animations.push(animation);
  37158. }
  37159. };
  37160. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  37161. var animations = this._animations;
  37162. for (var index = 0; index < animations.length; index++) {
  37163. if (animations[index].targetProperty === property) {
  37164. return animations[index];
  37165. }
  37166. }
  37167. return null;
  37168. };
  37169. Animatable.prototype.reset = function () {
  37170. var animations = this._animations;
  37171. for (var index = 0; index < animations.length; index++) {
  37172. animations[index].reset();
  37173. }
  37174. this._localDelayOffset = null;
  37175. this._pausedDelay = null;
  37176. };
  37177. Animatable.prototype.enableBlending = function (blendingSpeed) {
  37178. var animations = this._animations;
  37179. for (var index = 0; index < animations.length; index++) {
  37180. animations[index].enableBlending = true;
  37181. animations[index].blendingSpeed = blendingSpeed;
  37182. }
  37183. };
  37184. Animatable.prototype.disableBlending = function () {
  37185. var animations = this._animations;
  37186. for (var index = 0; index < animations.length; index++) {
  37187. animations[index].enableBlending = false;
  37188. }
  37189. };
  37190. Animatable.prototype.goToFrame = function (frame) {
  37191. var animations = this._animations;
  37192. if (animations[0]) {
  37193. var fps = animations[0].framePerSecond;
  37194. var currentFrame = animations[0].currentFrame;
  37195. var adjustTime = frame - currentFrame;
  37196. var delay = adjustTime * 1000 / fps;
  37197. this._localDelayOffset -= delay;
  37198. }
  37199. for (var index = 0; index < animations.length; index++) {
  37200. animations[index].goToFrame(frame);
  37201. }
  37202. };
  37203. Animatable.prototype.pause = function () {
  37204. if (this._paused) {
  37205. return;
  37206. }
  37207. this._paused = true;
  37208. };
  37209. Animatable.prototype.restart = function () {
  37210. this._paused = false;
  37211. };
  37212. Animatable.prototype.stop = function (animationName) {
  37213. if (animationName) {
  37214. var idx = this._scene._activeAnimatables.indexOf(this);
  37215. if (idx > -1) {
  37216. var animations = this._animations;
  37217. for (var index = animations.length - 1; index >= 0; index--) {
  37218. if (typeof animationName === "string" && animations[index].name != animationName) {
  37219. continue;
  37220. }
  37221. animations[index].reset();
  37222. animations.splice(index, 1);
  37223. }
  37224. if (animations.length == 0) {
  37225. this._scene._activeAnimatables.splice(idx, 1);
  37226. if (this.onAnimationEnd) {
  37227. this.onAnimationEnd();
  37228. }
  37229. }
  37230. }
  37231. }
  37232. else {
  37233. var index = this._scene._activeAnimatables.indexOf(this);
  37234. if (index > -1) {
  37235. this._scene._activeAnimatables.splice(index, 1);
  37236. var animations = this._animations;
  37237. for (var index = 0; index < animations.length; index++) {
  37238. animations[index].reset();
  37239. }
  37240. if (this.onAnimationEnd) {
  37241. this.onAnimationEnd();
  37242. }
  37243. }
  37244. }
  37245. };
  37246. Animatable.prototype._animate = function (delay) {
  37247. if (this._paused) {
  37248. this.animationStarted = false;
  37249. if (this._pausedDelay === null) {
  37250. this._pausedDelay = delay;
  37251. }
  37252. return true;
  37253. }
  37254. if (this._localDelayOffset === null) {
  37255. this._localDelayOffset = delay;
  37256. }
  37257. else if (this._pausedDelay !== null) {
  37258. this._localDelayOffset += delay - this._pausedDelay;
  37259. this._pausedDelay = null;
  37260. }
  37261. // Animating
  37262. var running = false;
  37263. var animations = this._animations;
  37264. var index;
  37265. for (index = 0; index < animations.length; index++) {
  37266. var animation = animations[index];
  37267. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  37268. running = running || isRunning;
  37269. }
  37270. this.animationStarted = running;
  37271. if (!running) {
  37272. // Remove from active animatables
  37273. index = this._scene._activeAnimatables.indexOf(this);
  37274. this._scene._activeAnimatables.splice(index, 1);
  37275. }
  37276. if (!running && this.onAnimationEnd) {
  37277. this.onAnimationEnd();
  37278. this.onAnimationEnd = null;
  37279. }
  37280. return running;
  37281. };
  37282. return Animatable;
  37283. }());
  37284. BABYLON.Animatable = Animatable;
  37285. })(BABYLON || (BABYLON = {}));
  37286. //# sourceMappingURL=babylon.animatable.js.map
  37287. var BABYLON;
  37288. (function (BABYLON) {
  37289. var EasingFunction = (function () {
  37290. function EasingFunction() {
  37291. // Properties
  37292. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  37293. }
  37294. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  37295. get: function () {
  37296. return EasingFunction._EASINGMODE_EASEIN;
  37297. },
  37298. enumerable: true,
  37299. configurable: true
  37300. });
  37301. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  37302. get: function () {
  37303. return EasingFunction._EASINGMODE_EASEOUT;
  37304. },
  37305. enumerable: true,
  37306. configurable: true
  37307. });
  37308. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  37309. get: function () {
  37310. return EasingFunction._EASINGMODE_EASEINOUT;
  37311. },
  37312. enumerable: true,
  37313. configurable: true
  37314. });
  37315. EasingFunction.prototype.setEasingMode = function (easingMode) {
  37316. var n = Math.min(Math.max(easingMode, 0), 2);
  37317. this._easingMode = n;
  37318. };
  37319. EasingFunction.prototype.getEasingMode = function () {
  37320. return this._easingMode;
  37321. };
  37322. EasingFunction.prototype.easeInCore = function (gradient) {
  37323. throw new Error('You must implement this method');
  37324. };
  37325. EasingFunction.prototype.ease = function (gradient) {
  37326. switch (this._easingMode) {
  37327. case EasingFunction.EASINGMODE_EASEIN:
  37328. return this.easeInCore(gradient);
  37329. case EasingFunction.EASINGMODE_EASEOUT:
  37330. return (1 - this.easeInCore(1 - gradient));
  37331. }
  37332. if (gradient >= 0.5) {
  37333. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  37334. }
  37335. return (this.easeInCore(gradient * 2) * 0.5);
  37336. };
  37337. //Statics
  37338. EasingFunction._EASINGMODE_EASEIN = 0;
  37339. EasingFunction._EASINGMODE_EASEOUT = 1;
  37340. EasingFunction._EASINGMODE_EASEINOUT = 2;
  37341. return EasingFunction;
  37342. }());
  37343. BABYLON.EasingFunction = EasingFunction;
  37344. var CircleEase = (function (_super) {
  37345. __extends(CircleEase, _super);
  37346. function CircleEase() {
  37347. return _super !== null && _super.apply(this, arguments) || this;
  37348. }
  37349. CircleEase.prototype.easeInCore = function (gradient) {
  37350. gradient = Math.max(0, Math.min(1, gradient));
  37351. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  37352. };
  37353. return CircleEase;
  37354. }(EasingFunction));
  37355. BABYLON.CircleEase = CircleEase;
  37356. var BackEase = (function (_super) {
  37357. __extends(BackEase, _super);
  37358. function BackEase(amplitude) {
  37359. if (amplitude === void 0) { amplitude = 1; }
  37360. var _this = _super.call(this) || this;
  37361. _this.amplitude = amplitude;
  37362. return _this;
  37363. }
  37364. BackEase.prototype.easeInCore = function (gradient) {
  37365. var num = Math.max(0, this.amplitude);
  37366. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  37367. };
  37368. return BackEase;
  37369. }(EasingFunction));
  37370. BABYLON.BackEase = BackEase;
  37371. var BounceEase = (function (_super) {
  37372. __extends(BounceEase, _super);
  37373. function BounceEase(bounces, bounciness) {
  37374. if (bounces === void 0) { bounces = 3; }
  37375. if (bounciness === void 0) { bounciness = 2; }
  37376. var _this = _super.call(this) || this;
  37377. _this.bounces = bounces;
  37378. _this.bounciness = bounciness;
  37379. return _this;
  37380. }
  37381. BounceEase.prototype.easeInCore = function (gradient) {
  37382. var y = Math.max(0.0, this.bounces);
  37383. var bounciness = this.bounciness;
  37384. if (bounciness <= 1.0) {
  37385. bounciness = 1.001;
  37386. }
  37387. var num9 = Math.pow(bounciness, y);
  37388. var num5 = 1.0 - bounciness;
  37389. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  37390. var num15 = gradient * num4;
  37391. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  37392. var num3 = Math.floor(num65);
  37393. var num13 = num3 + 1.0;
  37394. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  37395. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  37396. var num7 = (num8 + num12) * 0.5;
  37397. var num6 = gradient - num7;
  37398. var num2 = num7 - num8;
  37399. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  37400. };
  37401. return BounceEase;
  37402. }(EasingFunction));
  37403. BABYLON.BounceEase = BounceEase;
  37404. var CubicEase = (function (_super) {
  37405. __extends(CubicEase, _super);
  37406. function CubicEase() {
  37407. return _super !== null && _super.apply(this, arguments) || this;
  37408. }
  37409. CubicEase.prototype.easeInCore = function (gradient) {
  37410. return (gradient * gradient * gradient);
  37411. };
  37412. return CubicEase;
  37413. }(EasingFunction));
  37414. BABYLON.CubicEase = CubicEase;
  37415. var ElasticEase = (function (_super) {
  37416. __extends(ElasticEase, _super);
  37417. function ElasticEase(oscillations, springiness) {
  37418. if (oscillations === void 0) { oscillations = 3; }
  37419. if (springiness === void 0) { springiness = 3; }
  37420. var _this = _super.call(this) || this;
  37421. _this.oscillations = oscillations;
  37422. _this.springiness = springiness;
  37423. return _this;
  37424. }
  37425. ElasticEase.prototype.easeInCore = function (gradient) {
  37426. var num2;
  37427. var num3 = Math.max(0.0, this.oscillations);
  37428. var num = Math.max(0.0, this.springiness);
  37429. if (num == 0) {
  37430. num2 = gradient;
  37431. }
  37432. else {
  37433. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  37434. }
  37435. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  37436. };
  37437. return ElasticEase;
  37438. }(EasingFunction));
  37439. BABYLON.ElasticEase = ElasticEase;
  37440. var ExponentialEase = (function (_super) {
  37441. __extends(ExponentialEase, _super);
  37442. function ExponentialEase(exponent) {
  37443. if (exponent === void 0) { exponent = 2; }
  37444. var _this = _super.call(this) || this;
  37445. _this.exponent = exponent;
  37446. return _this;
  37447. }
  37448. ExponentialEase.prototype.easeInCore = function (gradient) {
  37449. if (this.exponent <= 0) {
  37450. return gradient;
  37451. }
  37452. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  37453. };
  37454. return ExponentialEase;
  37455. }(EasingFunction));
  37456. BABYLON.ExponentialEase = ExponentialEase;
  37457. var PowerEase = (function (_super) {
  37458. __extends(PowerEase, _super);
  37459. function PowerEase(power) {
  37460. if (power === void 0) { power = 2; }
  37461. var _this = _super.call(this) || this;
  37462. _this.power = power;
  37463. return _this;
  37464. }
  37465. PowerEase.prototype.easeInCore = function (gradient) {
  37466. var y = Math.max(0.0, this.power);
  37467. return Math.pow(gradient, y);
  37468. };
  37469. return PowerEase;
  37470. }(EasingFunction));
  37471. BABYLON.PowerEase = PowerEase;
  37472. var QuadraticEase = (function (_super) {
  37473. __extends(QuadraticEase, _super);
  37474. function QuadraticEase() {
  37475. return _super !== null && _super.apply(this, arguments) || this;
  37476. }
  37477. QuadraticEase.prototype.easeInCore = function (gradient) {
  37478. return (gradient * gradient);
  37479. };
  37480. return QuadraticEase;
  37481. }(EasingFunction));
  37482. BABYLON.QuadraticEase = QuadraticEase;
  37483. var QuarticEase = (function (_super) {
  37484. __extends(QuarticEase, _super);
  37485. function QuarticEase() {
  37486. return _super !== null && _super.apply(this, arguments) || this;
  37487. }
  37488. QuarticEase.prototype.easeInCore = function (gradient) {
  37489. return (gradient * gradient * gradient * gradient);
  37490. };
  37491. return QuarticEase;
  37492. }(EasingFunction));
  37493. BABYLON.QuarticEase = QuarticEase;
  37494. var QuinticEase = (function (_super) {
  37495. __extends(QuinticEase, _super);
  37496. function QuinticEase() {
  37497. return _super !== null && _super.apply(this, arguments) || this;
  37498. }
  37499. QuinticEase.prototype.easeInCore = function (gradient) {
  37500. return (gradient * gradient * gradient * gradient * gradient);
  37501. };
  37502. return QuinticEase;
  37503. }(EasingFunction));
  37504. BABYLON.QuinticEase = QuinticEase;
  37505. var SineEase = (function (_super) {
  37506. __extends(SineEase, _super);
  37507. function SineEase() {
  37508. return _super !== null && _super.apply(this, arguments) || this;
  37509. }
  37510. SineEase.prototype.easeInCore = function (gradient) {
  37511. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  37512. };
  37513. return SineEase;
  37514. }(EasingFunction));
  37515. BABYLON.SineEase = SineEase;
  37516. var BezierCurveEase = (function (_super) {
  37517. __extends(BezierCurveEase, _super);
  37518. function BezierCurveEase(x1, y1, x2, y2) {
  37519. if (x1 === void 0) { x1 = 0; }
  37520. if (y1 === void 0) { y1 = 0; }
  37521. if (x2 === void 0) { x2 = 1; }
  37522. if (y2 === void 0) { y2 = 1; }
  37523. var _this = _super.call(this) || this;
  37524. _this.x1 = x1;
  37525. _this.y1 = y1;
  37526. _this.x2 = x2;
  37527. _this.y2 = y2;
  37528. return _this;
  37529. }
  37530. BezierCurveEase.prototype.easeInCore = function (gradient) {
  37531. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  37532. };
  37533. return BezierCurveEase;
  37534. }(EasingFunction));
  37535. BABYLON.BezierCurveEase = BezierCurveEase;
  37536. })(BABYLON || (BABYLON = {}));
  37537. //# sourceMappingURL=babylon.easing.js.map
  37538. var BABYLON;
  37539. (function (BABYLON) {
  37540. var Condition = (function () {
  37541. function Condition(actionManager) {
  37542. this._actionManager = actionManager;
  37543. }
  37544. Condition.prototype.isValid = function () {
  37545. return true;
  37546. };
  37547. Condition.prototype._getProperty = function (propertyPath) {
  37548. return this._actionManager._getProperty(propertyPath);
  37549. };
  37550. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  37551. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37552. };
  37553. Condition.prototype.serialize = function () {
  37554. };
  37555. Condition.prototype._serialize = function (serializedCondition) {
  37556. return {
  37557. type: 2,
  37558. children: [],
  37559. name: serializedCondition.name,
  37560. properties: serializedCondition.properties
  37561. };
  37562. };
  37563. return Condition;
  37564. }());
  37565. BABYLON.Condition = Condition;
  37566. var ValueCondition = (function (_super) {
  37567. __extends(ValueCondition, _super);
  37568. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  37569. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  37570. var _this = _super.call(this, actionManager) || this;
  37571. _this.propertyPath = propertyPath;
  37572. _this.value = value;
  37573. _this.operator = operator;
  37574. _this._target = target;
  37575. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  37576. _this._property = _this._getProperty(_this.propertyPath);
  37577. return _this;
  37578. }
  37579. Object.defineProperty(ValueCondition, "IsEqual", {
  37580. get: function () {
  37581. return ValueCondition._IsEqual;
  37582. },
  37583. enumerable: true,
  37584. configurable: true
  37585. });
  37586. Object.defineProperty(ValueCondition, "IsDifferent", {
  37587. get: function () {
  37588. return ValueCondition._IsDifferent;
  37589. },
  37590. enumerable: true,
  37591. configurable: true
  37592. });
  37593. Object.defineProperty(ValueCondition, "IsGreater", {
  37594. get: function () {
  37595. return ValueCondition._IsGreater;
  37596. },
  37597. enumerable: true,
  37598. configurable: true
  37599. });
  37600. Object.defineProperty(ValueCondition, "IsLesser", {
  37601. get: function () {
  37602. return ValueCondition._IsLesser;
  37603. },
  37604. enumerable: true,
  37605. configurable: true
  37606. });
  37607. // Methods
  37608. ValueCondition.prototype.isValid = function () {
  37609. switch (this.operator) {
  37610. case ValueCondition.IsGreater:
  37611. return this._effectiveTarget[this._property] > this.value;
  37612. case ValueCondition.IsLesser:
  37613. return this._effectiveTarget[this._property] < this.value;
  37614. case ValueCondition.IsEqual:
  37615. case ValueCondition.IsDifferent:
  37616. var check;
  37617. if (this.value.equals) {
  37618. check = this.value.equals(this._effectiveTarget[this._property]);
  37619. }
  37620. else {
  37621. check = this.value === this._effectiveTarget[this._property];
  37622. }
  37623. return this.operator === ValueCondition.IsEqual ? check : !check;
  37624. }
  37625. return false;
  37626. };
  37627. ValueCondition.prototype.serialize = function () {
  37628. return this._serialize({
  37629. name: "ValueCondition",
  37630. properties: [
  37631. BABYLON.Action._GetTargetProperty(this._target),
  37632. { name: "propertyPath", value: this.propertyPath },
  37633. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37634. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  37635. ]
  37636. });
  37637. };
  37638. ValueCondition.GetOperatorName = function (operator) {
  37639. switch (operator) {
  37640. case ValueCondition._IsEqual: return "IsEqual";
  37641. case ValueCondition._IsDifferent: return "IsDifferent";
  37642. case ValueCondition._IsGreater: return "IsGreater";
  37643. case ValueCondition._IsLesser: return "IsLesser";
  37644. default: return "";
  37645. }
  37646. };
  37647. // Statics
  37648. ValueCondition._IsEqual = 0;
  37649. ValueCondition._IsDifferent = 1;
  37650. ValueCondition._IsGreater = 2;
  37651. ValueCondition._IsLesser = 3;
  37652. return ValueCondition;
  37653. }(Condition));
  37654. BABYLON.ValueCondition = ValueCondition;
  37655. var PredicateCondition = (function (_super) {
  37656. __extends(PredicateCondition, _super);
  37657. function PredicateCondition(actionManager, predicate) {
  37658. var _this = _super.call(this, actionManager) || this;
  37659. _this.predicate = predicate;
  37660. return _this;
  37661. }
  37662. PredicateCondition.prototype.isValid = function () {
  37663. return this.predicate();
  37664. };
  37665. return PredicateCondition;
  37666. }(Condition));
  37667. BABYLON.PredicateCondition = PredicateCondition;
  37668. var StateCondition = (function (_super) {
  37669. __extends(StateCondition, _super);
  37670. function StateCondition(actionManager, target, value) {
  37671. var _this = _super.call(this, actionManager) || this;
  37672. _this.value = value;
  37673. _this._target = target;
  37674. return _this;
  37675. }
  37676. // Methods
  37677. StateCondition.prototype.isValid = function () {
  37678. return this._target.state === this.value;
  37679. };
  37680. StateCondition.prototype.serialize = function () {
  37681. return this._serialize({
  37682. name: "StateCondition",
  37683. properties: [
  37684. BABYLON.Action._GetTargetProperty(this._target),
  37685. { name: "value", value: this.value }
  37686. ]
  37687. });
  37688. };
  37689. return StateCondition;
  37690. }(Condition));
  37691. BABYLON.StateCondition = StateCondition;
  37692. })(BABYLON || (BABYLON = {}));
  37693. //# sourceMappingURL=babylon.condition.js.map
  37694. var BABYLON;
  37695. (function (BABYLON) {
  37696. var Action = (function () {
  37697. function Action(triggerOptions, condition) {
  37698. this.triggerOptions = triggerOptions;
  37699. if (triggerOptions.parameter) {
  37700. this.trigger = triggerOptions.trigger;
  37701. this._triggerParameter = triggerOptions.parameter;
  37702. }
  37703. else {
  37704. this.trigger = triggerOptions;
  37705. }
  37706. this._nextActiveAction = this;
  37707. this._condition = condition;
  37708. }
  37709. // Methods
  37710. Action.prototype._prepare = function () {
  37711. };
  37712. Action.prototype.getTriggerParameter = function () {
  37713. return this._triggerParameter;
  37714. };
  37715. Action.prototype._executeCurrent = function (evt) {
  37716. if (this._nextActiveAction._condition) {
  37717. var condition = this._nextActiveAction._condition;
  37718. var currentRenderId = this._actionManager.getScene().getRenderId();
  37719. // We cache the current evaluation for the current frame
  37720. if (condition._evaluationId === currentRenderId) {
  37721. if (!condition._currentResult) {
  37722. return;
  37723. }
  37724. }
  37725. else {
  37726. condition._evaluationId = currentRenderId;
  37727. if (!condition.isValid()) {
  37728. condition._currentResult = false;
  37729. return;
  37730. }
  37731. condition._currentResult = true;
  37732. }
  37733. }
  37734. this._nextActiveAction.execute(evt);
  37735. this.skipToNextActiveAction();
  37736. };
  37737. Action.prototype.execute = function (evt) {
  37738. };
  37739. Action.prototype.skipToNextActiveAction = function () {
  37740. if (this._nextActiveAction._child) {
  37741. if (!this._nextActiveAction._child._actionManager) {
  37742. this._nextActiveAction._child._actionManager = this._actionManager;
  37743. }
  37744. this._nextActiveAction = this._nextActiveAction._child;
  37745. }
  37746. else {
  37747. this._nextActiveAction = this;
  37748. }
  37749. };
  37750. Action.prototype.then = function (action) {
  37751. this._child = action;
  37752. action._actionManager = this._actionManager;
  37753. action._prepare();
  37754. return action;
  37755. };
  37756. Action.prototype._getProperty = function (propertyPath) {
  37757. return this._actionManager._getProperty(propertyPath);
  37758. };
  37759. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  37760. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37761. };
  37762. Action.prototype.serialize = function (parent) {
  37763. };
  37764. // Called by BABYLON.Action objects in serialize(...). Internal use
  37765. Action.prototype._serialize = function (serializedAction, parent) {
  37766. var serializationObject = {
  37767. type: 1,
  37768. children: [],
  37769. name: serializedAction.name,
  37770. properties: serializedAction.properties || []
  37771. };
  37772. // Serialize child
  37773. if (this._child) {
  37774. this._child.serialize(serializationObject);
  37775. }
  37776. // Check if "this" has a condition
  37777. if (this._condition) {
  37778. var serializedCondition = this._condition.serialize();
  37779. serializedCondition.children.push(serializationObject);
  37780. if (parent) {
  37781. parent.children.push(serializedCondition);
  37782. }
  37783. return serializedCondition;
  37784. }
  37785. if (parent) {
  37786. parent.children.push(serializationObject);
  37787. }
  37788. return serializationObject;
  37789. };
  37790. Action._SerializeValueAsString = function (value) {
  37791. if (typeof value === "number") {
  37792. return value.toString();
  37793. }
  37794. if (typeof value === "boolean") {
  37795. return value ? "true" : "false";
  37796. }
  37797. if (value instanceof BABYLON.Vector2) {
  37798. return value.x + ", " + value.y;
  37799. }
  37800. if (value instanceof BABYLON.Vector3) {
  37801. return value.x + ", " + value.y + ", " + value.z;
  37802. }
  37803. if (value instanceof BABYLON.Color3) {
  37804. return value.r + ", " + value.g + ", " + value.b;
  37805. }
  37806. if (value instanceof BABYLON.Color4) {
  37807. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  37808. }
  37809. return value; // string
  37810. };
  37811. Action._GetTargetProperty = function (target) {
  37812. return {
  37813. name: "target",
  37814. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  37815. : target instanceof BABYLON.Light ? "LightProperties"
  37816. : target instanceof BABYLON.Camera ? "CameraProperties"
  37817. : "SceneProperties",
  37818. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  37819. };
  37820. };
  37821. return Action;
  37822. }());
  37823. BABYLON.Action = Action;
  37824. })(BABYLON || (BABYLON = {}));
  37825. //# sourceMappingURL=babylon.action.js.map
  37826. var BABYLON;
  37827. (function (BABYLON) {
  37828. /**
  37829. * ActionEvent is the event beint sent when an action is triggered.
  37830. */
  37831. var ActionEvent = (function () {
  37832. /**
  37833. * @param source The mesh or sprite that triggered the action.
  37834. * @param pointerX The X mouse cursor position at the time of the event
  37835. * @param pointerY The Y mouse cursor position at the time of the event
  37836. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  37837. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  37838. */
  37839. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  37840. this.source = source;
  37841. this.pointerX = pointerX;
  37842. this.pointerY = pointerY;
  37843. this.meshUnderPointer = meshUnderPointer;
  37844. this.sourceEvent = sourceEvent;
  37845. this.additionalData = additionalData;
  37846. }
  37847. /**
  37848. * Helper function to auto-create an ActionEvent from a source mesh.
  37849. * @param source The source mesh that triggered the event
  37850. * @param evt {Event} The original (browser) event
  37851. */
  37852. ActionEvent.CreateNew = function (source, evt, additionalData) {
  37853. var scene = source.getScene();
  37854. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37855. };
  37856. /**
  37857. * Helper function to auto-create an ActionEvent from a source mesh.
  37858. * @param source The source sprite that triggered the event
  37859. * @param scene Scene associated with the sprite
  37860. * @param evt {Event} The original (browser) event
  37861. */
  37862. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  37863. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37864. };
  37865. /**
  37866. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  37867. * @param scene the scene where the event occurred
  37868. * @param evt {Event} The original (browser) event
  37869. */
  37870. ActionEvent.CreateNewFromScene = function (scene, evt) {
  37871. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  37872. };
  37873. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  37874. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  37875. };
  37876. return ActionEvent;
  37877. }());
  37878. BABYLON.ActionEvent = ActionEvent;
  37879. /**
  37880. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  37881. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  37882. */
  37883. var ActionManager = (function () {
  37884. function ActionManager(scene) {
  37885. // Members
  37886. this.actions = new Array();
  37887. this.hoverCursor = '';
  37888. this._scene = scene;
  37889. scene._actionManagers.push(this);
  37890. }
  37891. Object.defineProperty(ActionManager, "NothingTrigger", {
  37892. get: function () {
  37893. return ActionManager._NothingTrigger;
  37894. },
  37895. enumerable: true,
  37896. configurable: true
  37897. });
  37898. Object.defineProperty(ActionManager, "OnPickTrigger", {
  37899. get: function () {
  37900. return ActionManager._OnPickTrigger;
  37901. },
  37902. enumerable: true,
  37903. configurable: true
  37904. });
  37905. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  37906. get: function () {
  37907. return ActionManager._OnLeftPickTrigger;
  37908. },
  37909. enumerable: true,
  37910. configurable: true
  37911. });
  37912. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  37913. get: function () {
  37914. return ActionManager._OnRightPickTrigger;
  37915. },
  37916. enumerable: true,
  37917. configurable: true
  37918. });
  37919. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  37920. get: function () {
  37921. return ActionManager._OnCenterPickTrigger;
  37922. },
  37923. enumerable: true,
  37924. configurable: true
  37925. });
  37926. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  37927. get: function () {
  37928. return ActionManager._OnPickDownTrigger;
  37929. },
  37930. enumerable: true,
  37931. configurable: true
  37932. });
  37933. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  37934. get: function () {
  37935. return ActionManager._OnDoublePickTrigger;
  37936. },
  37937. enumerable: true,
  37938. configurable: true
  37939. });
  37940. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  37941. get: function () {
  37942. return ActionManager._OnPickUpTrigger;
  37943. },
  37944. enumerable: true,
  37945. configurable: true
  37946. });
  37947. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  37948. /// This trigger will only be raised if you also declared a OnPickDown
  37949. get: function () {
  37950. return ActionManager._OnPickOutTrigger;
  37951. },
  37952. enumerable: true,
  37953. configurable: true
  37954. });
  37955. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  37956. get: function () {
  37957. return ActionManager._OnLongPressTrigger;
  37958. },
  37959. enumerable: true,
  37960. configurable: true
  37961. });
  37962. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  37963. get: function () {
  37964. return ActionManager._OnPointerOverTrigger;
  37965. },
  37966. enumerable: true,
  37967. configurable: true
  37968. });
  37969. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  37970. get: function () {
  37971. return ActionManager._OnPointerOutTrigger;
  37972. },
  37973. enumerable: true,
  37974. configurable: true
  37975. });
  37976. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  37977. get: function () {
  37978. return ActionManager._OnEveryFrameTrigger;
  37979. },
  37980. enumerable: true,
  37981. configurable: true
  37982. });
  37983. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  37984. get: function () {
  37985. return ActionManager._OnIntersectionEnterTrigger;
  37986. },
  37987. enumerable: true,
  37988. configurable: true
  37989. });
  37990. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  37991. get: function () {
  37992. return ActionManager._OnIntersectionExitTrigger;
  37993. },
  37994. enumerable: true,
  37995. configurable: true
  37996. });
  37997. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  37998. get: function () {
  37999. return ActionManager._OnKeyDownTrigger;
  38000. },
  38001. enumerable: true,
  38002. configurable: true
  38003. });
  38004. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38005. get: function () {
  38006. return ActionManager._OnKeyUpTrigger;
  38007. },
  38008. enumerable: true,
  38009. configurable: true
  38010. });
  38011. // Methods
  38012. ActionManager.prototype.dispose = function () {
  38013. var index = this._scene._actionManagers.indexOf(this);
  38014. for (var i = 0; i < this.actions.length; i++) {
  38015. var action = this.actions[i];
  38016. ActionManager.Triggers[action.trigger]--;
  38017. if (ActionManager.Triggers[action.trigger] === 0) {
  38018. delete ActionManager.Triggers[action.trigger];
  38019. }
  38020. }
  38021. if (index > -1) {
  38022. this._scene._actionManagers.splice(index, 1);
  38023. }
  38024. };
  38025. ActionManager.prototype.getScene = function () {
  38026. return this._scene;
  38027. };
  38028. /**
  38029. * Does this action manager handles actions of any of the given triggers
  38030. * @param {number[]} triggers - the triggers to be tested
  38031. * @return {boolean} whether one (or more) of the triggers is handeled
  38032. */
  38033. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38034. for (var index = 0; index < this.actions.length; index++) {
  38035. var action = this.actions[index];
  38036. if (triggers.indexOf(action.trigger) > -1) {
  38037. return true;
  38038. }
  38039. }
  38040. return false;
  38041. };
  38042. /**
  38043. * Does this action manager handles actions of a given trigger
  38044. * @param {number} trigger - the trigger to be tested
  38045. * @return {boolean} whether the trigger is handeled
  38046. */
  38047. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38048. for (var index = 0; index < this.actions.length; index++) {
  38049. var action = this.actions[index];
  38050. if (action.trigger === trigger) {
  38051. return true;
  38052. }
  38053. }
  38054. return false;
  38055. };
  38056. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38057. /**
  38058. * Does this action manager has pointer triggers
  38059. * @return {boolean} whether or not it has pointer triggers
  38060. */
  38061. get: function () {
  38062. for (var index = 0; index < this.actions.length; index++) {
  38063. var action = this.actions[index];
  38064. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38065. return true;
  38066. }
  38067. }
  38068. return false;
  38069. },
  38070. enumerable: true,
  38071. configurable: true
  38072. });
  38073. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38074. /**
  38075. * Does this action manager has pick triggers
  38076. * @return {boolean} whether or not it has pick triggers
  38077. */
  38078. get: function () {
  38079. for (var index = 0; index < this.actions.length; index++) {
  38080. var action = this.actions[index];
  38081. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38082. return true;
  38083. }
  38084. }
  38085. return false;
  38086. },
  38087. enumerable: true,
  38088. configurable: true
  38089. });
  38090. Object.defineProperty(ActionManager, "HasTriggers", {
  38091. /**
  38092. * Does exist one action manager with at least one trigger
  38093. * @return {boolean} whether or not it exists one action manager with one trigger
  38094. **/
  38095. get: function () {
  38096. for (var t in ActionManager.Triggers) {
  38097. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38098. return true;
  38099. }
  38100. }
  38101. return false;
  38102. },
  38103. enumerable: true,
  38104. configurable: true
  38105. });
  38106. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38107. /**
  38108. * Does exist one action manager with at least one pick trigger
  38109. * @return {boolean} whether or not it exists one action manager with one pick trigger
  38110. **/
  38111. get: function () {
  38112. for (var t in ActionManager.Triggers) {
  38113. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38114. var t_int = parseInt(t);
  38115. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  38116. return true;
  38117. }
  38118. }
  38119. }
  38120. return false;
  38121. },
  38122. enumerable: true,
  38123. configurable: true
  38124. });
  38125. /**
  38126. * Does exist one action manager that handles actions of a given trigger
  38127. * @param {number} trigger - the trigger to be tested
  38128. * @return {boolean} whether the trigger is handeled by at least one action manager
  38129. **/
  38130. ActionManager.HasSpecificTrigger = function (trigger) {
  38131. for (var t in ActionManager.Triggers) {
  38132. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38133. var t_int = parseInt(t);
  38134. if (t_int === trigger) {
  38135. return true;
  38136. }
  38137. }
  38138. }
  38139. return false;
  38140. };
  38141. /**
  38142. * Registers an action to this action manager
  38143. * @param {BABYLON.Action} action - the action to be registered
  38144. * @return {BABYLON.Action} the action amended (prepared) after registration
  38145. */
  38146. ActionManager.prototype.registerAction = function (action) {
  38147. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38148. if (this.getScene().actionManager !== this) {
  38149. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38150. return null;
  38151. }
  38152. }
  38153. this.actions.push(action);
  38154. if (ActionManager.Triggers[action.trigger]) {
  38155. ActionManager.Triggers[action.trigger]++;
  38156. }
  38157. else {
  38158. ActionManager.Triggers[action.trigger] = 1;
  38159. }
  38160. action._actionManager = this;
  38161. action._prepare();
  38162. return action;
  38163. };
  38164. /**
  38165. * Process a specific trigger
  38166. * @param {number} trigger - the trigger to process
  38167. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38168. */
  38169. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38170. for (var index = 0; index < this.actions.length; index++) {
  38171. var action = this.actions[index];
  38172. if (action.trigger === trigger) {
  38173. if (trigger === ActionManager.OnKeyUpTrigger
  38174. || trigger === ActionManager.OnKeyDownTrigger) {
  38175. var parameter = action.getTriggerParameter();
  38176. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38177. if (!parameter.toLowerCase) {
  38178. continue;
  38179. }
  38180. var lowerCase = parameter.toLowerCase();
  38181. if (lowerCase !== evt.sourceEvent.key) {
  38182. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38183. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38184. if (actualkey !== lowerCase) {
  38185. continue;
  38186. }
  38187. }
  38188. }
  38189. }
  38190. action._executeCurrent(evt);
  38191. }
  38192. }
  38193. };
  38194. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38195. var properties = propertyPath.split(".");
  38196. for (var index = 0; index < properties.length - 1; index++) {
  38197. target = target[properties[index]];
  38198. }
  38199. return target;
  38200. };
  38201. ActionManager.prototype._getProperty = function (propertyPath) {
  38202. var properties = propertyPath.split(".");
  38203. return properties[properties.length - 1];
  38204. };
  38205. ActionManager.prototype.serialize = function (name) {
  38206. var root = {
  38207. children: [],
  38208. name: name,
  38209. type: 3,
  38210. properties: [] // Empty for root but required
  38211. };
  38212. for (var i = 0; i < this.actions.length; i++) {
  38213. var triggerObject = {
  38214. type: 0,
  38215. children: [],
  38216. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38217. properties: []
  38218. };
  38219. var triggerOptions = this.actions[i].triggerOptions;
  38220. if (triggerOptions && typeof triggerOptions !== "number") {
  38221. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38222. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38223. }
  38224. else {
  38225. var parameter = {};
  38226. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38227. if (triggerOptions.parameter.mesh) {
  38228. parameter._meshId = triggerOptions.parameter.mesh.id;
  38229. }
  38230. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38231. }
  38232. }
  38233. // Serialize child action, recursively
  38234. this.actions[i].serialize(triggerObject);
  38235. // Add serialized trigger
  38236. root.children.push(triggerObject);
  38237. }
  38238. return root;
  38239. };
  38240. ActionManager.Parse = function (parsedActions, object, scene) {
  38241. var actionManager = new BABYLON.ActionManager(scene);
  38242. if (object === null)
  38243. scene.actionManager = actionManager;
  38244. else
  38245. object.actionManager = actionManager;
  38246. // instanciate a new object
  38247. var instanciate = function (name, params) {
  38248. var newInstance = Object.create(BABYLON[name].prototype);
  38249. newInstance.constructor.apply(newInstance, params);
  38250. return newInstance;
  38251. };
  38252. var parseParameter = function (name, value, target, propertyPath) {
  38253. if (propertyPath === null) {
  38254. // String, boolean or float
  38255. var floatValue = parseFloat(value);
  38256. if (value === "true" || value === "false")
  38257. return value === "true";
  38258. else
  38259. return isNaN(floatValue) ? value : floatValue;
  38260. }
  38261. var effectiveTarget = propertyPath.split(".");
  38262. var values = value.split(",");
  38263. // Get effective Target
  38264. for (var i = 0; i < effectiveTarget.length; i++) {
  38265. target = target[effectiveTarget[i]];
  38266. }
  38267. // Return appropriate value with its type
  38268. if (typeof (target) === "boolean")
  38269. return values[0] === "true";
  38270. if (typeof (target) === "string")
  38271. return values[0];
  38272. // Parameters with multiple values such as Vector3 etc.
  38273. var split = new Array();
  38274. for (var i = 0; i < values.length; i++)
  38275. split.push(parseFloat(values[i]));
  38276. if (target instanceof BABYLON.Vector3)
  38277. return BABYLON.Vector3.FromArray(split);
  38278. if (target instanceof BABYLON.Vector4)
  38279. return BABYLON.Vector4.FromArray(split);
  38280. if (target instanceof BABYLON.Color3)
  38281. return BABYLON.Color3.FromArray(split);
  38282. if (target instanceof BABYLON.Color4)
  38283. return BABYLON.Color4.FromArray(split);
  38284. return parseFloat(values[0]);
  38285. };
  38286. // traverse graph per trigger
  38287. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38288. if (combineArray === void 0) { combineArray = null; }
  38289. if (parsedAction.detached)
  38290. return;
  38291. var parameters = new Array();
  38292. var target = null;
  38293. var propertyPath = null;
  38294. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38295. // Parameters
  38296. if (parsedAction.type === 2)
  38297. parameters.push(actionManager);
  38298. else
  38299. parameters.push(trigger);
  38300. if (combine) {
  38301. var actions = new Array();
  38302. for (var j = 0; j < parsedAction.combine.length; j++) {
  38303. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38304. }
  38305. parameters.push(actions);
  38306. }
  38307. else {
  38308. for (var i = 0; i < parsedAction.properties.length; i++) {
  38309. var value = parsedAction.properties[i].value;
  38310. var name = parsedAction.properties[i].name;
  38311. var targetType = parsedAction.properties[i].targetType;
  38312. if (name === "target")
  38313. if (targetType !== null && targetType === "SceneProperties")
  38314. value = target = scene;
  38315. else
  38316. value = target = scene.getNodeByName(value);
  38317. else if (name === "parent")
  38318. value = scene.getNodeByName(value);
  38319. else if (name === "sound")
  38320. value = scene.getSoundByName(value);
  38321. else if (name !== "propertyPath") {
  38322. if (parsedAction.type === 2 && name === "operator")
  38323. value = BABYLON.ValueCondition[value];
  38324. else
  38325. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38326. }
  38327. else {
  38328. propertyPath = value;
  38329. }
  38330. parameters.push(value);
  38331. }
  38332. }
  38333. if (combineArray === null) {
  38334. parameters.push(condition);
  38335. }
  38336. else {
  38337. parameters.push(null);
  38338. }
  38339. // If interpolate value action
  38340. if (parsedAction.name === "InterpolateValueAction") {
  38341. var param = parameters[parameters.length - 2];
  38342. parameters[parameters.length - 1] = param;
  38343. parameters[parameters.length - 2] = condition;
  38344. }
  38345. // Action or condition(s) and not CombineAction
  38346. var newAction = instanciate(parsedAction.name, parameters);
  38347. if (newAction instanceof BABYLON.Condition && condition !== null) {
  38348. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  38349. if (action)
  38350. action.then(nothing);
  38351. else
  38352. actionManager.registerAction(nothing);
  38353. action = nothing;
  38354. }
  38355. if (combineArray === null) {
  38356. if (newAction instanceof BABYLON.Condition) {
  38357. condition = newAction;
  38358. newAction = action;
  38359. }
  38360. else {
  38361. condition = null;
  38362. if (action)
  38363. action.then(newAction);
  38364. else
  38365. actionManager.registerAction(newAction);
  38366. }
  38367. }
  38368. else {
  38369. combineArray.push(newAction);
  38370. }
  38371. for (var i = 0; i < parsedAction.children.length; i++)
  38372. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  38373. };
  38374. // triggers
  38375. for (var i = 0; i < parsedActions.children.length; i++) {
  38376. var triggerParams;
  38377. var trigger = parsedActions.children[i];
  38378. if (trigger.properties.length > 0) {
  38379. var param = trigger.properties[0].value;
  38380. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  38381. if (value._meshId) {
  38382. value.mesh = scene.getMeshByID(value._meshId);
  38383. }
  38384. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  38385. }
  38386. else
  38387. triggerParams = BABYLON.ActionManager[trigger.name];
  38388. for (var j = 0; j < trigger.children.length; j++) {
  38389. if (!trigger.detached)
  38390. traverse(trigger.children[j], triggerParams, null, null);
  38391. }
  38392. }
  38393. };
  38394. ActionManager.GetTriggerName = function (trigger) {
  38395. switch (trigger) {
  38396. case 0: return "NothingTrigger";
  38397. case 1: return "OnPickTrigger";
  38398. case 2: return "OnLeftPickTrigger";
  38399. case 3: return "OnRightPickTrigger";
  38400. case 4: return "OnCenterPickTrigger";
  38401. case 5: return "OnPickDownTrigger";
  38402. case 6: return "OnPickUpTrigger";
  38403. case 7: return "OnLongPressTrigger";
  38404. case 8: return "OnPointerOverTrigger";
  38405. case 9: return "OnPointerOutTrigger";
  38406. case 10: return "OnEveryFrameTrigger";
  38407. case 11: return "OnIntersectionEnterTrigger";
  38408. case 12: return "OnIntersectionExitTrigger";
  38409. case 13: return "OnKeyDownTrigger";
  38410. case 14: return "OnKeyUpTrigger";
  38411. case 15: return "OnPickOutTrigger";
  38412. default: return "";
  38413. }
  38414. };
  38415. // Statics
  38416. ActionManager._NothingTrigger = 0;
  38417. ActionManager._OnPickTrigger = 1;
  38418. ActionManager._OnLeftPickTrigger = 2;
  38419. ActionManager._OnRightPickTrigger = 3;
  38420. ActionManager._OnCenterPickTrigger = 4;
  38421. ActionManager._OnPickDownTrigger = 5;
  38422. ActionManager._OnDoublePickTrigger = 6;
  38423. ActionManager._OnPickUpTrigger = 7;
  38424. ActionManager._OnLongPressTrigger = 8;
  38425. ActionManager._OnPointerOverTrigger = 9;
  38426. ActionManager._OnPointerOutTrigger = 10;
  38427. ActionManager._OnEveryFrameTrigger = 11;
  38428. ActionManager._OnIntersectionEnterTrigger = 12;
  38429. ActionManager._OnIntersectionExitTrigger = 13;
  38430. ActionManager._OnKeyDownTrigger = 14;
  38431. ActionManager._OnKeyUpTrigger = 15;
  38432. ActionManager._OnPickOutTrigger = 16;
  38433. ActionManager.Triggers = {};
  38434. return ActionManager;
  38435. }());
  38436. BABYLON.ActionManager = ActionManager;
  38437. })(BABYLON || (BABYLON = {}));
  38438. //# sourceMappingURL=babylon.actionManager.js.map
  38439. var BABYLON;
  38440. (function (BABYLON) {
  38441. var InterpolateValueAction = (function (_super) {
  38442. __extends(InterpolateValueAction, _super);
  38443. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  38444. if (duration === void 0) { duration = 1000; }
  38445. var _this = _super.call(this, triggerOptions, condition) || this;
  38446. _this.propertyPath = propertyPath;
  38447. _this.value = value;
  38448. _this.duration = duration;
  38449. _this.stopOtherAnimations = stopOtherAnimations;
  38450. _this.onInterpolationDone = onInterpolationDone;
  38451. _this._target = _this._effectiveTarget = target;
  38452. return _this;
  38453. }
  38454. InterpolateValueAction.prototype._prepare = function () {
  38455. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38456. this._property = this._getProperty(this.propertyPath);
  38457. };
  38458. InterpolateValueAction.prototype.execute = function () {
  38459. var scene = this._actionManager.getScene();
  38460. var keys = [
  38461. {
  38462. frame: 0,
  38463. value: this._effectiveTarget[this._property]
  38464. }, {
  38465. frame: 100,
  38466. value: this.value
  38467. }
  38468. ];
  38469. var dataType;
  38470. if (typeof this.value === "number") {
  38471. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  38472. }
  38473. else if (this.value instanceof BABYLON.Color3) {
  38474. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  38475. }
  38476. else if (this.value instanceof BABYLON.Vector3) {
  38477. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  38478. }
  38479. else if (this.value instanceof BABYLON.Matrix) {
  38480. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  38481. }
  38482. else if (this.value instanceof BABYLON.Quaternion) {
  38483. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  38484. }
  38485. else {
  38486. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  38487. return;
  38488. }
  38489. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38490. animation.setKeys(keys);
  38491. if (this.stopOtherAnimations) {
  38492. scene.stopAnimation(this._effectiveTarget);
  38493. }
  38494. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  38495. };
  38496. InterpolateValueAction.prototype.serialize = function (parent) {
  38497. return _super.prototype._serialize.call(this, {
  38498. name: "InterpolateValueAction",
  38499. properties: [
  38500. BABYLON.Action._GetTargetProperty(this._target),
  38501. { name: "propertyPath", value: this.propertyPath },
  38502. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38503. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  38504. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  38505. ]
  38506. }, parent);
  38507. };
  38508. return InterpolateValueAction;
  38509. }(BABYLON.Action));
  38510. BABYLON.InterpolateValueAction = InterpolateValueAction;
  38511. })(BABYLON || (BABYLON = {}));
  38512. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  38513. var BABYLON;
  38514. (function (BABYLON) {
  38515. var SwitchBooleanAction = (function (_super) {
  38516. __extends(SwitchBooleanAction, _super);
  38517. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  38518. var _this = _super.call(this, triggerOptions, condition) || this;
  38519. _this.propertyPath = propertyPath;
  38520. _this._target = _this._effectiveTarget = target;
  38521. return _this;
  38522. }
  38523. SwitchBooleanAction.prototype._prepare = function () {
  38524. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38525. this._property = this._getProperty(this.propertyPath);
  38526. };
  38527. SwitchBooleanAction.prototype.execute = function () {
  38528. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  38529. };
  38530. SwitchBooleanAction.prototype.serialize = function (parent) {
  38531. return _super.prototype._serialize.call(this, {
  38532. name: "SwitchBooleanAction",
  38533. properties: [
  38534. BABYLON.Action._GetTargetProperty(this._target),
  38535. { name: "propertyPath", value: this.propertyPath }
  38536. ]
  38537. }, parent);
  38538. };
  38539. return SwitchBooleanAction;
  38540. }(BABYLON.Action));
  38541. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  38542. var SetStateAction = (function (_super) {
  38543. __extends(SetStateAction, _super);
  38544. function SetStateAction(triggerOptions, target, value, condition) {
  38545. var _this = _super.call(this, triggerOptions, condition) || this;
  38546. _this.value = value;
  38547. _this._target = target;
  38548. return _this;
  38549. }
  38550. SetStateAction.prototype.execute = function () {
  38551. this._target.state = this.value;
  38552. };
  38553. SetStateAction.prototype.serialize = function (parent) {
  38554. return _super.prototype._serialize.call(this, {
  38555. name: "SetStateAction",
  38556. properties: [
  38557. BABYLON.Action._GetTargetProperty(this._target),
  38558. { name: "value", value: this.value }
  38559. ]
  38560. }, parent);
  38561. };
  38562. return SetStateAction;
  38563. }(BABYLON.Action));
  38564. BABYLON.SetStateAction = SetStateAction;
  38565. var SetValueAction = (function (_super) {
  38566. __extends(SetValueAction, _super);
  38567. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  38568. var _this = _super.call(this, triggerOptions, condition) || this;
  38569. _this.propertyPath = propertyPath;
  38570. _this.value = value;
  38571. _this._target = _this._effectiveTarget = target;
  38572. return _this;
  38573. }
  38574. SetValueAction.prototype._prepare = function () {
  38575. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38576. this._property = this._getProperty(this.propertyPath);
  38577. };
  38578. SetValueAction.prototype.execute = function () {
  38579. this._effectiveTarget[this._property] = this.value;
  38580. if (this._target.markAsDirty) {
  38581. this._target.markAsDirty(this._property);
  38582. }
  38583. };
  38584. SetValueAction.prototype.serialize = function (parent) {
  38585. return _super.prototype._serialize.call(this, {
  38586. name: "SetValueAction",
  38587. properties: [
  38588. BABYLON.Action._GetTargetProperty(this._target),
  38589. { name: "propertyPath", value: this.propertyPath },
  38590. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  38591. ]
  38592. }, parent);
  38593. };
  38594. return SetValueAction;
  38595. }(BABYLON.Action));
  38596. BABYLON.SetValueAction = SetValueAction;
  38597. var IncrementValueAction = (function (_super) {
  38598. __extends(IncrementValueAction, _super);
  38599. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  38600. var _this = _super.call(this, triggerOptions, condition) || this;
  38601. _this.propertyPath = propertyPath;
  38602. _this.value = value;
  38603. _this._target = _this._effectiveTarget = target;
  38604. return _this;
  38605. }
  38606. IncrementValueAction.prototype._prepare = function () {
  38607. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38608. this._property = this._getProperty(this.propertyPath);
  38609. if (typeof this._effectiveTarget[this._property] !== "number") {
  38610. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  38611. }
  38612. };
  38613. IncrementValueAction.prototype.execute = function () {
  38614. this._effectiveTarget[this._property] += this.value;
  38615. if (this._target.markAsDirty) {
  38616. this._target.markAsDirty(this._property);
  38617. }
  38618. };
  38619. IncrementValueAction.prototype.serialize = function (parent) {
  38620. return _super.prototype._serialize.call(this, {
  38621. name: "IncrementValueAction",
  38622. properties: [
  38623. BABYLON.Action._GetTargetProperty(this._target),
  38624. { name: "propertyPath", value: this.propertyPath },
  38625. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  38626. ]
  38627. }, parent);
  38628. };
  38629. return IncrementValueAction;
  38630. }(BABYLON.Action));
  38631. BABYLON.IncrementValueAction = IncrementValueAction;
  38632. var PlayAnimationAction = (function (_super) {
  38633. __extends(PlayAnimationAction, _super);
  38634. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  38635. var _this = _super.call(this, triggerOptions, condition) || this;
  38636. _this.from = from;
  38637. _this.to = to;
  38638. _this.loop = loop;
  38639. _this._target = target;
  38640. return _this;
  38641. }
  38642. PlayAnimationAction.prototype._prepare = function () {
  38643. };
  38644. PlayAnimationAction.prototype.execute = function () {
  38645. var scene = this._actionManager.getScene();
  38646. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  38647. };
  38648. PlayAnimationAction.prototype.serialize = function (parent) {
  38649. return _super.prototype._serialize.call(this, {
  38650. name: "PlayAnimationAction",
  38651. properties: [
  38652. BABYLON.Action._GetTargetProperty(this._target),
  38653. { name: "from", value: String(this.from) },
  38654. { name: "to", value: String(this.to) },
  38655. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  38656. ]
  38657. }, parent);
  38658. };
  38659. return PlayAnimationAction;
  38660. }(BABYLON.Action));
  38661. BABYLON.PlayAnimationAction = PlayAnimationAction;
  38662. var StopAnimationAction = (function (_super) {
  38663. __extends(StopAnimationAction, _super);
  38664. function StopAnimationAction(triggerOptions, target, condition) {
  38665. var _this = _super.call(this, triggerOptions, condition) || this;
  38666. _this._target = target;
  38667. return _this;
  38668. }
  38669. StopAnimationAction.prototype._prepare = function () {
  38670. };
  38671. StopAnimationAction.prototype.execute = function () {
  38672. var scene = this._actionManager.getScene();
  38673. scene.stopAnimation(this._target);
  38674. };
  38675. StopAnimationAction.prototype.serialize = function (parent) {
  38676. return _super.prototype._serialize.call(this, {
  38677. name: "StopAnimationAction",
  38678. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  38679. }, parent);
  38680. };
  38681. return StopAnimationAction;
  38682. }(BABYLON.Action));
  38683. BABYLON.StopAnimationAction = StopAnimationAction;
  38684. var DoNothingAction = (function (_super) {
  38685. __extends(DoNothingAction, _super);
  38686. function DoNothingAction(triggerOptions, condition) {
  38687. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  38688. return _super.call(this, triggerOptions, condition) || this;
  38689. }
  38690. DoNothingAction.prototype.execute = function () {
  38691. };
  38692. DoNothingAction.prototype.serialize = function (parent) {
  38693. return _super.prototype._serialize.call(this, {
  38694. name: "DoNothingAction",
  38695. properties: []
  38696. }, parent);
  38697. };
  38698. return DoNothingAction;
  38699. }(BABYLON.Action));
  38700. BABYLON.DoNothingAction = DoNothingAction;
  38701. var CombineAction = (function (_super) {
  38702. __extends(CombineAction, _super);
  38703. function CombineAction(triggerOptions, children, condition) {
  38704. var _this = _super.call(this, triggerOptions, condition) || this;
  38705. _this.children = children;
  38706. return _this;
  38707. }
  38708. CombineAction.prototype._prepare = function () {
  38709. for (var index = 0; index < this.children.length; index++) {
  38710. this.children[index]._actionManager = this._actionManager;
  38711. this.children[index]._prepare();
  38712. }
  38713. };
  38714. CombineAction.prototype.execute = function (evt) {
  38715. for (var index = 0; index < this.children.length; index++) {
  38716. this.children[index].execute(evt);
  38717. }
  38718. };
  38719. CombineAction.prototype.serialize = function (parent) {
  38720. var serializationObject = _super.prototype._serialize.call(this, {
  38721. name: "CombineAction",
  38722. properties: [],
  38723. combine: []
  38724. }, parent);
  38725. for (var i = 0; i < this.children.length; i++) {
  38726. serializationObject.combine.push(this.children[i].serialize(null));
  38727. }
  38728. return serializationObject;
  38729. };
  38730. return CombineAction;
  38731. }(BABYLON.Action));
  38732. BABYLON.CombineAction = CombineAction;
  38733. var ExecuteCodeAction = (function (_super) {
  38734. __extends(ExecuteCodeAction, _super);
  38735. function ExecuteCodeAction(triggerOptions, func, condition) {
  38736. var _this = _super.call(this, triggerOptions, condition) || this;
  38737. _this.func = func;
  38738. return _this;
  38739. }
  38740. ExecuteCodeAction.prototype.execute = function (evt) {
  38741. this.func(evt);
  38742. };
  38743. return ExecuteCodeAction;
  38744. }(BABYLON.Action));
  38745. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  38746. var SetParentAction = (function (_super) {
  38747. __extends(SetParentAction, _super);
  38748. function SetParentAction(triggerOptions, target, parent, condition) {
  38749. var _this = _super.call(this, triggerOptions, condition) || this;
  38750. _this._target = target;
  38751. _this._parent = parent;
  38752. return _this;
  38753. }
  38754. SetParentAction.prototype._prepare = function () {
  38755. };
  38756. SetParentAction.prototype.execute = function () {
  38757. if (this._target.parent === this._parent) {
  38758. return;
  38759. }
  38760. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  38761. invertParentWorldMatrix.invert();
  38762. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  38763. this._target.parent = this._parent;
  38764. };
  38765. SetParentAction.prototype.serialize = function (parent) {
  38766. return _super.prototype._serialize.call(this, {
  38767. name: "SetParentAction",
  38768. properties: [
  38769. BABYLON.Action._GetTargetProperty(this._target),
  38770. BABYLON.Action._GetTargetProperty(this._parent),
  38771. ]
  38772. }, parent);
  38773. };
  38774. return SetParentAction;
  38775. }(BABYLON.Action));
  38776. BABYLON.SetParentAction = SetParentAction;
  38777. var PlaySoundAction = (function (_super) {
  38778. __extends(PlaySoundAction, _super);
  38779. function PlaySoundAction(triggerOptions, sound, condition) {
  38780. var _this = _super.call(this, triggerOptions, condition) || this;
  38781. _this._sound = sound;
  38782. return _this;
  38783. }
  38784. PlaySoundAction.prototype._prepare = function () {
  38785. };
  38786. PlaySoundAction.prototype.execute = function () {
  38787. if (this._sound !== undefined)
  38788. this._sound.play();
  38789. };
  38790. PlaySoundAction.prototype.serialize = function (parent) {
  38791. return _super.prototype._serialize.call(this, {
  38792. name: "PlaySoundAction",
  38793. properties: [{ name: "sound", value: this._sound.name }]
  38794. }, parent);
  38795. };
  38796. return PlaySoundAction;
  38797. }(BABYLON.Action));
  38798. BABYLON.PlaySoundAction = PlaySoundAction;
  38799. var StopSoundAction = (function (_super) {
  38800. __extends(StopSoundAction, _super);
  38801. function StopSoundAction(triggerOptions, sound, condition) {
  38802. var _this = _super.call(this, triggerOptions, condition) || this;
  38803. _this._sound = sound;
  38804. return _this;
  38805. }
  38806. StopSoundAction.prototype._prepare = function () {
  38807. };
  38808. StopSoundAction.prototype.execute = function () {
  38809. if (this._sound !== undefined)
  38810. this._sound.stop();
  38811. };
  38812. StopSoundAction.prototype.serialize = function (parent) {
  38813. return _super.prototype._serialize.call(this, {
  38814. name: "StopSoundAction",
  38815. properties: [{ name: "sound", value: this._sound.name }]
  38816. }, parent);
  38817. };
  38818. return StopSoundAction;
  38819. }(BABYLON.Action));
  38820. BABYLON.StopSoundAction = StopSoundAction;
  38821. })(BABYLON || (BABYLON = {}));
  38822. //# sourceMappingURL=babylon.directActions.js.map
  38823. var BABYLON;
  38824. (function (BABYLON) {
  38825. var SpriteManager = (function () {
  38826. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  38827. if (epsilon === void 0) { epsilon = 0.01; }
  38828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38829. this.name = name;
  38830. this.sprites = new Array();
  38831. this.renderingGroupId = 0;
  38832. this.layerMask = 0x0FFFFFFF;
  38833. this.fogEnabled = true;
  38834. this.isPickable = false;
  38835. /**
  38836. * An event triggered when the manager is disposed.
  38837. * @type {BABYLON.Observable}
  38838. */
  38839. this.onDisposeObservable = new BABYLON.Observable();
  38840. this._vertexBuffers = {};
  38841. this._capacity = capacity;
  38842. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  38843. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38844. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38845. if (cellSize.width && cellSize.height) {
  38846. this.cellWidth = cellSize.width;
  38847. this.cellHeight = cellSize.height;
  38848. }
  38849. else if (cellSize !== undefined) {
  38850. this.cellWidth = cellSize;
  38851. this.cellHeight = cellSize;
  38852. }
  38853. else {
  38854. return;
  38855. }
  38856. this._epsilon = epsilon;
  38857. this._scene = scene;
  38858. this._scene.spriteManagers.push(this);
  38859. var indices = [];
  38860. var index = 0;
  38861. for (var count = 0; count < capacity; count++) {
  38862. indices.push(index);
  38863. indices.push(index + 1);
  38864. indices.push(index + 2);
  38865. indices.push(index);
  38866. indices.push(index + 2);
  38867. indices.push(index + 3);
  38868. index += 4;
  38869. }
  38870. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38871. // VBO
  38872. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  38873. this._vertexData = new Float32Array(capacity * 16 * 4);
  38874. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  38875. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  38876. var options = this._buffer.createVertexBuffer("options", 4, 4);
  38877. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  38878. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  38879. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  38880. this._vertexBuffers["options"] = options;
  38881. this._vertexBuffers["cellInfo"] = cellInfo;
  38882. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  38883. // Effects
  38884. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  38885. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  38886. }
  38887. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  38888. set: function (callback) {
  38889. if (this._onDisposeObserver) {
  38890. this.onDisposeObservable.remove(this._onDisposeObserver);
  38891. }
  38892. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38893. },
  38894. enumerable: true,
  38895. configurable: true
  38896. });
  38897. Object.defineProperty(SpriteManager.prototype, "texture", {
  38898. get: function () {
  38899. return this._spriteTexture;
  38900. },
  38901. set: function (value) {
  38902. this._spriteTexture = value;
  38903. },
  38904. enumerable: true,
  38905. configurable: true
  38906. });
  38907. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  38908. var arrayOffset = index * 16;
  38909. if (offsetX === 0)
  38910. offsetX = this._epsilon;
  38911. else if (offsetX === 1)
  38912. offsetX = 1 - this._epsilon;
  38913. if (offsetY === 0)
  38914. offsetY = this._epsilon;
  38915. else if (offsetY === 1)
  38916. offsetY = 1 - this._epsilon;
  38917. this._vertexData[arrayOffset] = sprite.position.x;
  38918. this._vertexData[arrayOffset + 1] = sprite.position.y;
  38919. this._vertexData[arrayOffset + 2] = sprite.position.z;
  38920. this._vertexData[arrayOffset + 3] = sprite.angle;
  38921. this._vertexData[arrayOffset + 4] = sprite.width;
  38922. this._vertexData[arrayOffset + 5] = sprite.height;
  38923. this._vertexData[arrayOffset + 6] = offsetX;
  38924. this._vertexData[arrayOffset + 7] = offsetY;
  38925. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  38926. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  38927. var offset = (sprite.cellIndex / rowSize) >> 0;
  38928. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  38929. this._vertexData[arrayOffset + 11] = offset;
  38930. // Color
  38931. this._vertexData[arrayOffset + 12] = sprite.color.r;
  38932. this._vertexData[arrayOffset + 13] = sprite.color.g;
  38933. this._vertexData[arrayOffset + 14] = sprite.color.b;
  38934. this._vertexData[arrayOffset + 15] = sprite.color.a;
  38935. };
  38936. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  38937. var count = Math.min(this._capacity, this.sprites.length);
  38938. var min = BABYLON.Vector3.Zero();
  38939. var max = BABYLON.Vector3.Zero();
  38940. var distance = Number.MAX_VALUE;
  38941. var currentSprite;
  38942. var cameraSpacePosition = BABYLON.Vector3.Zero();
  38943. var cameraView = camera.getViewMatrix();
  38944. for (var index = 0; index < count; index++) {
  38945. var sprite = this.sprites[index];
  38946. if (!sprite) {
  38947. continue;
  38948. }
  38949. if (predicate) {
  38950. if (!predicate(sprite)) {
  38951. continue;
  38952. }
  38953. }
  38954. else if (!sprite.isPickable) {
  38955. continue;
  38956. }
  38957. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  38958. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  38959. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  38960. if (ray.intersectsBoxMinMax(min, max)) {
  38961. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  38962. if (distance > currentDistance) {
  38963. distance = currentDistance;
  38964. currentSprite = sprite;
  38965. if (fastCheck) {
  38966. break;
  38967. }
  38968. }
  38969. }
  38970. }
  38971. if (currentSprite) {
  38972. var result = new BABYLON.PickingInfo();
  38973. result.hit = true;
  38974. result.pickedSprite = currentSprite;
  38975. result.distance = distance;
  38976. return result;
  38977. }
  38978. return null;
  38979. };
  38980. SpriteManager.prototype.render = function () {
  38981. // Check
  38982. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  38983. return;
  38984. var engine = this._scene.getEngine();
  38985. var baseSize = this._spriteTexture.getBaseSize();
  38986. // Sprites
  38987. var deltaTime = engine.getDeltaTime();
  38988. var max = Math.min(this._capacity, this.sprites.length);
  38989. var rowSize = baseSize.width / this.cellWidth;
  38990. var offset = 0;
  38991. for (var index = 0; index < max; index++) {
  38992. var sprite = this.sprites[index];
  38993. if (!sprite) {
  38994. continue;
  38995. }
  38996. sprite._animate(deltaTime);
  38997. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  38998. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  38999. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39000. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39001. }
  39002. this._buffer.update(this._vertexData);
  39003. // Render
  39004. var effect = this._effectBase;
  39005. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39006. effect = this._effectFog;
  39007. }
  39008. engine.enableEffect(effect);
  39009. var viewMatrix = this._scene.getViewMatrix();
  39010. effect.setTexture("diffuseSampler", this._spriteTexture);
  39011. effect.setMatrix("view", viewMatrix);
  39012. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39013. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39014. // Fog
  39015. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39016. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39017. effect.setColor3("vFogColor", this._scene.fogColor);
  39018. }
  39019. // VBOs
  39020. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39021. // Draw order
  39022. engine.setDepthFunctionToLessOrEqual();
  39023. effect.setBool("alphaTest", true);
  39024. engine.setColorWrite(false);
  39025. engine.draw(true, 0, max * 6);
  39026. engine.setColorWrite(true);
  39027. effect.setBool("alphaTest", false);
  39028. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39029. engine.draw(true, 0, max * 6);
  39030. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39031. };
  39032. SpriteManager.prototype.dispose = function () {
  39033. if (this._buffer) {
  39034. this._buffer.dispose();
  39035. this._buffer = null;
  39036. }
  39037. if (this._indexBuffer) {
  39038. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39039. this._indexBuffer = null;
  39040. }
  39041. if (this._spriteTexture) {
  39042. this._spriteTexture.dispose();
  39043. this._spriteTexture = null;
  39044. }
  39045. // Remove from scene
  39046. var index = this._scene.spriteManagers.indexOf(this);
  39047. this._scene.spriteManagers.splice(index, 1);
  39048. // Callback
  39049. this.onDisposeObservable.notifyObservers(this);
  39050. this.onDisposeObservable.clear();
  39051. };
  39052. return SpriteManager;
  39053. }());
  39054. BABYLON.SpriteManager = SpriteManager;
  39055. })(BABYLON || (BABYLON = {}));
  39056. //# sourceMappingURL=babylon.spriteManager.js.map
  39057. var BABYLON;
  39058. (function (BABYLON) {
  39059. var Sprite = (function () {
  39060. function Sprite(name, manager) {
  39061. this.name = name;
  39062. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39063. this.width = 1.0;
  39064. this.height = 1.0;
  39065. this.angle = 0;
  39066. this.cellIndex = 0;
  39067. this.invertU = 0;
  39068. this.invertV = 0;
  39069. this.animations = new Array();
  39070. this.isPickable = false;
  39071. this._animationStarted = false;
  39072. this._loopAnimation = false;
  39073. this._fromIndex = 0;
  39074. this._toIndex = 0;
  39075. this._delay = 0;
  39076. this._direction = 1;
  39077. this._frameCount = 0;
  39078. this._time = 0;
  39079. this._manager = manager;
  39080. this._manager.sprites.push(this);
  39081. this.position = BABYLON.Vector3.Zero();
  39082. }
  39083. Object.defineProperty(Sprite.prototype, "size", {
  39084. get: function () {
  39085. return this.width;
  39086. },
  39087. set: function (value) {
  39088. this.width = value;
  39089. this.height = value;
  39090. },
  39091. enumerable: true,
  39092. configurable: true
  39093. });
  39094. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39095. this._fromIndex = from;
  39096. this._toIndex = to;
  39097. this._loopAnimation = loop;
  39098. this._delay = delay;
  39099. this._animationStarted = true;
  39100. this._direction = from < to ? 1 : -1;
  39101. this.cellIndex = from;
  39102. this._time = 0;
  39103. this._onAnimationEnd = onAnimationEnd;
  39104. };
  39105. Sprite.prototype.stopAnimation = function () {
  39106. this._animationStarted = false;
  39107. };
  39108. Sprite.prototype._animate = function (deltaTime) {
  39109. if (!this._animationStarted)
  39110. return;
  39111. this._time += deltaTime;
  39112. if (this._time > this._delay) {
  39113. this._time = this._time % this._delay;
  39114. this.cellIndex += this._direction;
  39115. if (this.cellIndex === this._toIndex) {
  39116. if (this._loopAnimation) {
  39117. this.cellIndex = this._fromIndex;
  39118. }
  39119. else {
  39120. this._animationStarted = false;
  39121. if (this._onAnimationEnd) {
  39122. this._onAnimationEnd();
  39123. }
  39124. if (this.disposeWhenFinishedAnimating) {
  39125. this.dispose();
  39126. }
  39127. }
  39128. }
  39129. }
  39130. };
  39131. Sprite.prototype.dispose = function () {
  39132. for (var i = 0; i < this._manager.sprites.length; i++) {
  39133. if (this._manager.sprites[i] == this) {
  39134. this._manager.sprites.splice(i, 1);
  39135. }
  39136. }
  39137. };
  39138. return Sprite;
  39139. }());
  39140. BABYLON.Sprite = Sprite;
  39141. })(BABYLON || (BABYLON = {}));
  39142. //# sourceMappingURL=babylon.sprite.js.map
  39143. var BABYLON;
  39144. (function (BABYLON) {
  39145. var IntersectionInfo = (function () {
  39146. function IntersectionInfo(bu, bv, distance) {
  39147. this.bu = bu;
  39148. this.bv = bv;
  39149. this.distance = distance;
  39150. this.faceId = 0;
  39151. this.subMeshId = 0;
  39152. }
  39153. return IntersectionInfo;
  39154. }());
  39155. BABYLON.IntersectionInfo = IntersectionInfo;
  39156. var PickingInfo = (function () {
  39157. function PickingInfo() {
  39158. this.hit = false;
  39159. this.distance = 0;
  39160. this.pickedPoint = null;
  39161. this.pickedMesh = null;
  39162. this.bu = 0;
  39163. this.bv = 0;
  39164. this.faceId = -1;
  39165. this.subMeshId = 0;
  39166. this.pickedSprite = null;
  39167. }
  39168. // Methods
  39169. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  39170. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  39171. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  39172. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39173. return null;
  39174. }
  39175. var indices = this.pickedMesh.getIndices();
  39176. var result;
  39177. if (useVerticesNormals) {
  39178. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39179. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  39180. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  39181. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  39182. normal0 = normal0.scale(this.bu);
  39183. normal1 = normal1.scale(this.bv);
  39184. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  39185. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  39186. }
  39187. else {
  39188. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39189. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  39190. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  39191. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  39192. var p1p2 = vertex1.subtract(vertex2);
  39193. var p3p2 = vertex3.subtract(vertex2);
  39194. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  39195. }
  39196. if (useWorldCoordinates) {
  39197. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  39198. }
  39199. return BABYLON.Vector3.Normalize(result);
  39200. };
  39201. PickingInfo.prototype.getTextureCoordinates = function () {
  39202. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39203. return null;
  39204. }
  39205. var indices = this.pickedMesh.getIndices();
  39206. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39207. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  39208. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  39209. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  39210. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  39211. uv1 = uv1.scale(this.bu);
  39212. uv2 = uv2.scale(this.bv);
  39213. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  39214. };
  39215. return PickingInfo;
  39216. }());
  39217. BABYLON.PickingInfo = PickingInfo;
  39218. })(BABYLON || (BABYLON = {}));
  39219. //# sourceMappingURL=babylon.pickingInfo.js.map
  39220. var BABYLON;
  39221. (function (BABYLON) {
  39222. var Ray = (function () {
  39223. function Ray(origin, direction, length) {
  39224. if (length === void 0) { length = Number.MAX_VALUE; }
  39225. this.origin = origin;
  39226. this.direction = direction;
  39227. this.length = length;
  39228. }
  39229. // Methods
  39230. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  39231. var d = 0.0;
  39232. var maxValue = Number.MAX_VALUE;
  39233. var inv;
  39234. var min;
  39235. var max;
  39236. var temp;
  39237. if (Math.abs(this.direction.x) < 0.0000001) {
  39238. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  39239. return false;
  39240. }
  39241. }
  39242. else {
  39243. inv = 1.0 / this.direction.x;
  39244. min = (minimum.x - this.origin.x) * inv;
  39245. max = (maximum.x - this.origin.x) * inv;
  39246. if (max === -Infinity) {
  39247. max = Infinity;
  39248. }
  39249. if (min > max) {
  39250. temp = min;
  39251. min = max;
  39252. max = temp;
  39253. }
  39254. d = Math.max(min, d);
  39255. maxValue = Math.min(max, maxValue);
  39256. if (d > maxValue) {
  39257. return false;
  39258. }
  39259. }
  39260. if (Math.abs(this.direction.y) < 0.0000001) {
  39261. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  39262. return false;
  39263. }
  39264. }
  39265. else {
  39266. inv = 1.0 / this.direction.y;
  39267. min = (minimum.y - this.origin.y) * inv;
  39268. max = (maximum.y - this.origin.y) * inv;
  39269. if (max === -Infinity) {
  39270. max = Infinity;
  39271. }
  39272. if (min > max) {
  39273. temp = min;
  39274. min = max;
  39275. max = temp;
  39276. }
  39277. d = Math.max(min, d);
  39278. maxValue = Math.min(max, maxValue);
  39279. if (d > maxValue) {
  39280. return false;
  39281. }
  39282. }
  39283. if (Math.abs(this.direction.z) < 0.0000001) {
  39284. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  39285. return false;
  39286. }
  39287. }
  39288. else {
  39289. inv = 1.0 / this.direction.z;
  39290. min = (minimum.z - this.origin.z) * inv;
  39291. max = (maximum.z - this.origin.z) * inv;
  39292. if (max === -Infinity) {
  39293. max = Infinity;
  39294. }
  39295. if (min > max) {
  39296. temp = min;
  39297. min = max;
  39298. max = temp;
  39299. }
  39300. d = Math.max(min, d);
  39301. maxValue = Math.min(max, maxValue);
  39302. if (d > maxValue) {
  39303. return false;
  39304. }
  39305. }
  39306. return true;
  39307. };
  39308. Ray.prototype.intersectsBox = function (box) {
  39309. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  39310. };
  39311. Ray.prototype.intersectsSphere = function (sphere) {
  39312. var x = sphere.center.x - this.origin.x;
  39313. var y = sphere.center.y - this.origin.y;
  39314. var z = sphere.center.z - this.origin.z;
  39315. var pyth = (x * x) + (y * y) + (z * z);
  39316. var rr = sphere.radius * sphere.radius;
  39317. if (pyth <= rr) {
  39318. return true;
  39319. }
  39320. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  39321. if (dot < 0.0) {
  39322. return false;
  39323. }
  39324. var temp = pyth - (dot * dot);
  39325. return temp <= rr;
  39326. };
  39327. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  39328. if (!this._edge1) {
  39329. this._edge1 = BABYLON.Vector3.Zero();
  39330. this._edge2 = BABYLON.Vector3.Zero();
  39331. this._pvec = BABYLON.Vector3.Zero();
  39332. this._tvec = BABYLON.Vector3.Zero();
  39333. this._qvec = BABYLON.Vector3.Zero();
  39334. }
  39335. vertex1.subtractToRef(vertex0, this._edge1);
  39336. vertex2.subtractToRef(vertex0, this._edge2);
  39337. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  39338. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  39339. if (det === 0) {
  39340. return null;
  39341. }
  39342. var invdet = 1 / det;
  39343. this.origin.subtractToRef(vertex0, this._tvec);
  39344. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  39345. if (bu < 0 || bu > 1.0) {
  39346. return null;
  39347. }
  39348. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  39349. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  39350. if (bv < 0 || bu + bv > 1.0) {
  39351. return null;
  39352. }
  39353. //check if the distance is longer than the predefined length.
  39354. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  39355. if (distance > this.length) {
  39356. return null;
  39357. }
  39358. return new BABYLON.IntersectionInfo(bu, bv, distance);
  39359. };
  39360. Ray.prototype.intersectsPlane = function (plane) {
  39361. var distance;
  39362. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  39363. if (Math.abs(result1) < 9.99999997475243E-07) {
  39364. return null;
  39365. }
  39366. else {
  39367. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  39368. distance = (-plane.d - result2) / result1;
  39369. if (distance < 0.0) {
  39370. if (distance < -9.99999997475243E-07) {
  39371. return null;
  39372. }
  39373. else {
  39374. return 0;
  39375. }
  39376. }
  39377. return distance;
  39378. }
  39379. };
  39380. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  39381. var tm = BABYLON.Tmp.Matrix[0];
  39382. mesh.getWorldMatrix().invertToRef(tm);
  39383. if (this._tmpRay) {
  39384. Ray.TransformToRef(this, tm, this._tmpRay);
  39385. }
  39386. else {
  39387. this._tmpRay = Ray.Transform(this, tm);
  39388. }
  39389. return mesh.intersects(this._tmpRay, fastCheck);
  39390. };
  39391. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  39392. if (results) {
  39393. results.length = 0;
  39394. }
  39395. else {
  39396. results = [];
  39397. }
  39398. for (var i = 0; i < meshes.length; i++) {
  39399. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  39400. if (pickInfo.hit) {
  39401. results.push(pickInfo);
  39402. }
  39403. }
  39404. results.sort(this._comparePickingInfo);
  39405. return results;
  39406. };
  39407. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  39408. if (pickingInfoA.distance < pickingInfoB.distance) {
  39409. return -1;
  39410. }
  39411. else if (pickingInfoA.distance > pickingInfoB.distance) {
  39412. return 1;
  39413. }
  39414. else {
  39415. return 0;
  39416. }
  39417. };
  39418. /**
  39419. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  39420. * @param sega the first point of the segment to test the intersection against
  39421. * @param segb the second point of the segment to test the intersection against
  39422. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  39423. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  39424. */
  39425. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  39426. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  39427. var u = segb.subtract(sega);
  39428. var v = rsegb.subtract(this.origin);
  39429. var w = sega.subtract(this.origin);
  39430. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  39431. var b = BABYLON.Vector3.Dot(u, v);
  39432. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  39433. var d = BABYLON.Vector3.Dot(u, w);
  39434. var e = BABYLON.Vector3.Dot(v, w);
  39435. var D = a * c - b * b; // always >= 0
  39436. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  39437. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  39438. // compute the line parameters of the two closest points
  39439. if (D < Ray.smallnum) {
  39440. sN = 0.0; // force using point P0 on segment S1
  39441. sD = 1.0; // to prevent possible division by 0.0 later
  39442. tN = e;
  39443. tD = c;
  39444. }
  39445. else {
  39446. sN = (b * e - c * d);
  39447. tN = (a * e - b * d);
  39448. if (sN < 0.0) {
  39449. sN = 0.0;
  39450. tN = e;
  39451. tD = c;
  39452. }
  39453. else if (sN > sD) {
  39454. sN = sD;
  39455. tN = e + b;
  39456. tD = c;
  39457. }
  39458. }
  39459. if (tN < 0.0) {
  39460. tN = 0.0;
  39461. // recompute sc for this edge
  39462. if (-d < 0.0) {
  39463. sN = 0.0;
  39464. }
  39465. else if (-d > a)
  39466. sN = sD;
  39467. else {
  39468. sN = -d;
  39469. sD = a;
  39470. }
  39471. }
  39472. else if (tN > tD) {
  39473. tN = tD;
  39474. // recompute sc for this edge
  39475. if ((-d + b) < 0.0) {
  39476. sN = 0;
  39477. }
  39478. else if ((-d + b) > a) {
  39479. sN = sD;
  39480. }
  39481. else {
  39482. sN = (-d + b);
  39483. sD = a;
  39484. }
  39485. }
  39486. // finally do the division to get sc and tc
  39487. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  39488. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  39489. // get the difference of the two closest points
  39490. var qtc = v.multiplyByFloats(tc, tc, tc);
  39491. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  39492. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  39493. if (isIntersected) {
  39494. return qtc.length();
  39495. }
  39496. return -1;
  39497. };
  39498. // Statics
  39499. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  39500. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  39501. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  39502. var direction = end.subtract(start);
  39503. direction.normalize();
  39504. return new Ray(start, direction);
  39505. };
  39506. /**
  39507. * 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
  39508. * transformed to the given world matrix.
  39509. * @param origin The origin point
  39510. * @param end The end point
  39511. * @param world a matrix to transform the ray to. Default is the identity matrix.
  39512. */
  39513. Ray.CreateNewFromTo = function (origin, end, world) {
  39514. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  39515. var direction = end.subtract(origin);
  39516. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  39517. direction.normalize();
  39518. return Ray.Transform(new Ray(origin, direction, length), world);
  39519. };
  39520. Ray.Transform = function (ray, matrix) {
  39521. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  39522. Ray.TransformToRef(ray, matrix, result);
  39523. return result;
  39524. };
  39525. Ray.TransformToRef = function (ray, matrix, result) {
  39526. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  39527. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  39528. result.length = ray.length;
  39529. var dir = result.direction;
  39530. var len = dir.length();
  39531. if (!(len === 0 || len === 1)) {
  39532. var num = 1.0 / len;
  39533. dir.x *= num;
  39534. dir.y *= num;
  39535. dir.z *= num;
  39536. result.length *= len;
  39537. }
  39538. };
  39539. Ray.smallnum = 0.00000001;
  39540. Ray.rayl = 10e8;
  39541. return Ray;
  39542. }());
  39543. BABYLON.Ray = Ray;
  39544. })(BABYLON || (BABYLON = {}));
  39545. //# sourceMappingURL=babylon.ray.js.map
  39546. var BABYLON;
  39547. (function (BABYLON) {
  39548. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  39549. if (boxMin.x > sphereCenter.x + sphereRadius)
  39550. return false;
  39551. if (sphereCenter.x - sphereRadius > boxMax.x)
  39552. return false;
  39553. if (boxMin.y > sphereCenter.y + sphereRadius)
  39554. return false;
  39555. if (sphereCenter.y - sphereRadius > boxMax.y)
  39556. return false;
  39557. if (boxMin.z > sphereCenter.z + sphereRadius)
  39558. return false;
  39559. if (sphereCenter.z - sphereRadius > boxMax.z)
  39560. return false;
  39561. return true;
  39562. };
  39563. var getLowestRoot = (function () {
  39564. var result = { root: 0, found: false };
  39565. return function (a, b, c, maxR) {
  39566. result.root = 0;
  39567. result.found = false;
  39568. var determinant = b * b - 4.0 * a * c;
  39569. if (determinant < 0)
  39570. return result;
  39571. var sqrtD = Math.sqrt(determinant);
  39572. var r1 = (-b - sqrtD) / (2.0 * a);
  39573. var r2 = (-b + sqrtD) / (2.0 * a);
  39574. if (r1 > r2) {
  39575. var temp = r2;
  39576. r2 = r1;
  39577. r1 = temp;
  39578. }
  39579. if (r1 > 0 && r1 < maxR) {
  39580. result.root = r1;
  39581. result.found = true;
  39582. return result;
  39583. }
  39584. if (r2 > 0 && r2 < maxR) {
  39585. result.root = r2;
  39586. result.found = true;
  39587. return result;
  39588. }
  39589. return result;
  39590. };
  39591. })();
  39592. var Collider = (function () {
  39593. function Collider() {
  39594. this.radius = BABYLON.Vector3.One();
  39595. this.retry = 0;
  39596. this.basePointWorld = BABYLON.Vector3.Zero();
  39597. this.velocityWorld = BABYLON.Vector3.Zero();
  39598. this.normalizedVelocity = BABYLON.Vector3.Zero();
  39599. this._collisionPoint = BABYLON.Vector3.Zero();
  39600. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  39601. this._tempVector = BABYLON.Vector3.Zero();
  39602. this._tempVector2 = BABYLON.Vector3.Zero();
  39603. this._tempVector3 = BABYLON.Vector3.Zero();
  39604. this._tempVector4 = BABYLON.Vector3.Zero();
  39605. this._edge = BABYLON.Vector3.Zero();
  39606. this._baseToVertex = BABYLON.Vector3.Zero();
  39607. this._destinationPoint = BABYLON.Vector3.Zero();
  39608. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  39609. this._displacementVector = BABYLON.Vector3.Zero();
  39610. this._collisionMask = -1;
  39611. }
  39612. Object.defineProperty(Collider.prototype, "collisionMask", {
  39613. get: function () {
  39614. return this._collisionMask;
  39615. },
  39616. set: function (mask) {
  39617. this._collisionMask = !isNaN(mask) ? mask : -1;
  39618. },
  39619. enumerable: true,
  39620. configurable: true
  39621. });
  39622. // Methods
  39623. Collider.prototype._initialize = function (source, dir, e) {
  39624. this.velocity = dir;
  39625. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  39626. this.basePoint = source;
  39627. source.multiplyToRef(this.radius, this.basePointWorld);
  39628. dir.multiplyToRef(this.radius, this.velocityWorld);
  39629. this.velocityWorldLength = this.velocityWorld.length();
  39630. this.epsilon = e;
  39631. this.collisionFound = false;
  39632. };
  39633. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  39634. pa.subtractToRef(point, this._tempVector);
  39635. pb.subtractToRef(point, this._tempVector2);
  39636. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  39637. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39638. if (d < 0)
  39639. return false;
  39640. pc.subtractToRef(point, this._tempVector3);
  39641. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  39642. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39643. if (d < 0)
  39644. return false;
  39645. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  39646. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39647. return d >= 0;
  39648. };
  39649. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  39650. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  39651. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  39652. if (distance > this.velocityWorldLength + max + sphereRadius) {
  39653. return false;
  39654. }
  39655. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  39656. return false;
  39657. return true;
  39658. };
  39659. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  39660. var t0;
  39661. var embeddedInPlane = false;
  39662. //defensive programming, actually not needed.
  39663. if (!trianglePlaneArray) {
  39664. trianglePlaneArray = [];
  39665. }
  39666. if (!trianglePlaneArray[faceIndex]) {
  39667. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  39668. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  39669. }
  39670. var trianglePlane = trianglePlaneArray[faceIndex];
  39671. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  39672. return;
  39673. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  39674. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  39675. if (normalDotVelocity == 0) {
  39676. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  39677. return;
  39678. embeddedInPlane = true;
  39679. t0 = 0;
  39680. }
  39681. else {
  39682. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39683. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39684. if (t0 > t1) {
  39685. var temp = t1;
  39686. t1 = t0;
  39687. t0 = temp;
  39688. }
  39689. if (t0 > 1.0 || t1 < 0.0)
  39690. return;
  39691. if (t0 < 0)
  39692. t0 = 0;
  39693. if (t0 > 1.0)
  39694. t0 = 1.0;
  39695. }
  39696. this._collisionPoint.copyFromFloats(0, 0, 0);
  39697. var found = false;
  39698. var t = 1.0;
  39699. if (!embeddedInPlane) {
  39700. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  39701. this.velocity.scaleToRef(t0, this._tempVector);
  39702. this._planeIntersectionPoint.addInPlace(this._tempVector);
  39703. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  39704. found = true;
  39705. t = t0;
  39706. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  39707. }
  39708. }
  39709. if (!found) {
  39710. var velocitySquaredLength = this.velocity.lengthSquared();
  39711. var a = velocitySquaredLength;
  39712. this.basePoint.subtractToRef(p1, this._tempVector);
  39713. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39714. var c = this._tempVector.lengthSquared() - 1.0;
  39715. var lowestRoot = getLowestRoot(a, b, c, t);
  39716. if (lowestRoot.found) {
  39717. t = lowestRoot.root;
  39718. found = true;
  39719. this._collisionPoint.copyFrom(p1);
  39720. }
  39721. this.basePoint.subtractToRef(p2, this._tempVector);
  39722. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39723. c = this._tempVector.lengthSquared() - 1.0;
  39724. lowestRoot = getLowestRoot(a, b, c, t);
  39725. if (lowestRoot.found) {
  39726. t = lowestRoot.root;
  39727. found = true;
  39728. this._collisionPoint.copyFrom(p2);
  39729. }
  39730. this.basePoint.subtractToRef(p3, this._tempVector);
  39731. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39732. c = this._tempVector.lengthSquared() - 1.0;
  39733. lowestRoot = getLowestRoot(a, b, c, t);
  39734. if (lowestRoot.found) {
  39735. t = lowestRoot.root;
  39736. found = true;
  39737. this._collisionPoint.copyFrom(p3);
  39738. }
  39739. p2.subtractToRef(p1, this._edge);
  39740. p1.subtractToRef(this.basePoint, this._baseToVertex);
  39741. var edgeSquaredLength = this._edge.lengthSquared();
  39742. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39743. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39744. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39745. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39746. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39747. lowestRoot = getLowestRoot(a, b, c, t);
  39748. if (lowestRoot.found) {
  39749. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39750. if (f >= 0.0 && f <= 1.0) {
  39751. t = lowestRoot.root;
  39752. found = true;
  39753. this._edge.scaleInPlace(f);
  39754. p1.addToRef(this._edge, this._collisionPoint);
  39755. }
  39756. }
  39757. p3.subtractToRef(p2, this._edge);
  39758. p2.subtractToRef(this.basePoint, this._baseToVertex);
  39759. edgeSquaredLength = this._edge.lengthSquared();
  39760. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39761. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39762. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39763. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39764. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39765. lowestRoot = getLowestRoot(a, b, c, t);
  39766. if (lowestRoot.found) {
  39767. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39768. if (f >= 0.0 && f <= 1.0) {
  39769. t = lowestRoot.root;
  39770. found = true;
  39771. this._edge.scaleInPlace(f);
  39772. p2.addToRef(this._edge, this._collisionPoint);
  39773. }
  39774. }
  39775. p1.subtractToRef(p3, this._edge);
  39776. p3.subtractToRef(this.basePoint, this._baseToVertex);
  39777. edgeSquaredLength = this._edge.lengthSquared();
  39778. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39779. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39780. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39781. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39782. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39783. lowestRoot = getLowestRoot(a, b, c, t);
  39784. if (lowestRoot.found) {
  39785. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39786. if (f >= 0.0 && f <= 1.0) {
  39787. t = lowestRoot.root;
  39788. found = true;
  39789. this._edge.scaleInPlace(f);
  39790. p3.addToRef(this._edge, this._collisionPoint);
  39791. }
  39792. }
  39793. }
  39794. if (found) {
  39795. var distToCollision = t * this.velocity.length();
  39796. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  39797. if (!this.intersectionPoint) {
  39798. this.intersectionPoint = this._collisionPoint.clone();
  39799. }
  39800. else {
  39801. this.intersectionPoint.copyFrom(this._collisionPoint);
  39802. }
  39803. this.nearestDistance = distToCollision;
  39804. this.collisionFound = true;
  39805. }
  39806. }
  39807. };
  39808. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  39809. for (var i = indexStart; i < indexEnd; i += 3) {
  39810. var p1 = pts[indices[i] - decal];
  39811. var p2 = pts[indices[i + 1] - decal];
  39812. var p3 = pts[indices[i + 2] - decal];
  39813. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  39814. }
  39815. };
  39816. Collider.prototype._getResponse = function (pos, vel) {
  39817. pos.addToRef(vel, this._destinationPoint);
  39818. vel.scaleInPlace((this.nearestDistance / vel.length()));
  39819. this.basePoint.addToRef(vel, pos);
  39820. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  39821. this._slidePlaneNormal.normalize();
  39822. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  39823. pos.addInPlace(this._displacementVector);
  39824. this.intersectionPoint.addInPlace(this._displacementVector);
  39825. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  39826. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  39827. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  39828. };
  39829. return Collider;
  39830. }());
  39831. BABYLON.Collider = Collider;
  39832. })(BABYLON || (BABYLON = {}));
  39833. //# sourceMappingURL=babylon.collider.js.map
  39834. var BABYLON;
  39835. (function (BABYLON) {
  39836. //WebWorker code will be inserted to this variable.
  39837. BABYLON.CollisionWorker = "";
  39838. var WorkerTaskType;
  39839. (function (WorkerTaskType) {
  39840. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  39841. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  39842. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  39843. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  39844. var WorkerReplyType;
  39845. (function (WorkerReplyType) {
  39846. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  39847. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  39848. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  39849. var CollisionCoordinatorWorker = (function () {
  39850. function CollisionCoordinatorWorker() {
  39851. var _this = this;
  39852. this._scaledPosition = BABYLON.Vector3.Zero();
  39853. this._scaledVelocity = BABYLON.Vector3.Zero();
  39854. this.onMeshUpdated = function (mesh) {
  39855. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  39856. };
  39857. this.onGeometryUpdated = function (geometry) {
  39858. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  39859. };
  39860. this._afterRender = function () {
  39861. if (!_this._init)
  39862. return;
  39863. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  39864. return;
  39865. }
  39866. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  39867. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  39868. if (_this._runningUpdated > 4) {
  39869. return;
  39870. }
  39871. ++_this._runningUpdated;
  39872. var payload = {
  39873. updatedMeshes: _this._addUpdateMeshesList,
  39874. updatedGeometries: _this._addUpdateGeometriesList,
  39875. removedGeometries: _this._toRemoveGeometryArray,
  39876. removedMeshes: _this._toRemoveMeshesArray
  39877. };
  39878. var message = {
  39879. payload: payload,
  39880. taskType: WorkerTaskType.UPDATE
  39881. };
  39882. var serializable = [];
  39883. for (var id in payload.updatedGeometries) {
  39884. if (payload.updatedGeometries.hasOwnProperty(id)) {
  39885. //prepare transferables
  39886. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  39887. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  39888. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  39889. }
  39890. }
  39891. _this._worker.postMessage(message, serializable);
  39892. _this._addUpdateMeshesList = {};
  39893. _this._addUpdateGeometriesList = {};
  39894. _this._toRemoveGeometryArray = [];
  39895. _this._toRemoveMeshesArray = [];
  39896. };
  39897. this._onMessageFromWorker = function (e) {
  39898. var returnData = e.data;
  39899. if (returnData.error != WorkerReplyType.SUCCESS) {
  39900. //TODO what errors can be returned from the worker?
  39901. BABYLON.Tools.Warn("error returned from worker!");
  39902. return;
  39903. }
  39904. switch (returnData.taskType) {
  39905. case WorkerTaskType.INIT:
  39906. _this._init = true;
  39907. //Update the worked with ALL of the scene's current state
  39908. _this._scene.meshes.forEach(function (mesh) {
  39909. _this.onMeshAdded(mesh);
  39910. });
  39911. _this._scene.getGeometries().forEach(function (geometry) {
  39912. _this.onGeometryAdded(geometry);
  39913. });
  39914. break;
  39915. case WorkerTaskType.UPDATE:
  39916. _this._runningUpdated--;
  39917. break;
  39918. case WorkerTaskType.COLLIDE:
  39919. _this._runningCollisionTask = false;
  39920. var returnPayload = returnData.payload;
  39921. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  39922. return;
  39923. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  39924. //cleanup
  39925. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  39926. break;
  39927. }
  39928. };
  39929. this._collisionsCallbackArray = [];
  39930. this._init = false;
  39931. this._runningUpdated = 0;
  39932. this._runningCollisionTask = false;
  39933. this._addUpdateMeshesList = {};
  39934. this._addUpdateGeometriesList = {};
  39935. this._toRemoveGeometryArray = [];
  39936. this._toRemoveMeshesArray = [];
  39937. }
  39938. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  39939. if (!this._init)
  39940. return;
  39941. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  39942. return;
  39943. position.divideToRef(collider.radius, this._scaledPosition);
  39944. velocity.divideToRef(collider.radius, this._scaledVelocity);
  39945. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  39946. var payload = {
  39947. collider: {
  39948. position: this._scaledPosition.asArray(),
  39949. velocity: this._scaledVelocity.asArray(),
  39950. radius: collider.radius.asArray()
  39951. },
  39952. collisionId: collisionIndex,
  39953. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  39954. maximumRetry: maximumRetry
  39955. };
  39956. var message = {
  39957. payload: payload,
  39958. taskType: WorkerTaskType.COLLIDE
  39959. };
  39960. this._worker.postMessage(message);
  39961. };
  39962. CollisionCoordinatorWorker.prototype.init = function (scene) {
  39963. this._scene = scene;
  39964. this._scene.registerAfterRender(this._afterRender);
  39965. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  39966. this._worker = new Worker(workerUrl);
  39967. this._worker.onmessage = this._onMessageFromWorker;
  39968. var message = {
  39969. payload: {},
  39970. taskType: WorkerTaskType.INIT
  39971. };
  39972. this._worker.postMessage(message);
  39973. };
  39974. CollisionCoordinatorWorker.prototype.destroy = function () {
  39975. this._scene.unregisterAfterRender(this._afterRender);
  39976. this._worker.terminate();
  39977. };
  39978. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  39979. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  39980. this.onMeshUpdated(mesh);
  39981. };
  39982. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  39983. this._toRemoveMeshesArray.push(mesh.uniqueId);
  39984. };
  39985. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  39986. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  39987. geometry.onGeometryUpdated = this.onGeometryUpdated;
  39988. this.onGeometryUpdated(geometry);
  39989. };
  39990. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  39991. this._toRemoveGeometryArray.push(geometry.id);
  39992. };
  39993. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  39994. var submeshes = [];
  39995. if (mesh.subMeshes) {
  39996. submeshes = mesh.subMeshes.map(function (sm, idx) {
  39997. return {
  39998. position: idx,
  39999. verticesStart: sm.verticesStart,
  40000. verticesCount: sm.verticesCount,
  40001. indexStart: sm.indexStart,
  40002. indexCount: sm.indexCount,
  40003. hasMaterial: !!sm.getMaterial(),
  40004. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40005. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40006. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40007. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40008. };
  40009. });
  40010. }
  40011. var geometryId = null;
  40012. if (mesh instanceof BABYLON.Mesh) {
  40013. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40014. }
  40015. else if (mesh instanceof BABYLON.InstancedMesh) {
  40016. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40017. }
  40018. return {
  40019. uniqueId: mesh.uniqueId,
  40020. id: mesh.id,
  40021. name: mesh.name,
  40022. geometryId: geometryId,
  40023. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40024. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40025. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40026. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40027. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40028. subMeshes: submeshes,
  40029. checkCollisions: mesh.checkCollisions
  40030. };
  40031. };
  40032. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40033. return {
  40034. id: geometry.id,
  40035. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40036. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40037. indices: new Uint32Array(geometry.getIndices() || []),
  40038. };
  40039. };
  40040. return CollisionCoordinatorWorker;
  40041. }());
  40042. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40043. var CollisionCoordinatorLegacy = (function () {
  40044. function CollisionCoordinatorLegacy() {
  40045. this._scaledPosition = BABYLON.Vector3.Zero();
  40046. this._scaledVelocity = BABYLON.Vector3.Zero();
  40047. this._finalPosition = BABYLON.Vector3.Zero();
  40048. }
  40049. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40050. position.divideToRef(collider.radius, this._scaledPosition);
  40051. velocity.divideToRef(collider.radius, this._scaledVelocity);
  40052. collider.collidedMesh = null;
  40053. collider.retry = 0;
  40054. collider.initialVelocity = this._scaledVelocity;
  40055. collider.initialPosition = this._scaledPosition;
  40056. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40057. this._finalPosition.multiplyInPlace(collider.radius);
  40058. //run the callback
  40059. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40060. };
  40061. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40062. this._scene = scene;
  40063. };
  40064. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40065. //Legacy need no destruction method.
  40066. };
  40067. //No update in legacy mode
  40068. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40069. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40070. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40071. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40072. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40073. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40074. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40075. if (excludedMesh === void 0) { excludedMesh = null; }
  40076. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40077. if (collider.retry >= maximumRetry) {
  40078. finalPosition.copyFrom(position);
  40079. return;
  40080. }
  40081. // Check if this is a mesh else camera or -1
  40082. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40083. collider._initialize(position, velocity, closeDistance);
  40084. // Check all meshes
  40085. for (var index = 0; index < this._scene.meshes.length; index++) {
  40086. var mesh = this._scene.meshes[index];
  40087. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40088. mesh._checkCollision(collider);
  40089. }
  40090. }
  40091. if (!collider.collisionFound) {
  40092. position.addToRef(velocity, finalPosition);
  40093. return;
  40094. }
  40095. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40096. collider._getResponse(position, velocity);
  40097. }
  40098. if (velocity.length() <= closeDistance) {
  40099. finalPosition.copyFrom(position);
  40100. return;
  40101. }
  40102. collider.retry++;
  40103. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  40104. };
  40105. return CollisionCoordinatorLegacy;
  40106. }());
  40107. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  40108. })(BABYLON || (BABYLON = {}));
  40109. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  40110. var BABYLON;
  40111. (function (BABYLON) {
  40112. var Particle = (function () {
  40113. function Particle() {
  40114. this.position = BABYLON.Vector3.Zero();
  40115. this.direction = BABYLON.Vector3.Zero();
  40116. this.color = new BABYLON.Color4(0, 0, 0, 0);
  40117. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  40118. this.lifeTime = 1.0;
  40119. this.age = 0;
  40120. this.size = 0;
  40121. this.angle = 0;
  40122. this.angularSpeed = 0;
  40123. }
  40124. Particle.prototype.copyTo = function (other) {
  40125. other.position.copyFrom(this.position);
  40126. other.direction.copyFrom(this.direction);
  40127. other.color.copyFrom(this.color);
  40128. other.colorStep.copyFrom(this.colorStep);
  40129. other.lifeTime = this.lifeTime;
  40130. other.age = this.age;
  40131. other.size = this.size;
  40132. other.angle = this.angle;
  40133. other.angularSpeed = this.angularSpeed;
  40134. };
  40135. return Particle;
  40136. }());
  40137. BABYLON.Particle = Particle;
  40138. })(BABYLON || (BABYLON = {}));
  40139. //# sourceMappingURL=babylon.particle.js.map
  40140. var BABYLON;
  40141. (function (BABYLON) {
  40142. var randomNumber = function (min, max) {
  40143. if (min === max) {
  40144. return (min);
  40145. }
  40146. var random = Math.random();
  40147. return ((random * (max - min)) + min);
  40148. };
  40149. var ParticleSystem = (function () {
  40150. function ParticleSystem(name, capacity, scene, customEffect) {
  40151. var _this = this;
  40152. this.name = name;
  40153. // Members
  40154. this.animations = [];
  40155. this.renderingGroupId = 0;
  40156. this.emitter = null;
  40157. this.emitRate = 10;
  40158. this.manualEmitCount = -1;
  40159. this.updateSpeed = 0.01;
  40160. this.targetStopDuration = 0;
  40161. this.disposeOnStop = false;
  40162. this.minEmitPower = 1;
  40163. this.maxEmitPower = 1;
  40164. this.minLifeTime = 1;
  40165. this.maxLifeTime = 1;
  40166. this.minSize = 1;
  40167. this.maxSize = 1;
  40168. this.minAngularSpeed = 0;
  40169. this.maxAngularSpeed = 0;
  40170. this.layerMask = 0x0FFFFFFF;
  40171. this.customShader = null;
  40172. this.preventAutoStart = false;
  40173. /**
  40174. * An event triggered when the system is disposed.
  40175. * @type {BABYLON.Observable}
  40176. */
  40177. this.onDisposeObservable = new BABYLON.Observable();
  40178. this.onAnimationEnd = null;
  40179. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  40180. this.forceDepthWrite = false;
  40181. this.gravity = BABYLON.Vector3.Zero();
  40182. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  40183. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  40184. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  40185. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40186. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40187. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40188. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40189. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40190. this.particles = new Array();
  40191. this._stockParticles = new Array();
  40192. this._newPartsExcess = 0;
  40193. this._vertexBuffers = {};
  40194. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  40195. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  40196. this._scaledDirection = BABYLON.Vector3.Zero();
  40197. this._scaledGravity = BABYLON.Vector3.Zero();
  40198. this._currentRenderId = -1;
  40199. this._started = false;
  40200. this._stopped = false;
  40201. this._actualFrame = 0;
  40202. this.id = name;
  40203. this._capacity = capacity;
  40204. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40205. this._customEffect = customEffect;
  40206. scene.particleSystems.push(this);
  40207. var indices = [];
  40208. var index = 0;
  40209. for (var count = 0; count < capacity; count++) {
  40210. indices.push(index);
  40211. indices.push(index + 1);
  40212. indices.push(index + 2);
  40213. indices.push(index);
  40214. indices.push(index + 2);
  40215. indices.push(index + 3);
  40216. index += 4;
  40217. }
  40218. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  40219. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  40220. this._vertexData = new Float32Array(capacity * 11 * 4);
  40221. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  40222. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  40223. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  40224. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  40225. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  40226. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  40227. this._vertexBuffers["options"] = options;
  40228. // Default behaviors
  40229. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  40230. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  40231. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  40232. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  40233. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  40234. };
  40235. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  40236. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  40237. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  40238. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  40239. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  40240. };
  40241. this.updateFunction = function (particles) {
  40242. for (var index = 0; index < particles.length; index++) {
  40243. var particle = particles[index];
  40244. particle.age += _this._scaledUpdateSpeed;
  40245. if (particle.age >= particle.lifeTime) {
  40246. _this.recycleParticle(particle);
  40247. index--;
  40248. continue;
  40249. }
  40250. else {
  40251. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  40252. particle.color.addInPlace(_this._scaledColorStep);
  40253. if (particle.color.a < 0)
  40254. particle.color.a = 0;
  40255. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  40256. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  40257. particle.position.addInPlace(_this._scaledDirection);
  40258. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  40259. particle.direction.addInPlace(_this._scaledGravity);
  40260. }
  40261. }
  40262. };
  40263. }
  40264. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  40265. set: function (callback) {
  40266. if (this._onDisposeObserver) {
  40267. this.onDisposeObservable.remove(this._onDisposeObserver);
  40268. }
  40269. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40270. },
  40271. enumerable: true,
  40272. configurable: true
  40273. });
  40274. ParticleSystem.prototype.recycleParticle = function (particle) {
  40275. var lastParticle = this.particles.pop();
  40276. if (lastParticle !== particle) {
  40277. lastParticle.copyTo(particle);
  40278. this._stockParticles.push(lastParticle);
  40279. }
  40280. };
  40281. ParticleSystem.prototype.getCapacity = function () {
  40282. return this._capacity;
  40283. };
  40284. ParticleSystem.prototype.isAlive = function () {
  40285. return this._alive;
  40286. };
  40287. ParticleSystem.prototype.isStarted = function () {
  40288. return this._started;
  40289. };
  40290. ParticleSystem.prototype.start = function () {
  40291. this._started = true;
  40292. this._stopped = false;
  40293. this._actualFrame = 0;
  40294. };
  40295. ParticleSystem.prototype.stop = function () {
  40296. this._stopped = true;
  40297. };
  40298. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  40299. var offset = index * 11;
  40300. this._vertexData[offset] = particle.position.x;
  40301. this._vertexData[offset + 1] = particle.position.y;
  40302. this._vertexData[offset + 2] = particle.position.z;
  40303. this._vertexData[offset + 3] = particle.color.r;
  40304. this._vertexData[offset + 4] = particle.color.g;
  40305. this._vertexData[offset + 5] = particle.color.b;
  40306. this._vertexData[offset + 6] = particle.color.a;
  40307. this._vertexData[offset + 7] = particle.angle;
  40308. this._vertexData[offset + 8] = particle.size;
  40309. this._vertexData[offset + 9] = offsetX;
  40310. this._vertexData[offset + 10] = offsetY;
  40311. };
  40312. ParticleSystem.prototype._update = function (newParticles) {
  40313. // Update current
  40314. this._alive = this.particles.length > 0;
  40315. this.updateFunction(this.particles);
  40316. // Add new ones
  40317. var worldMatrix;
  40318. if (this.emitter.position) {
  40319. var emitterMesh = this.emitter;
  40320. worldMatrix = emitterMesh.getWorldMatrix();
  40321. }
  40322. else {
  40323. var emitterPosition = this.emitter;
  40324. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  40325. }
  40326. var particle;
  40327. for (var index = 0; index < newParticles; index++) {
  40328. if (this.particles.length === this._capacity) {
  40329. break;
  40330. }
  40331. if (this._stockParticles.length !== 0) {
  40332. particle = this._stockParticles.pop();
  40333. particle.age = 0;
  40334. }
  40335. else {
  40336. particle = new BABYLON.Particle();
  40337. }
  40338. this.particles.push(particle);
  40339. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  40340. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  40341. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  40342. particle.size = randomNumber(this.minSize, this.maxSize);
  40343. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  40344. this.startPositionFunction(worldMatrix, particle.position, particle);
  40345. var step = randomNumber(0, 1.0);
  40346. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  40347. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  40348. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  40349. }
  40350. };
  40351. ParticleSystem.prototype._getEffect = function () {
  40352. if (this._customEffect) {
  40353. return this._customEffect;
  40354. }
  40355. ;
  40356. var defines = [];
  40357. if (this._scene.clipPlane) {
  40358. defines.push("#define CLIPPLANE");
  40359. }
  40360. // Effect
  40361. var join = defines.join("\n");
  40362. if (this._cachedDefines !== join) {
  40363. this._cachedDefines = join;
  40364. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  40365. }
  40366. return this._effect;
  40367. };
  40368. ParticleSystem.prototype.animate = function () {
  40369. if (!this._started)
  40370. return;
  40371. var effect = this._getEffect();
  40372. // Check
  40373. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  40374. return;
  40375. if (this._currentRenderId === this._scene.getRenderId()) {
  40376. return;
  40377. }
  40378. this._currentRenderId = this._scene.getRenderId();
  40379. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  40380. // determine the number of particles we need to create
  40381. var newParticles;
  40382. if (this.manualEmitCount > -1) {
  40383. newParticles = this.manualEmitCount;
  40384. this._newPartsExcess = 0;
  40385. this.manualEmitCount = 0;
  40386. }
  40387. else {
  40388. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  40389. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  40390. }
  40391. if (this._newPartsExcess > 1.0) {
  40392. newParticles += this._newPartsExcess >> 0;
  40393. this._newPartsExcess -= this._newPartsExcess >> 0;
  40394. }
  40395. this._alive = false;
  40396. if (!this._stopped) {
  40397. this._actualFrame += this._scaledUpdateSpeed;
  40398. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  40399. this.stop();
  40400. }
  40401. else {
  40402. newParticles = 0;
  40403. }
  40404. this._update(newParticles);
  40405. // Stopped?
  40406. if (this._stopped) {
  40407. if (!this._alive) {
  40408. this._started = false;
  40409. if (this.onAnimationEnd) {
  40410. this.onAnimationEnd();
  40411. }
  40412. if (this.disposeOnStop) {
  40413. this._scene._toBeDisposed.push(this);
  40414. }
  40415. }
  40416. }
  40417. // Update VBO
  40418. var offset = 0;
  40419. for (var index = 0; index < this.particles.length; index++) {
  40420. var particle = this.particles[index];
  40421. this._appendParticleVertex(offset++, particle, 0, 0);
  40422. this._appendParticleVertex(offset++, particle, 1, 0);
  40423. this._appendParticleVertex(offset++, particle, 1, 1);
  40424. this._appendParticleVertex(offset++, particle, 0, 1);
  40425. }
  40426. this._vertexBuffer.update(this._vertexData);
  40427. };
  40428. ParticleSystem.prototype.render = function () {
  40429. var effect = this._getEffect();
  40430. // Check
  40431. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  40432. return 0;
  40433. var engine = this._scene.getEngine();
  40434. // Render
  40435. engine.enableEffect(effect);
  40436. engine.setState(false);
  40437. var viewMatrix = this._scene.getViewMatrix();
  40438. effect.setTexture("diffuseSampler", this.particleTexture);
  40439. effect.setMatrix("view", viewMatrix);
  40440. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  40441. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  40442. if (this._scene.clipPlane) {
  40443. var clipPlane = this._scene.clipPlane;
  40444. var invView = viewMatrix.clone();
  40445. invView.invert();
  40446. effect.setMatrix("invView", invView);
  40447. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  40448. }
  40449. // VBOs
  40450. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40451. // Draw order
  40452. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  40453. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  40454. }
  40455. else {
  40456. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40457. }
  40458. if (this.forceDepthWrite) {
  40459. engine.setDepthWrite(true);
  40460. }
  40461. engine.draw(true, 0, this.particles.length * 6);
  40462. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40463. return this.particles.length;
  40464. };
  40465. ParticleSystem.prototype.dispose = function () {
  40466. if (this._vertexBuffer) {
  40467. this._vertexBuffer.dispose();
  40468. this._vertexBuffer = null;
  40469. }
  40470. if (this._indexBuffer) {
  40471. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40472. this._indexBuffer = null;
  40473. }
  40474. if (this.particleTexture) {
  40475. this.particleTexture.dispose();
  40476. this.particleTexture = null;
  40477. }
  40478. // Remove from scene
  40479. var index = this._scene.particleSystems.indexOf(this);
  40480. if (index > -1) {
  40481. this._scene.particleSystems.splice(index, 1);
  40482. }
  40483. // Callback
  40484. this.onDisposeObservable.notifyObservers(this);
  40485. this.onDisposeObservable.clear();
  40486. };
  40487. // Clone
  40488. ParticleSystem.prototype.clone = function (name, newEmitter) {
  40489. var custom = null;
  40490. var program = null;
  40491. if (this.customShader != null) {
  40492. program = this.customShader;
  40493. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40494. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40495. }
  40496. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  40497. result.customShader = program;
  40498. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  40499. if (newEmitter === undefined) {
  40500. newEmitter = this.emitter;
  40501. }
  40502. result.emitter = newEmitter;
  40503. if (this.particleTexture) {
  40504. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  40505. }
  40506. if (!this.preventAutoStart) {
  40507. result.start();
  40508. }
  40509. return result;
  40510. };
  40511. ParticleSystem.prototype.serialize = function () {
  40512. var serializationObject = {};
  40513. serializationObject.name = this.name;
  40514. serializationObject.id = this.id;
  40515. // Emitter
  40516. if (this.emitter.position) {
  40517. var emitterMesh = this.emitter;
  40518. serializationObject.emitterId = emitterMesh.id;
  40519. }
  40520. else {
  40521. var emitterPosition = this.emitter;
  40522. serializationObject.emitter = emitterPosition.asArray();
  40523. }
  40524. serializationObject.capacity = this.getCapacity();
  40525. if (this.particleTexture) {
  40526. serializationObject.textureName = this.particleTexture.name;
  40527. }
  40528. // Animations
  40529. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  40530. // Particle system
  40531. serializationObject.minAngularSpeed = this.minAngularSpeed;
  40532. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  40533. serializationObject.minSize = this.minSize;
  40534. serializationObject.maxSize = this.maxSize;
  40535. serializationObject.minEmitPower = this.minEmitPower;
  40536. serializationObject.maxEmitPower = this.maxEmitPower;
  40537. serializationObject.minLifeTime = this.minLifeTime;
  40538. serializationObject.maxLifeTime = this.maxLifeTime;
  40539. serializationObject.emitRate = this.emitRate;
  40540. serializationObject.minEmitBox = this.minEmitBox.asArray();
  40541. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  40542. serializationObject.gravity = this.gravity.asArray();
  40543. serializationObject.direction1 = this.direction1.asArray();
  40544. serializationObject.direction2 = this.direction2.asArray();
  40545. serializationObject.color1 = this.color1.asArray();
  40546. serializationObject.color2 = this.color2.asArray();
  40547. serializationObject.colorDead = this.colorDead.asArray();
  40548. serializationObject.updateSpeed = this.updateSpeed;
  40549. serializationObject.targetStopDuration = this.targetStopDuration;
  40550. serializationObject.textureMask = this.textureMask.asArray();
  40551. serializationObject.blendMode = this.blendMode;
  40552. serializationObject.customShader = this.customShader;
  40553. serializationObject.preventAutoStart = this.preventAutoStart;
  40554. return serializationObject;
  40555. };
  40556. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  40557. var name = parsedParticleSystem.name;
  40558. var custom = null;
  40559. var program = null;
  40560. if (parsedParticleSystem.customShader) {
  40561. program = parsedParticleSystem.customShader;
  40562. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40563. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40564. }
  40565. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  40566. particleSystem.customShader = program;
  40567. if (parsedParticleSystem.id) {
  40568. particleSystem.id = parsedParticleSystem.id;
  40569. }
  40570. // Auto start
  40571. if (parsedParticleSystem.preventAutoStart) {
  40572. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  40573. }
  40574. // Texture
  40575. if (parsedParticleSystem.textureName) {
  40576. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  40577. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  40578. }
  40579. // Emitter
  40580. if (parsedParticleSystem.emitterId) {
  40581. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  40582. }
  40583. else {
  40584. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  40585. }
  40586. // Animations
  40587. if (parsedParticleSystem.animations) {
  40588. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  40589. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  40590. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40591. }
  40592. }
  40593. if (parsedParticleSystem.autoAnimate) {
  40594. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  40595. }
  40596. // Particle system
  40597. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  40598. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  40599. particleSystem.minSize = parsedParticleSystem.minSize;
  40600. particleSystem.maxSize = parsedParticleSystem.maxSize;
  40601. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  40602. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  40603. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  40604. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  40605. particleSystem.emitRate = parsedParticleSystem.emitRate;
  40606. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  40607. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  40608. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  40609. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  40610. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  40611. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  40612. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  40613. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  40614. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  40615. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  40616. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  40617. particleSystem.blendMode = parsedParticleSystem.blendMode;
  40618. if (!particleSystem.preventAutoStart) {
  40619. particleSystem.start();
  40620. }
  40621. return particleSystem;
  40622. };
  40623. // Statics
  40624. ParticleSystem.BLENDMODE_ONEONE = 0;
  40625. ParticleSystem.BLENDMODE_STANDARD = 1;
  40626. return ParticleSystem;
  40627. }());
  40628. BABYLON.ParticleSystem = ParticleSystem;
  40629. })(BABYLON || (BABYLON = {}));
  40630. //# sourceMappingURL=babylon.particleSystem.js.map
  40631. var BABYLON;
  40632. (function (BABYLON) {
  40633. var SolidParticle = (function () {
  40634. /**
  40635. * Creates a Solid Particle object.
  40636. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  40637. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  40638. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  40639. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  40640. * `shapeId` (integer) is the model shape identifier in the SPS.
  40641. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  40642. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  40643. */
  40644. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  40645. this.idx = 0; // particle global index
  40646. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  40647. this.position = BABYLON.Vector3.Zero(); // position
  40648. this.rotation = BABYLON.Vector3.Zero(); // rotation
  40649. this.scaling = BABYLON.Vector3.One(); // scaling
  40650. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  40651. this.velocity = BABYLON.Vector3.Zero(); // velocity
  40652. this.alive = true; // alive
  40653. this.isVisible = true; // visibility
  40654. this._pos = 0; // index of this particle in the global "positions" array
  40655. this.shapeId = 0; // model shape id
  40656. this.idxInShape = 0; // index of the particle in its shape id
  40657. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  40658. this.idx = particleIndex;
  40659. this._pos = positionIndex;
  40660. this._model = model;
  40661. this.shapeId = shapeId;
  40662. this.idxInShape = idxInShape;
  40663. this._sps = sps;
  40664. if (modelBoundingInfo) {
  40665. this._modelBoundingInfo = modelBoundingInfo;
  40666. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  40667. }
  40668. }
  40669. Object.defineProperty(SolidParticle.prototype, "scale", {
  40670. /**
  40671. * legacy support, changed scale to scaling
  40672. */
  40673. get: function () {
  40674. return this.scaling;
  40675. },
  40676. set: function (scale) {
  40677. this.scaling = scale;
  40678. },
  40679. enumerable: true,
  40680. configurable: true
  40681. });
  40682. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  40683. /**
  40684. * legacy support, changed quaternion to rotationQuaternion
  40685. */
  40686. get: function () {
  40687. return this.rotationQuaternion;
  40688. },
  40689. set: function (q) {
  40690. this.rotationQuaternion = q;
  40691. },
  40692. enumerable: true,
  40693. configurable: true
  40694. });
  40695. /**
  40696. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  40697. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  40698. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  40699. */
  40700. SolidParticle.prototype.intersectsMesh = function (target) {
  40701. if (!this._boundingInfo || !target._boundingInfo) {
  40702. return false;
  40703. }
  40704. if (this._sps._bSphereOnly) {
  40705. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  40706. }
  40707. return this._boundingInfo.intersects(target._boundingInfo, false);
  40708. };
  40709. return SolidParticle;
  40710. }());
  40711. BABYLON.SolidParticle = SolidParticle;
  40712. var ModelShape = (function () {
  40713. /**
  40714. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  40715. * SPS internal tool, don't use it manually.
  40716. */
  40717. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  40718. this.shapeID = id;
  40719. this._shape = shape;
  40720. this._shapeUV = shapeUV;
  40721. this._positionFunction = posFunction;
  40722. this._vertexFunction = vtxFunction;
  40723. }
  40724. return ModelShape;
  40725. }());
  40726. BABYLON.ModelShape = ModelShape;
  40727. })(BABYLON || (BABYLON = {}));
  40728. //# sourceMappingURL=babylon.solidParticle.js.map
  40729. var BABYLON;
  40730. (function (BABYLON) {
  40731. /**
  40732. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  40733. */
  40734. var SolidParticleSystem = (function () {
  40735. /**
  40736. * Creates a SPS (Solid Particle System) object.
  40737. * `name` (String) is the SPS name, this will be the underlying mesh name.
  40738. * `scene` (Scene) is the scene in which the SPS is added.
  40739. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  40740. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  40741. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  40742. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  40743. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  40744. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  40745. */
  40746. function SolidParticleSystem(name, scene, options) {
  40747. // public members
  40748. /**
  40749. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  40750. * Example : var p = SPS.particles[i];
  40751. */
  40752. this.particles = new Array();
  40753. /**
  40754. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  40755. */
  40756. this.nbParticles = 0;
  40757. /**
  40758. * If the particles must ever face the camera (default false). Useful for planar particles.
  40759. */
  40760. this.billboard = false;
  40761. /**
  40762. * Recompute normals when adding a shape
  40763. */
  40764. this.recomputeNormals = true;
  40765. /**
  40766. * This a counter ofr your own usage. It's not set by any SPS functions.
  40767. */
  40768. this.counter = 0;
  40769. /**
  40770. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  40771. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  40772. */
  40773. this.vars = {};
  40774. this._positions = new Array();
  40775. this._indices = new Array();
  40776. this._normals = new Array();
  40777. this._colors = new Array();
  40778. this._uvs = new Array();
  40779. this._index = 0; // indices index
  40780. this._updatable = true;
  40781. this._pickable = false;
  40782. this._isVisibilityBoxLocked = false;
  40783. this._alwaysVisible = false;
  40784. this._shapeCounter = 0;
  40785. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  40786. this._color = new BABYLON.Color4(0, 0, 0, 0);
  40787. this._computeParticleColor = true;
  40788. this._computeParticleTexture = true;
  40789. this._computeParticleRotation = true;
  40790. this._computeParticleVertex = false;
  40791. this._computeBoundingBox = false;
  40792. this._cam_axisZ = BABYLON.Vector3.Zero();
  40793. this._cam_axisY = BABYLON.Vector3.Zero();
  40794. this._cam_axisX = BABYLON.Vector3.Zero();
  40795. this._axisX = BABYLON.Axis.X;
  40796. this._axisY = BABYLON.Axis.Y;
  40797. this._axisZ = BABYLON.Axis.Z;
  40798. this._camDir = BABYLON.Vector3.Zero();
  40799. this._rotMatrix = new BABYLON.Matrix();
  40800. this._invertMatrix = new BABYLON.Matrix();
  40801. this._rotated = BABYLON.Vector3.Zero();
  40802. this._quaternion = new BABYLON.Quaternion();
  40803. this._vertex = BABYLON.Vector3.Zero();
  40804. this._normal = BABYLON.Vector3.Zero();
  40805. this._yaw = 0.0;
  40806. this._pitch = 0.0;
  40807. this._roll = 0.0;
  40808. this._halfroll = 0.0;
  40809. this._halfpitch = 0.0;
  40810. this._halfyaw = 0.0;
  40811. this._sinRoll = 0.0;
  40812. this._cosRoll = 0.0;
  40813. this._sinPitch = 0.0;
  40814. this._cosPitch = 0.0;
  40815. this._sinYaw = 0.0;
  40816. this._cosYaw = 0.0;
  40817. this._w = 0.0;
  40818. this._mustUnrotateFixedNormals = false;
  40819. this._minimum = BABYLON.Tmp.Vector3[0];
  40820. this._maximum = BABYLON.Tmp.Vector3[1];
  40821. this._scale = BABYLON.Tmp.Vector3[2];
  40822. this._translation = BABYLON.Tmp.Vector3[3];
  40823. this._minBbox = BABYLON.Tmp.Vector3[4];
  40824. this._maxBbox = BABYLON.Tmp.Vector3[5];
  40825. this._particlesIntersect = false;
  40826. this._bSphereOnly = false;
  40827. this._bSphereRadiusFactor = 1.0;
  40828. this.name = name;
  40829. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40830. this._camera = scene.activeCamera;
  40831. this._pickable = options ? options.isPickable : false;
  40832. this._particlesIntersect = options ? options.particleIntersection : false;
  40833. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  40834. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  40835. if (options && options.updatable) {
  40836. this._updatable = options.updatable;
  40837. }
  40838. else {
  40839. this._updatable = true;
  40840. }
  40841. if (this._pickable) {
  40842. this.pickedParticles = [];
  40843. }
  40844. }
  40845. /**
  40846. * Builds the SPS underlying mesh. Returns a standard Mesh.
  40847. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  40848. */
  40849. SolidParticleSystem.prototype.buildMesh = function () {
  40850. if (this.nbParticles === 0) {
  40851. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  40852. this.addShape(triangle, 1);
  40853. triangle.dispose();
  40854. }
  40855. this._positions32 = new Float32Array(this._positions);
  40856. this._uvs32 = new Float32Array(this._uvs);
  40857. this._colors32 = new Float32Array(this._colors);
  40858. if (this.recomputeNormals) {
  40859. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  40860. }
  40861. this._normals32 = new Float32Array(this._normals);
  40862. this._fixedNormal32 = new Float32Array(this._normals);
  40863. if (this._mustUnrotateFixedNormals) {
  40864. this._unrotateFixedNormals();
  40865. }
  40866. var vertexData = new BABYLON.VertexData();
  40867. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40868. vertexData.indices = this._indices;
  40869. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40870. if (this._uvs32) {
  40871. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  40872. ;
  40873. }
  40874. if (this._colors32) {
  40875. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  40876. }
  40877. var mesh = new BABYLON.Mesh(this.name, this._scene);
  40878. vertexData.applyToMesh(mesh, this._updatable);
  40879. this.mesh = mesh;
  40880. this.mesh.isPickable = this._pickable;
  40881. // free memory
  40882. this._positions = null;
  40883. this._normals = null;
  40884. this._uvs = null;
  40885. this._colors = null;
  40886. if (!this._updatable) {
  40887. this.particles.length = 0;
  40888. }
  40889. return mesh;
  40890. };
  40891. /**
  40892. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  40893. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  40894. * Thus the particles generated from `digest()` have their property `position` set yet.
  40895. * `mesh` ( Mesh ) is the mesh to be digested
  40896. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  40897. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  40898. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  40899. */
  40900. SolidParticleSystem.prototype.digest = function (mesh, options) {
  40901. var size = (options && options.facetNb) || 1;
  40902. var number = (options && options.number);
  40903. var delta = (options && options.delta) || 0;
  40904. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40905. var meshInd = mesh.getIndices();
  40906. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40907. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40908. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40909. var f = 0; // facet counter
  40910. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  40911. // compute size from number
  40912. if (number) {
  40913. number = (number > totalFacets) ? totalFacets : number;
  40914. size = Math.round(totalFacets / number);
  40915. delta = 0;
  40916. }
  40917. else {
  40918. size = (size > totalFacets) ? totalFacets : size;
  40919. }
  40920. var facetPos = []; // submesh positions
  40921. var facetInd = []; // submesh indices
  40922. var facetUV = []; // submesh UV
  40923. var facetCol = []; // submesh colors
  40924. var barycenter = BABYLON.Tmp.Vector3[0];
  40925. var rand;
  40926. var sizeO = size;
  40927. while (f < totalFacets) {
  40928. size = sizeO + Math.floor((1 + delta) * Math.random());
  40929. if (f > totalFacets - size) {
  40930. size = totalFacets - f;
  40931. }
  40932. // reset temp arrays
  40933. facetPos.length = 0;
  40934. facetInd.length = 0;
  40935. facetUV.length = 0;
  40936. facetCol.length = 0;
  40937. // iterate over "size" facets
  40938. var fi = 0;
  40939. for (var j = f * 3; j < (f + size) * 3; j++) {
  40940. facetInd.push(fi);
  40941. var i = meshInd[j];
  40942. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  40943. if (meshUV) {
  40944. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  40945. }
  40946. if (meshCol) {
  40947. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  40948. }
  40949. fi++;
  40950. }
  40951. // create a model shape for each single particle
  40952. var idx = this.nbParticles;
  40953. var shape = this._posToShape(facetPos);
  40954. var shapeUV = this._uvsToShapeUV(facetUV);
  40955. // compute the barycenter of the shape
  40956. var v;
  40957. for (v = 0; v < shape.length; v++) {
  40958. barycenter.addInPlace(shape[v]);
  40959. }
  40960. barycenter.scaleInPlace(1 / shape.length);
  40961. // shift the shape from its barycenter to the origin
  40962. for (v = 0; v < shape.length; v++) {
  40963. shape[v].subtractInPlace(barycenter);
  40964. }
  40965. var bInfo;
  40966. if (this._particlesIntersect) {
  40967. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  40968. }
  40969. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  40970. // add the particle in the SPS
  40971. var currentPos = this._positions.length;
  40972. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  40973. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  40974. // initialize the particle position
  40975. this.particles[this.nbParticles].position.addInPlace(barycenter);
  40976. this._index += shape.length;
  40977. idx++;
  40978. this.nbParticles++;
  40979. this._shapeCounter++;
  40980. f += size;
  40981. }
  40982. return this;
  40983. };
  40984. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  40985. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  40986. var index = 0;
  40987. var idx = 0;
  40988. for (var p = 0; p < this.particles.length; p++) {
  40989. this._particle = this.particles[p];
  40990. this._shape = this._particle._model._shape;
  40991. if (this._particle.rotationQuaternion) {
  40992. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40993. }
  40994. else {
  40995. this._yaw = this._particle.rotation.y;
  40996. this._pitch = this._particle.rotation.x;
  40997. this._roll = this._particle.rotation.z;
  40998. this._quaternionRotationYPR();
  40999. }
  41000. this._quaternionToRotationMatrix();
  41001. this._rotMatrix.invertToRef(this._invertMatrix);
  41002. for (var pt = 0; pt < this._shape.length; pt++) {
  41003. idx = index + pt * 3;
  41004. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  41005. this._fixedNormal32[idx] = this._normal.x;
  41006. this._fixedNormal32[idx + 1] = this._normal.y;
  41007. this._fixedNormal32[idx + 2] = this._normal.z;
  41008. }
  41009. index = idx + 3;
  41010. }
  41011. };
  41012. //reset copy
  41013. SolidParticleSystem.prototype._resetCopy = function () {
  41014. this._copy.position.x = 0;
  41015. this._copy.position.y = 0;
  41016. this._copy.position.z = 0;
  41017. this._copy.rotation.x = 0;
  41018. this._copy.rotation.y = 0;
  41019. this._copy.rotation.z = 0;
  41020. this._copy.rotationQuaternion = null;
  41021. this._copy.scaling.x = 1;
  41022. this._copy.scaling.y = 1;
  41023. this._copy.scaling.z = 1;
  41024. this._copy.uvs.x = 0;
  41025. this._copy.uvs.y = 0;
  41026. this._copy.uvs.z = 1;
  41027. this._copy.uvs.w = 1;
  41028. this._copy.color = null;
  41029. };
  41030. // _meshBuilder : inserts the shape model in the global SPS mesh
  41031. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  41032. var i;
  41033. var u = 0;
  41034. var c = 0;
  41035. var n = 0;
  41036. this._resetCopy();
  41037. if (options && options.positionFunction) {
  41038. options.positionFunction(this._copy, idx, idxInShape);
  41039. this._mustUnrotateFixedNormals = true;
  41040. }
  41041. if (this._copy.rotationQuaternion) {
  41042. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41043. }
  41044. else {
  41045. this._yaw = this._copy.rotation.y;
  41046. this._pitch = this._copy.rotation.x;
  41047. this._roll = this._copy.rotation.z;
  41048. this._quaternionRotationYPR();
  41049. }
  41050. this._quaternionToRotationMatrix();
  41051. for (i = 0; i < shape.length; i++) {
  41052. this._vertex.x = shape[i].x;
  41053. this._vertex.y = shape[i].y;
  41054. this._vertex.z = shape[i].z;
  41055. if (options && options.vertexFunction) {
  41056. options.vertexFunction(this._copy, this._vertex, i);
  41057. }
  41058. this._vertex.x *= this._copy.scaling.x;
  41059. this._vertex.y *= this._copy.scaling.y;
  41060. this._vertex.z *= this._copy.scaling.z;
  41061. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41062. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41063. if (meshUV) {
  41064. 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);
  41065. u += 2;
  41066. }
  41067. if (this._copy.color) {
  41068. this._color = this._copy.color;
  41069. }
  41070. else if (meshCol && meshCol[c] !== undefined) {
  41071. this._color.r = meshCol[c];
  41072. this._color.g = meshCol[c + 1];
  41073. this._color.b = meshCol[c + 2];
  41074. this._color.a = meshCol[c + 3];
  41075. }
  41076. else {
  41077. this._color.r = 1;
  41078. this._color.g = 1;
  41079. this._color.b = 1;
  41080. this._color.a = 1;
  41081. }
  41082. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41083. c += 4;
  41084. if (!this.recomputeNormals && meshNor) {
  41085. this._normal.x = meshNor[n];
  41086. this._normal.y = meshNor[n + 1];
  41087. this._normal.z = meshNor[n + 2];
  41088. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  41089. normals.push(this._normal.x, this._normal.y, this._normal.z);
  41090. n += 3;
  41091. }
  41092. }
  41093. for (i = 0; i < meshInd.length; i++) {
  41094. indices.push(p + meshInd[i]);
  41095. }
  41096. if (this._pickable) {
  41097. var nbfaces = meshInd.length / 3;
  41098. for (i = 0; i < nbfaces; i++) {
  41099. this.pickedParticles.push({ idx: idx, faceId: i });
  41100. }
  41101. }
  41102. return this._copy;
  41103. };
  41104. // returns a shape array from positions array
  41105. SolidParticleSystem.prototype._posToShape = function (positions) {
  41106. var shape = [];
  41107. for (var i = 0; i < positions.length; i += 3) {
  41108. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41109. }
  41110. return shape;
  41111. };
  41112. // returns a shapeUV array from a Vector4 uvs
  41113. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41114. var shapeUV = [];
  41115. if (uvs) {
  41116. for (var i = 0; i < uvs.length; i++)
  41117. shapeUV.push(uvs[i]);
  41118. }
  41119. return shapeUV;
  41120. };
  41121. // adds a new particle object in the particles array
  41122. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  41123. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  41124. this.particles.push(sp);
  41125. return sp;
  41126. };
  41127. /**
  41128. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41129. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  41130. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  41131. * `nb` (positive integer) the number of particles to be created from this model
  41132. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41133. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41134. */
  41135. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41136. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41137. var meshInd = mesh.getIndices();
  41138. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41139. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41140. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41141. var bbInfo;
  41142. if (this._particlesIntersect) {
  41143. bbInfo = mesh.getBoundingInfo();
  41144. }
  41145. var shape = this._posToShape(meshPos);
  41146. var shapeUV = this._uvsToShapeUV(meshUV);
  41147. var posfunc = options ? options.positionFunction : null;
  41148. var vtxfunc = options ? options.vertexFunction : null;
  41149. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41150. // particles
  41151. var sp;
  41152. var currentCopy;
  41153. var idx = this.nbParticles;
  41154. for (var i = 0; i < nb; i++) {
  41155. var currentPos = this._positions.length;
  41156. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  41157. if (this._updatable) {
  41158. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  41159. sp.position.copyFrom(currentCopy.position);
  41160. sp.rotation.copyFrom(currentCopy.rotation);
  41161. if (currentCopy.rotationQuaternion) {
  41162. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  41163. }
  41164. if (currentCopy.color) {
  41165. sp.color.copyFrom(currentCopy.color);
  41166. }
  41167. sp.scaling.copyFrom(currentCopy.scaling);
  41168. sp.uvs.copyFrom(currentCopy.uvs);
  41169. }
  41170. this._index += shape.length;
  41171. idx++;
  41172. }
  41173. this.nbParticles += nb;
  41174. this._shapeCounter++;
  41175. return this._shapeCounter - 1;
  41176. };
  41177. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41178. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41179. this._resetCopy();
  41180. if (particle._model._positionFunction) {
  41181. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41182. }
  41183. if (this._copy.rotationQuaternion) {
  41184. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41185. }
  41186. else {
  41187. this._yaw = this._copy.rotation.y;
  41188. this._pitch = this._copy.rotation.x;
  41189. this._roll = this._copy.rotation.z;
  41190. this._quaternionRotationYPR();
  41191. }
  41192. this._quaternionToRotationMatrix();
  41193. this._shape = particle._model._shape;
  41194. for (var pt = 0; pt < this._shape.length; pt++) {
  41195. this._vertex.x = this._shape[pt].x;
  41196. this._vertex.y = this._shape[pt].y;
  41197. this._vertex.z = this._shape[pt].z;
  41198. if (particle._model._vertexFunction) {
  41199. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41200. }
  41201. this._vertex.x *= this._copy.scaling.x;
  41202. this._vertex.y *= this._copy.scaling.y;
  41203. this._vertex.z *= this._copy.scaling.z;
  41204. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41205. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41206. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41207. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41208. }
  41209. particle.position.x = 0.0;
  41210. particle.position.y = 0.0;
  41211. particle.position.z = 0.0;
  41212. particle.rotation.x = 0.0;
  41213. particle.rotation.y = 0.0;
  41214. particle.rotation.z = 0.0;
  41215. particle.rotationQuaternion = null;
  41216. particle.scaling.x = 1.0;
  41217. particle.scaling.y = 1.0;
  41218. particle.scaling.z = 1.0;
  41219. };
  41220. /**
  41221. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41222. * Returns the SPS.
  41223. */
  41224. SolidParticleSystem.prototype.rebuildMesh = function () {
  41225. for (var p = 0; p < this.particles.length; p++) {
  41226. this._rebuildParticle(this.particles[p]);
  41227. }
  41228. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41229. return this;
  41230. };
  41231. /**
  41232. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41233. * This method calls `updateParticle()` for each particle of the SPS.
  41234. * For an animated SPS, it is usually called within the render loop.
  41235. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  41236. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  41237. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  41238. * Returns the SPS.
  41239. */
  41240. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41241. if (start === void 0) { start = 0; }
  41242. if (end === void 0) { end = this.nbParticles - 1; }
  41243. if (update === void 0) { update = true; }
  41244. if (!this._updatable) {
  41245. return;
  41246. }
  41247. // custom beforeUpdate
  41248. this.beforeUpdateParticles(start, end, update);
  41249. this._cam_axisX.x = 1.0;
  41250. this._cam_axisX.y = 0.0;
  41251. this._cam_axisX.z = 0.0;
  41252. this._cam_axisY.x = 0.0;
  41253. this._cam_axisY.y = 1.0;
  41254. this._cam_axisY.z = 0.0;
  41255. this._cam_axisZ.x = 0.0;
  41256. this._cam_axisZ.y = 0.0;
  41257. this._cam_axisZ.z = 1.0;
  41258. // if the particles will always face the camera
  41259. if (this.billboard) {
  41260. this.mesh.computeWorldMatrix(true);
  41261. // compute the camera position and un-rotate it by the current mesh rotation
  41262. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  41263. this._quaternionToRotationMatrix();
  41264. this._rotMatrix.invertToRef(this._invertMatrix);
  41265. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  41266. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  41267. this._cam_axisZ.normalize();
  41268. // same for camera up vector extracted from the cam view matrix
  41269. var view = this._camera.getViewMatrix(true);
  41270. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  41271. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  41272. this._cam_axisY.normalize();
  41273. this._cam_axisX.normalize();
  41274. }
  41275. }
  41276. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41277. var idx = 0; // current position index in the global array positions32
  41278. var index = 0; // position start index in the global array positions32 of the current particle
  41279. var colidx = 0; // current color index in the global array colors32
  41280. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  41281. var uvidx = 0; // current uv index in the global array uvs32
  41282. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  41283. var pt = 0; // current index in the particle model shape
  41284. if (this.mesh.isFacetDataEnabled) {
  41285. this._computeBoundingBox = true;
  41286. }
  41287. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  41288. if (this._computeBoundingBox) {
  41289. if (start == 0 && end == this.nbParticles - 1) {
  41290. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41291. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41292. }
  41293. else {
  41294. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  41295. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  41296. }
  41297. }
  41298. // particle loop
  41299. index = this.particles[start]._pos;
  41300. var vpos = (index / 3) | 0;
  41301. colorIndex = vpos * 4;
  41302. uvIndex = vpos * 2;
  41303. for (var p = start; p <= end; p++) {
  41304. this._particle = this.particles[p];
  41305. this._shape = this._particle._model._shape;
  41306. this._shapeUV = this._particle._model._shapeUV;
  41307. // call to custom user function to update the particle properties
  41308. this.updateParticle(this._particle);
  41309. // skip the computations for inactive or already invisible particles
  41310. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  41311. // increment indexes for the next particle
  41312. pt = this._shape.length;
  41313. index += pt * 3;
  41314. colorIndex += pt * 4;
  41315. uvIndex += pt * 2;
  41316. continue;
  41317. }
  41318. if (this._particle.isVisible) {
  41319. this._particle._stillInvisible = false; // un-mark permanent invisibility
  41320. // particle rotation matrix
  41321. if (this.billboard) {
  41322. this._particle.rotation.x = 0.0;
  41323. this._particle.rotation.y = 0.0;
  41324. }
  41325. if (this._computeParticleRotation || this.billboard) {
  41326. if (this._particle.rotationQuaternion) {
  41327. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41328. }
  41329. else {
  41330. this._yaw = this._particle.rotation.y;
  41331. this._pitch = this._particle.rotation.x;
  41332. this._roll = this._particle.rotation.z;
  41333. this._quaternionRotationYPR();
  41334. }
  41335. this._quaternionToRotationMatrix();
  41336. }
  41337. // particle vertex loop
  41338. for (pt = 0; pt < this._shape.length; pt++) {
  41339. idx = index + pt * 3;
  41340. colidx = colorIndex + pt * 4;
  41341. uvidx = uvIndex + pt * 2;
  41342. this._vertex.x = this._shape[pt].x;
  41343. this._vertex.y = this._shape[pt].y;
  41344. this._vertex.z = this._shape[pt].z;
  41345. if (this._computeParticleVertex) {
  41346. this.updateParticleVertex(this._particle, this._vertex, pt);
  41347. }
  41348. // positions
  41349. this._vertex.x *= this._particle.scaling.x;
  41350. this._vertex.y *= this._particle.scaling.y;
  41351. this._vertex.z *= this._particle.scaling.z;
  41352. 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];
  41353. 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;
  41354. 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;
  41355. 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;
  41356. 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;
  41357. 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;
  41358. 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;
  41359. if (this._computeBoundingBox) {
  41360. if (this._positions32[idx] < this._minimum.x) {
  41361. this._minimum.x = this._positions32[idx];
  41362. }
  41363. if (this._positions32[idx] > this._maximum.x) {
  41364. this._maximum.x = this._positions32[idx];
  41365. }
  41366. if (this._positions32[idx + 1] < this._minimum.y) {
  41367. this._minimum.y = this._positions32[idx + 1];
  41368. }
  41369. if (this._positions32[idx + 1] > this._maximum.y) {
  41370. this._maximum.y = this._positions32[idx + 1];
  41371. }
  41372. if (this._positions32[idx + 2] < this._minimum.z) {
  41373. this._minimum.z = this._positions32[idx + 2];
  41374. }
  41375. if (this._positions32[idx + 2] > this._maximum.z) {
  41376. this._maximum.z = this._positions32[idx + 2];
  41377. }
  41378. }
  41379. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  41380. if (!this._computeParticleVertex) {
  41381. this._normal.x = this._fixedNormal32[idx];
  41382. this._normal.y = this._fixedNormal32[idx + 1];
  41383. this._normal.z = this._fixedNormal32[idx + 2];
  41384. 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]);
  41385. 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]);
  41386. 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]);
  41387. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41388. 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;
  41389. 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;
  41390. }
  41391. if (this._computeParticleColor) {
  41392. this._colors32[colidx] = this._particle.color.r;
  41393. this._colors32[colidx + 1] = this._particle.color.g;
  41394. this._colors32[colidx + 2] = this._particle.color.b;
  41395. this._colors32[colidx + 3] = this._particle.color.a;
  41396. }
  41397. if (this._computeParticleTexture) {
  41398. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41399. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41400. }
  41401. }
  41402. }
  41403. else {
  41404. this._particle._stillInvisible = true; // mark the particle as invisible
  41405. for (pt = 0; pt < this._shape.length; pt++) {
  41406. idx = index + pt * 3;
  41407. colidx = colorIndex + pt * 4;
  41408. uvidx = uvIndex + pt * 2;
  41409. this._positions32[idx] = 0.0;
  41410. this._positions32[idx + 1] = 0.0;
  41411. this._positions32[idx + 2] = 0.0;
  41412. this._normals32[idx] = 0.0;
  41413. this._normals32[idx + 1] = 0.0;
  41414. this._normals32[idx + 2] = 0.0;
  41415. if (this._computeParticleColor) {
  41416. this._colors32[colidx] = this._particle.color.r;
  41417. this._colors32[colidx + 1] = this._particle.color.g;
  41418. this._colors32[colidx + 2] = this._particle.color.b;
  41419. this._colors32[colidx + 3] = this._particle.color.a;
  41420. }
  41421. if (this._computeParticleTexture) {
  41422. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41423. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41424. }
  41425. }
  41426. }
  41427. // if the particle intersections must be computed : update the bbInfo
  41428. if (this._particlesIntersect) {
  41429. var bInfo = this._particle._boundingInfo;
  41430. var bBox = bInfo.boundingBox;
  41431. var bSphere = bInfo.boundingSphere;
  41432. if (!this._bSphereOnly) {
  41433. // place, scale and rotate the particle bbox within the SPS local system, then update it
  41434. for (var b = 0; b < bBox.vectors.length; b++) {
  41435. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  41436. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  41437. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  41438. 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];
  41439. 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;
  41440. 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;
  41441. 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;
  41442. bBox.vectors[b].x = 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;
  41443. bBox.vectors[b].y = 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;
  41444. bBox.vectors[b].z = 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;
  41445. }
  41446. bBox._update(this.mesh._worldMatrix);
  41447. }
  41448. // place and scale the particle bouding sphere in the SPS local system, then update it
  41449. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  41450. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  41451. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  41452. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  41453. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  41454. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  41455. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  41456. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  41457. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  41458. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  41459. bSphere._update(this.mesh._worldMatrix);
  41460. }
  41461. // increment indexes for the next particle
  41462. index = idx + 3;
  41463. colorIndex = colidx + 4;
  41464. uvIndex = uvidx + 2;
  41465. }
  41466. // if the VBO must be updated
  41467. if (update) {
  41468. if (this._computeParticleColor) {
  41469. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41470. }
  41471. if (this._computeParticleTexture) {
  41472. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41473. }
  41474. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41475. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  41476. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  41477. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  41478. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  41479. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  41480. for (var i = 0; i < this._normals32.length; i++) {
  41481. this._fixedNormal32[i] = this._normals32[i];
  41482. }
  41483. }
  41484. if (!this.mesh.areNormalsFrozen) {
  41485. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41486. }
  41487. }
  41488. }
  41489. if (this._computeBoundingBox) {
  41490. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41491. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41492. }
  41493. this.afterUpdateParticles(start, end, update);
  41494. return this;
  41495. };
  41496. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  41497. this._halfroll = this._roll * 0.5;
  41498. this._halfpitch = this._pitch * 0.5;
  41499. this._halfyaw = this._yaw * 0.5;
  41500. this._sinRoll = Math.sin(this._halfroll);
  41501. this._cosRoll = Math.cos(this._halfroll);
  41502. this._sinPitch = Math.sin(this._halfpitch);
  41503. this._cosPitch = Math.cos(this._halfpitch);
  41504. this._sinYaw = Math.sin(this._halfyaw);
  41505. this._cosYaw = Math.cos(this._halfyaw);
  41506. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  41507. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  41508. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  41509. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  41510. };
  41511. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  41512. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  41513. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  41514. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  41515. this._rotMatrix.m[3] = 0;
  41516. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  41517. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  41518. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  41519. this._rotMatrix.m[7] = 0;
  41520. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  41521. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  41522. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  41523. this._rotMatrix.m[11] = 0;
  41524. this._rotMatrix.m[12] = 0;
  41525. this._rotMatrix.m[13] = 0;
  41526. this._rotMatrix.m[14] = 0;
  41527. this._rotMatrix.m[15] = 1.0;
  41528. };
  41529. /**
  41530. * Disposes the SPS.
  41531. * Returns nothing.
  41532. */
  41533. SolidParticleSystem.prototype.dispose = function () {
  41534. this.mesh.dispose();
  41535. this.vars = null;
  41536. // drop references to internal big arrays for the GC
  41537. this._positions = null;
  41538. this._indices = null;
  41539. this._normals = null;
  41540. this._uvs = null;
  41541. this._colors = null;
  41542. this._positions32 = null;
  41543. this._normals32 = null;
  41544. this._fixedNormal32 = null;
  41545. this._uvs32 = null;
  41546. this._colors32 = null;
  41547. this.pickedParticles = null;
  41548. };
  41549. /**
  41550. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  41551. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41552. * Returns the SPS.
  41553. */
  41554. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  41555. if (!this._isVisibilityBoxLocked) {
  41556. this.mesh.refreshBoundingInfo();
  41557. }
  41558. return this;
  41559. };
  41560. /**
  41561. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  41562. * @param size the size (float) of the visibility box
  41563. * note : this doesn't lock the SPS mesh bounding box.
  41564. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41565. */
  41566. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  41567. var vis = size / 2;
  41568. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  41569. };
  41570. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  41571. // getter and setter
  41572. get: function () {
  41573. return this._alwaysVisible;
  41574. },
  41575. /**
  41576. * Sets the SPS as always visible or not
  41577. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41578. */
  41579. set: function (val) {
  41580. this._alwaysVisible = val;
  41581. this.mesh.alwaysSelectAsActiveMesh = val;
  41582. },
  41583. enumerable: true,
  41584. configurable: true
  41585. });
  41586. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  41587. get: function () {
  41588. return this._isVisibilityBoxLocked;
  41589. },
  41590. /**
  41591. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  41592. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41593. */
  41594. set: function (val) {
  41595. this._isVisibilityBoxLocked = val;
  41596. this.mesh.getBoundingInfo().isLocked = val;
  41597. },
  41598. enumerable: true,
  41599. configurable: true
  41600. });
  41601. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  41602. // getters
  41603. get: function () {
  41604. return this._computeParticleRotation;
  41605. },
  41606. // Optimizer setters
  41607. /**
  41608. * Tells to `setParticles()` to compute the particle rotations or not.
  41609. * Default value : true. The SPS is faster when it's set to false.
  41610. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  41611. */
  41612. set: function (val) {
  41613. this._computeParticleRotation = val;
  41614. },
  41615. enumerable: true,
  41616. configurable: true
  41617. });
  41618. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  41619. get: function () {
  41620. return this._computeParticleColor;
  41621. },
  41622. /**
  41623. * Tells to `setParticles()` to compute the particle colors or not.
  41624. * Default value : true. The SPS is faster when it's set to false.
  41625. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  41626. */
  41627. set: function (val) {
  41628. this._computeParticleColor = val;
  41629. },
  41630. enumerable: true,
  41631. configurable: true
  41632. });
  41633. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  41634. get: function () {
  41635. return this._computeParticleTexture;
  41636. },
  41637. /**
  41638. * Tells to `setParticles()` to compute the particle textures or not.
  41639. * Default value : true. The SPS is faster when it's set to false.
  41640. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  41641. */
  41642. set: function (val) {
  41643. this._computeParticleTexture = val;
  41644. },
  41645. enumerable: true,
  41646. configurable: true
  41647. });
  41648. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  41649. get: function () {
  41650. return this._computeParticleVertex;
  41651. },
  41652. /**
  41653. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  41654. * Default value : false. The SPS is faster when it's set to false.
  41655. * Note : the particle custom vertex positions aren't stored values.
  41656. */
  41657. set: function (val) {
  41658. this._computeParticleVertex = val;
  41659. },
  41660. enumerable: true,
  41661. configurable: true
  41662. });
  41663. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  41664. get: function () {
  41665. return this._computeBoundingBox;
  41666. },
  41667. /**
  41668. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  41669. */
  41670. set: function (val) {
  41671. this._computeBoundingBox = val;
  41672. },
  41673. enumerable: true,
  41674. configurable: true
  41675. });
  41676. // =======================================================================
  41677. // Particle behavior logic
  41678. // these following methods may be overwritten by the user to fit his needs
  41679. /**
  41680. * This function does nothing. It may be overwritten to set all the particle first values.
  41681. * The SPS doesn't call this function, you may have to call it by your own.
  41682. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41683. */
  41684. SolidParticleSystem.prototype.initParticles = function () {
  41685. };
  41686. /**
  41687. * This function does nothing. It may be overwritten to recycle a particle.
  41688. * The SPS doesn't call this function, you may have to call it by your own.
  41689. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41690. */
  41691. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  41692. return particle;
  41693. };
  41694. /**
  41695. * Updates a particle : this function should be overwritten by the user.
  41696. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  41697. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41698. * ex : just set a particle position or velocity and recycle conditions
  41699. */
  41700. SolidParticleSystem.prototype.updateParticle = function (particle) {
  41701. return particle;
  41702. };
  41703. /**
  41704. * Updates a vertex of a particle : it can be overwritten by the user.
  41705. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  41706. * @param particle the current particle
  41707. * @param vertex the current index of the current particle
  41708. * @param pt the index of the current vertex in the particle shape
  41709. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  41710. * ex : just set a vertex particle position
  41711. */
  41712. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  41713. return vertex;
  41714. };
  41715. /**
  41716. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  41717. * This does nothing and may be overwritten by the user.
  41718. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41719. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41720. * @param update the boolean update value actually passed to setParticles()
  41721. */
  41722. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  41723. };
  41724. /**
  41725. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  41726. * This will be passed three parameters.
  41727. * This does nothing and may be overwritten by the user.
  41728. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41729. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41730. * @param update the boolean update value actually passed to setParticles()
  41731. */
  41732. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  41733. };
  41734. return SolidParticleSystem;
  41735. }());
  41736. BABYLON.SolidParticleSystem = SolidParticleSystem;
  41737. })(BABYLON || (BABYLON = {}));
  41738. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  41739. /// <reference path="babylon.mesh.ts" />
  41740. var BABYLON;
  41741. (function (BABYLON) {
  41742. var GroundMesh = (function (_super) {
  41743. __extends(GroundMesh, _super);
  41744. function GroundMesh(name, scene) {
  41745. var _this = _super.call(this, name, scene) || this;
  41746. _this.generateOctree = false;
  41747. _this._worldInverse = new BABYLON.Matrix();
  41748. return _this;
  41749. }
  41750. GroundMesh.prototype.getClassName = function () {
  41751. return "GroundMesh";
  41752. };
  41753. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41754. get: function () {
  41755. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41756. },
  41757. enumerable: true,
  41758. configurable: true
  41759. });
  41760. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41761. get: function () {
  41762. return this._subdivisionsX;
  41763. },
  41764. enumerable: true,
  41765. configurable: true
  41766. });
  41767. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41768. get: function () {
  41769. return this._subdivisionsY;
  41770. },
  41771. enumerable: true,
  41772. configurable: true
  41773. });
  41774. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41775. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41776. this._subdivisionsX = chunksCount;
  41777. this._subdivisionsY = chunksCount;
  41778. this.subdivide(chunksCount);
  41779. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41780. };
  41781. /**
  41782. * Returns a height (y) value in the Worl system :
  41783. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41784. * Returns the ground y position if (x, z) are outside the ground surface.
  41785. */
  41786. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41787. var world = this.getWorldMatrix();
  41788. var invMat = BABYLON.Tmp.Matrix[5];
  41789. world.invertToRef(invMat);
  41790. var tmpVect = BABYLON.Tmp.Vector3[8];
  41791. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41792. x = tmpVect.x;
  41793. z = tmpVect.z;
  41794. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41795. return this.position.y;
  41796. }
  41797. if (!this._heightQuads || this._heightQuads.length == 0) {
  41798. this._initHeightQuads();
  41799. this._computeHeightQuads();
  41800. }
  41801. var facet = this._getFacetAt(x, z);
  41802. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41803. // return y in the World system
  41804. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41805. return tmpVect.y;
  41806. };
  41807. /**
  41808. * Returns a normalized vector (Vector3) orthogonal to the ground
  41809. * at the ground coordinates (x, z) expressed in the World system.
  41810. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41811. */
  41812. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41813. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41814. this.getNormalAtCoordinatesToRef(x, z, normal);
  41815. return normal;
  41816. };
  41817. /**
  41818. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41819. * at the ground coordinates (x, z) expressed in the World system.
  41820. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41821. * Returns the GroundMesh.
  41822. */
  41823. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41824. var world = this.getWorldMatrix();
  41825. var tmpMat = BABYLON.Tmp.Matrix[5];
  41826. world.invertToRef(tmpMat);
  41827. var tmpVect = BABYLON.Tmp.Vector3[8];
  41828. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41829. x = tmpVect.x;
  41830. z = tmpVect.z;
  41831. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41832. return this;
  41833. }
  41834. if (!this._heightQuads || this._heightQuads.length == 0) {
  41835. this._initHeightQuads();
  41836. this._computeHeightQuads();
  41837. }
  41838. var facet = this._getFacetAt(x, z);
  41839. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41840. return this;
  41841. };
  41842. /**
  41843. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41844. * if the ground has been updated.
  41845. * This can be used in the render loop.
  41846. * Returns the GroundMesh.
  41847. */
  41848. GroundMesh.prototype.updateCoordinateHeights = function () {
  41849. if (!this._heightQuads || this._heightQuads.length == 0) {
  41850. this._initHeightQuads();
  41851. }
  41852. this._computeHeightQuads();
  41853. return this;
  41854. };
  41855. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41856. GroundMesh.prototype._getFacetAt = function (x, z) {
  41857. // retrieve col and row from x, z coordinates in the ground local system
  41858. var subdivisionsX = this._subdivisionsX;
  41859. var subdivisionsY = this._subdivisionsY;
  41860. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41861. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41862. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41863. var facet;
  41864. if (z < quad.slope.x * x + quad.slope.y) {
  41865. facet = quad.facet1;
  41866. }
  41867. else {
  41868. facet = quad.facet2;
  41869. }
  41870. return facet;
  41871. };
  41872. // Creates and populates the heightMap array with "facet" elements :
  41873. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  41874. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41875. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41876. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41877. // Returns the GroundMesh.
  41878. GroundMesh.prototype._initHeightQuads = function () {
  41879. var subdivisionsX = this._subdivisionsX;
  41880. var subdivisionsY = this._subdivisionsY;
  41881. this._heightQuads = new Array();
  41882. for (var row = 0; row < subdivisionsY; row++) {
  41883. for (var col = 0; col < subdivisionsX; col++) {
  41884. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  41885. this._heightQuads[row * subdivisionsX + col] = quad;
  41886. }
  41887. }
  41888. return this;
  41889. };
  41890. // Compute each quad element values and update the the heightMap array :
  41891. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41892. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41893. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41894. // Returns the GroundMesh.
  41895. GroundMesh.prototype._computeHeightQuads = function () {
  41896. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41897. var v1 = BABYLON.Tmp.Vector3[3];
  41898. var v2 = BABYLON.Tmp.Vector3[2];
  41899. var v3 = BABYLON.Tmp.Vector3[1];
  41900. var v4 = BABYLON.Tmp.Vector3[0];
  41901. var v1v2 = BABYLON.Tmp.Vector3[4];
  41902. var v1v3 = BABYLON.Tmp.Vector3[5];
  41903. var v1v4 = BABYLON.Tmp.Vector3[6];
  41904. var norm1 = BABYLON.Tmp.Vector3[7];
  41905. var norm2 = BABYLON.Tmp.Vector3[8];
  41906. var i = 0;
  41907. var j = 0;
  41908. var k = 0;
  41909. var cd = 0; // 2D slope coefficient : z = cd * x + h
  41910. var h = 0;
  41911. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  41912. var d2 = 0;
  41913. var subdivisionsX = this._subdivisionsX;
  41914. var subdivisionsY = this._subdivisionsY;
  41915. for (var row = 0; row < subdivisionsY; row++) {
  41916. for (var col = 0; col < subdivisionsX; col++) {
  41917. i = col * 3;
  41918. j = row * (subdivisionsX + 1) * 3;
  41919. k = (row + 1) * (subdivisionsX + 1) * 3;
  41920. v1.x = positions[j + i];
  41921. v1.y = positions[j + i + 1];
  41922. v1.z = positions[j + i + 2];
  41923. v2.x = positions[j + i + 3];
  41924. v2.y = positions[j + i + 4];
  41925. v2.z = positions[j + i + 5];
  41926. v3.x = positions[k + i];
  41927. v3.y = positions[k + i + 1];
  41928. v3.z = positions[k + i + 2];
  41929. v4.x = positions[k + i + 3];
  41930. v4.y = positions[k + i + 4];
  41931. v4.z = positions[k + i + 5];
  41932. // 2D slope V1V4
  41933. cd = (v4.z - v1.z) / (v4.x - v1.x);
  41934. h = v1.z - cd * v1.x; // v1 belongs to the slope
  41935. // facet equations :
  41936. // we compute each facet normal vector
  41937. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  41938. // we compute the value d by applying the equation to v1 which belongs to the plane
  41939. // then we store the facet equation in a Vector4
  41940. v2.subtractToRef(v1, v1v2);
  41941. v3.subtractToRef(v1, v1v3);
  41942. v4.subtractToRef(v1, v1v4);
  41943. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  41944. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  41945. norm1.normalize();
  41946. norm2.normalize();
  41947. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  41948. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  41949. var quad = this._heightQuads[row * subdivisionsX + col];
  41950. quad.slope.copyFromFloats(cd, h);
  41951. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41952. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41953. }
  41954. }
  41955. return this;
  41956. };
  41957. GroundMesh.prototype.serialize = function (serializationObject) {
  41958. _super.prototype.serialize.call(this, serializationObject);
  41959. serializationObject.subdivisionsX = this._subdivisionsX;
  41960. serializationObject.subdivisionsY = this._subdivisionsY;
  41961. serializationObject.minX = this._minX;
  41962. serializationObject.maxX = this._maxX;
  41963. serializationObject.minZ = this._minZ;
  41964. serializationObject.maxZ = this._maxZ;
  41965. serializationObject.width = this._width;
  41966. serializationObject.height = this._height;
  41967. };
  41968. GroundMesh.Parse = function (parsedMesh, scene) {
  41969. var result = new GroundMesh(parsedMesh.name, scene);
  41970. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41971. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41972. result._minX = parsedMesh.minX;
  41973. result._maxX = parsedMesh.maxX;
  41974. result._minZ = parsedMesh.minZ;
  41975. result._maxZ = parsedMesh.maxZ;
  41976. result._width = parsedMesh.width;
  41977. result._height = parsedMesh.height;
  41978. return result;
  41979. };
  41980. return GroundMesh;
  41981. }(BABYLON.Mesh));
  41982. BABYLON.GroundMesh = GroundMesh;
  41983. })(BABYLON || (BABYLON = {}));
  41984. //# sourceMappingURL=babylon.groundMesh.js.map
  41985. var BABYLON;
  41986. (function (BABYLON) {
  41987. /**
  41988. * Creates an instance based on a source mesh.
  41989. */
  41990. var InstancedMesh = (function (_super) {
  41991. __extends(InstancedMesh, _super);
  41992. function InstancedMesh(name, source) {
  41993. var _this = _super.call(this, name, source.getScene()) || this;
  41994. source.instances.push(_this);
  41995. _this._sourceMesh = source;
  41996. _this.position.copyFrom(source.position);
  41997. _this.rotation.copyFrom(source.rotation);
  41998. _this.scaling.copyFrom(source.scaling);
  41999. if (source.rotationQuaternion) {
  42000. _this.rotationQuaternion = source.rotationQuaternion.clone();
  42001. }
  42002. _this.infiniteDistance = source.infiniteDistance;
  42003. _this.setPivotMatrix(source.getPivotMatrix());
  42004. _this.refreshBoundingInfo();
  42005. _this._syncSubMeshes();
  42006. return _this;
  42007. }
  42008. /**
  42009. * Returns the string "InstancedMesh".
  42010. */
  42011. InstancedMesh.prototype.getClassName = function () {
  42012. return "InstancedMesh";
  42013. };
  42014. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  42015. // Methods
  42016. get: function () {
  42017. return this._sourceMesh.receiveShadows;
  42018. },
  42019. enumerable: true,
  42020. configurable: true
  42021. });
  42022. Object.defineProperty(InstancedMesh.prototype, "material", {
  42023. get: function () {
  42024. return this._sourceMesh.material;
  42025. },
  42026. enumerable: true,
  42027. configurable: true
  42028. });
  42029. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  42030. get: function () {
  42031. return this._sourceMesh.visibility;
  42032. },
  42033. enumerable: true,
  42034. configurable: true
  42035. });
  42036. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  42037. get: function () {
  42038. return this._sourceMesh.skeleton;
  42039. },
  42040. enumerable: true,
  42041. configurable: true
  42042. });
  42043. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  42044. get: function () {
  42045. return this._sourceMesh.renderingGroupId;
  42046. },
  42047. enumerable: true,
  42048. configurable: true
  42049. });
  42050. /**
  42051. * Returns the total number of vertices (integer).
  42052. */
  42053. InstancedMesh.prototype.getTotalVertices = function () {
  42054. return this._sourceMesh.getTotalVertices();
  42055. };
  42056. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  42057. get: function () {
  42058. return this._sourceMesh;
  42059. },
  42060. enumerable: true,
  42061. configurable: true
  42062. });
  42063. /**
  42064. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  42065. */
  42066. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  42067. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  42068. };
  42069. /**
  42070. * Sets the vertex data of the mesh geometry for the requested `kind`.
  42071. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  42072. * The `data` are either a numeric array either a Float32Array.
  42073. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  42074. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  42075. * Note that a new underlying VertexBuffer object is created each call.
  42076. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42077. *
  42078. * Possible `kind` values :
  42079. * - BABYLON.VertexBuffer.PositionKind
  42080. * - BABYLON.VertexBuffer.UVKind
  42081. * - BABYLON.VertexBuffer.UV2Kind
  42082. * - BABYLON.VertexBuffer.UV3Kind
  42083. * - BABYLON.VertexBuffer.UV4Kind
  42084. * - BABYLON.VertexBuffer.UV5Kind
  42085. * - BABYLON.VertexBuffer.UV6Kind
  42086. * - BABYLON.VertexBuffer.ColorKind
  42087. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42088. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42089. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42090. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42091. *
  42092. * Returns the Mesh.
  42093. */
  42094. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42095. if (this.sourceMesh) {
  42096. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  42097. }
  42098. return this.sourceMesh;
  42099. };
  42100. /**
  42101. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  42102. * If the mesh has no geometry, it is simply returned as it is.
  42103. * The `data` are either a numeric array either a Float32Array.
  42104. * No new underlying VertexBuffer object is created.
  42105. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42106. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  42107. *
  42108. * Possible `kind` values :
  42109. * - BABYLON.VertexBuffer.PositionKind
  42110. * - BABYLON.VertexBuffer.UVKind
  42111. * - BABYLON.VertexBuffer.UV2Kind
  42112. * - BABYLON.VertexBuffer.UV3Kind
  42113. * - BABYLON.VertexBuffer.UV4Kind
  42114. * - BABYLON.VertexBuffer.UV5Kind
  42115. * - BABYLON.VertexBuffer.UV6Kind
  42116. * - BABYLON.VertexBuffer.ColorKind
  42117. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42118. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42119. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42120. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42121. *
  42122. * Returns the Mesh.
  42123. */
  42124. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  42125. if (this.sourceMesh) {
  42126. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  42127. }
  42128. return this.sourceMesh;
  42129. };
  42130. /**
  42131. * Sets the mesh indices.
  42132. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  42133. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  42134. * This method creates a new index buffer each call.
  42135. * Returns the Mesh.
  42136. */
  42137. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  42138. if (this.sourceMesh) {
  42139. this.sourceMesh.setIndices(indices, totalVertices);
  42140. }
  42141. return this.sourceMesh;
  42142. };
  42143. /**
  42144. * Boolean : True if the mesh owns the requested kind of data.
  42145. */
  42146. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  42147. return this._sourceMesh.isVerticesDataPresent(kind);
  42148. };
  42149. /**
  42150. * Returns an array of indices (IndicesArray).
  42151. */
  42152. InstancedMesh.prototype.getIndices = function () {
  42153. return this._sourceMesh.getIndices();
  42154. };
  42155. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  42156. get: function () {
  42157. return this._sourceMesh._positions;
  42158. },
  42159. enumerable: true,
  42160. configurable: true
  42161. });
  42162. /**
  42163. * Sets a new updated BoundingInfo to the mesh.
  42164. * Returns the mesh.
  42165. */
  42166. InstancedMesh.prototype.refreshBoundingInfo = function () {
  42167. var meshBB = this._sourceMesh.getBoundingInfo();
  42168. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  42169. this._updateBoundingInfo();
  42170. return this;
  42171. };
  42172. InstancedMesh.prototype._preActivate = function () {
  42173. if (this._currentLOD) {
  42174. this._currentLOD._preActivate();
  42175. }
  42176. return this;
  42177. };
  42178. InstancedMesh.prototype._activate = function (renderId) {
  42179. if (this._currentLOD) {
  42180. this._currentLOD._registerInstanceForRenderId(this, renderId);
  42181. }
  42182. return this;
  42183. };
  42184. /**
  42185. * Returns the current associated LOD AbstractMesh.
  42186. */
  42187. InstancedMesh.prototype.getLOD = function (camera) {
  42188. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  42189. if (this._currentLOD === this.sourceMesh) {
  42190. return this;
  42191. }
  42192. return this._currentLOD;
  42193. };
  42194. InstancedMesh.prototype._syncSubMeshes = function () {
  42195. this.releaseSubMeshes();
  42196. if (this._sourceMesh.subMeshes) {
  42197. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  42198. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  42199. }
  42200. }
  42201. return this;
  42202. };
  42203. InstancedMesh.prototype._generatePointsArray = function () {
  42204. return this._sourceMesh._generatePointsArray();
  42205. };
  42206. /**
  42207. * Creates a new InstancedMesh from the current mesh.
  42208. * - name (string) : the cloned mesh name
  42209. * - newParent (optional Node) : the optional Node to parent the clone to.
  42210. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  42211. *
  42212. * Returns the clone.
  42213. */
  42214. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42215. var result = this._sourceMesh.createInstance(name);
  42216. // Deep copy
  42217. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  42218. // Bounding info
  42219. this.refreshBoundingInfo();
  42220. // Parent
  42221. if (newParent) {
  42222. result.parent = newParent;
  42223. }
  42224. if (!doNotCloneChildren) {
  42225. // Children
  42226. for (var index = 0; index < this.getScene().meshes.length; index++) {
  42227. var mesh = this.getScene().meshes[index];
  42228. if (mesh.parent === this) {
  42229. mesh.clone(mesh.name, result);
  42230. }
  42231. }
  42232. }
  42233. result.computeWorldMatrix(true);
  42234. return result;
  42235. };
  42236. /**
  42237. * Disposes the InstancedMesh.
  42238. * Returns nothing.
  42239. */
  42240. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  42241. // Remove from mesh
  42242. var index = this._sourceMesh.instances.indexOf(this);
  42243. this._sourceMesh.instances.splice(index, 1);
  42244. _super.prototype.dispose.call(this, doNotRecurse);
  42245. };
  42246. return InstancedMesh;
  42247. }(BABYLON.AbstractMesh));
  42248. BABYLON.InstancedMesh = InstancedMesh;
  42249. })(BABYLON || (BABYLON = {}));
  42250. //# sourceMappingURL=babylon.instancedMesh.js.map
  42251. /// <reference path="babylon.mesh.ts" />
  42252. var BABYLON;
  42253. (function (BABYLON) {
  42254. var LinesMesh = (function (_super) {
  42255. __extends(LinesMesh, _super);
  42256. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  42257. if (parent === void 0) { parent = null; }
  42258. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42259. _this.useVertexColor = useVertexColor;
  42260. _this.color = new BABYLON.Color3(1, 1, 1);
  42261. _this.alpha = 1;
  42262. if (source) {
  42263. _this.color = source.color.clone();
  42264. _this.alpha = source.alpha;
  42265. _this.useVertexColor = source.useVertexColor;
  42266. }
  42267. _this._intersectionThreshold = 0.1;
  42268. var options = {
  42269. attributes: [BABYLON.VertexBuffer.PositionKind],
  42270. uniforms: ["world", "viewProjection"],
  42271. needAlphaBlending: false,
  42272. };
  42273. if (!useVertexColor) {
  42274. options.uniforms.push("color");
  42275. options.needAlphaBlending = true;
  42276. }
  42277. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  42278. return _this;
  42279. }
  42280. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42281. /**
  42282. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42283. * This margin is expressed in world space coordinates, so its value may vary.
  42284. * Default value is 0.1
  42285. * @returns the intersection Threshold value.
  42286. */
  42287. get: function () {
  42288. return this._intersectionThreshold;
  42289. },
  42290. /**
  42291. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42292. * This margin is expressed in world space coordinates, so its value may vary.
  42293. * @param value the new threshold to apply
  42294. */
  42295. set: function (value) {
  42296. if (this._intersectionThreshold === value) {
  42297. return;
  42298. }
  42299. this._intersectionThreshold = value;
  42300. if (this.geometry) {
  42301. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42302. }
  42303. },
  42304. enumerable: true,
  42305. configurable: true
  42306. });
  42307. /**
  42308. * Returns the string "LineMesh"
  42309. */
  42310. LinesMesh.prototype.getClassName = function () {
  42311. return "LinesMesh";
  42312. };
  42313. Object.defineProperty(LinesMesh.prototype, "material", {
  42314. get: function () {
  42315. return this._colorShader;
  42316. },
  42317. enumerable: true,
  42318. configurable: true
  42319. });
  42320. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42321. get: function () {
  42322. return false;
  42323. },
  42324. enumerable: true,
  42325. configurable: true
  42326. });
  42327. LinesMesh.prototype.createInstance = function (name) {
  42328. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42329. return null;
  42330. };
  42331. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42332. // VBOs
  42333. this._geometry._bind(this._colorShader.getEffect());
  42334. // Color
  42335. if (!this.useVertexColor) {
  42336. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42337. }
  42338. return this;
  42339. };
  42340. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42341. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42342. return this;
  42343. }
  42344. var engine = this.getScene().getEngine();
  42345. // Draw order
  42346. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42347. return this;
  42348. };
  42349. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42350. this._colorShader.dispose();
  42351. _super.prototype.dispose.call(this, doNotRecurse);
  42352. };
  42353. /**
  42354. * Returns a new LineMesh object cloned from the current one.
  42355. */
  42356. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42357. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42358. };
  42359. return LinesMesh;
  42360. }(BABYLON.Mesh));
  42361. BABYLON.LinesMesh = LinesMesh;
  42362. })(BABYLON || (BABYLON = {}));
  42363. //# sourceMappingURL=babylon.linesMesh.js.map
  42364. var BABYLON;
  42365. (function (BABYLON) {
  42366. var ShaderMaterial = (function (_super) {
  42367. __extends(ShaderMaterial, _super);
  42368. function ShaderMaterial(name, scene, shaderPath, options) {
  42369. var _this = _super.call(this, name, scene) || this;
  42370. _this._textures = {};
  42371. _this._textureArrays = {};
  42372. _this._floats = {};
  42373. _this._floatsArrays = {};
  42374. _this._colors3 = {};
  42375. _this._colors3Arrays = {};
  42376. _this._colors4 = {};
  42377. _this._vectors2 = {};
  42378. _this._vectors3 = {};
  42379. _this._vectors4 = {};
  42380. _this._matrices = {};
  42381. _this._matrices3x3 = {};
  42382. _this._matrices2x2 = {};
  42383. _this._vectors3Arrays = {};
  42384. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  42385. _this._shaderPath = shaderPath;
  42386. options.needAlphaBlending = options.needAlphaBlending || false;
  42387. options.needAlphaTesting = options.needAlphaTesting || false;
  42388. options.attributes = options.attributes || ["position", "normal", "uv"];
  42389. options.uniforms = options.uniforms || ["worldViewProjection"];
  42390. options.uniformBuffers = options.uniformBuffers || [];
  42391. options.samplers = options.samplers || [];
  42392. options.defines = options.defines || [];
  42393. _this._options = options;
  42394. return _this;
  42395. }
  42396. ShaderMaterial.prototype.getClassName = function () {
  42397. return "ShaderMaterial";
  42398. };
  42399. ShaderMaterial.prototype.needAlphaBlending = function () {
  42400. return this._options.needAlphaBlending;
  42401. };
  42402. ShaderMaterial.prototype.needAlphaTesting = function () {
  42403. return this._options.needAlphaTesting;
  42404. };
  42405. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  42406. if (this._options.uniforms.indexOf(uniformName) === -1) {
  42407. this._options.uniforms.push(uniformName);
  42408. }
  42409. };
  42410. ShaderMaterial.prototype.setTexture = function (name, texture) {
  42411. if (this._options.samplers.indexOf(name) === -1) {
  42412. this._options.samplers.push(name);
  42413. }
  42414. this._textures[name] = texture;
  42415. return this;
  42416. };
  42417. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  42418. if (this._options.samplers.indexOf(name) === -1) {
  42419. this._options.samplers.push(name);
  42420. }
  42421. this._checkUniform(name);
  42422. this._textureArrays[name] = textures;
  42423. return this;
  42424. };
  42425. ShaderMaterial.prototype.setFloat = function (name, value) {
  42426. this._checkUniform(name);
  42427. this._floats[name] = value;
  42428. return this;
  42429. };
  42430. ShaderMaterial.prototype.setFloats = function (name, value) {
  42431. this._checkUniform(name);
  42432. this._floatsArrays[name] = value;
  42433. return this;
  42434. };
  42435. ShaderMaterial.prototype.setColor3 = function (name, value) {
  42436. this._checkUniform(name);
  42437. this._colors3[name] = value;
  42438. return this;
  42439. };
  42440. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  42441. this._checkUniform(name);
  42442. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  42443. color.toArray(arr, arr.length);
  42444. return arr;
  42445. }, []);
  42446. return this;
  42447. };
  42448. ShaderMaterial.prototype.setColor4 = function (name, value) {
  42449. this._checkUniform(name);
  42450. this._colors4[name] = value;
  42451. return this;
  42452. };
  42453. ShaderMaterial.prototype.setVector2 = function (name, value) {
  42454. this._checkUniform(name);
  42455. this._vectors2[name] = value;
  42456. return this;
  42457. };
  42458. ShaderMaterial.prototype.setVector3 = function (name, value) {
  42459. this._checkUniform(name);
  42460. this._vectors3[name] = value;
  42461. return this;
  42462. };
  42463. ShaderMaterial.prototype.setVector4 = function (name, value) {
  42464. this._checkUniform(name);
  42465. this._vectors4[name] = value;
  42466. return this;
  42467. };
  42468. ShaderMaterial.prototype.setMatrix = function (name, value) {
  42469. this._checkUniform(name);
  42470. this._matrices[name] = value;
  42471. return this;
  42472. };
  42473. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  42474. this._checkUniform(name);
  42475. this._matrices3x3[name] = value;
  42476. return this;
  42477. };
  42478. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  42479. this._checkUniform(name);
  42480. this._matrices2x2[name] = value;
  42481. return this;
  42482. };
  42483. ShaderMaterial.prototype.setArray3 = function (name, value) {
  42484. this._checkUniform(name);
  42485. this._vectors3Arrays[name] = value;
  42486. return this;
  42487. };
  42488. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  42489. if (!mesh) {
  42490. return true;
  42491. }
  42492. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  42493. return false;
  42494. }
  42495. return false;
  42496. };
  42497. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  42498. var scene = this.getScene();
  42499. var engine = scene.getEngine();
  42500. if (!this.checkReadyOnEveryCall) {
  42501. if (this._renderId === scene.getRenderId()) {
  42502. if (this._checkCache(scene, mesh, useInstances)) {
  42503. return true;
  42504. }
  42505. }
  42506. }
  42507. // Instances
  42508. var defines = [];
  42509. var attribs = [];
  42510. var fallbacks = new BABYLON.EffectFallbacks();
  42511. if (useInstances) {
  42512. defines.push("#define INSTANCES");
  42513. }
  42514. for (var index = 0; index < this._options.defines.length; index++) {
  42515. defines.push(this._options.defines[index]);
  42516. }
  42517. for (var index = 0; index < this._options.attributes.length; index++) {
  42518. attribs.push(this._options.attributes[index]);
  42519. }
  42520. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42521. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42522. defines.push("#define VERTEXCOLOR");
  42523. }
  42524. // Bones
  42525. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  42526. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42527. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42528. if (mesh.numBoneInfluencers > 4) {
  42529. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42530. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42531. }
  42532. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42533. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42534. fallbacks.addCPUSkinningFallback(0, mesh);
  42535. if (this._options.uniforms.indexOf("mBones") === -1) {
  42536. this._options.uniforms.push("mBones");
  42537. }
  42538. }
  42539. else {
  42540. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42541. }
  42542. // Textures
  42543. for (var name in this._textures) {
  42544. if (!this._textures[name].isReady()) {
  42545. return false;
  42546. }
  42547. }
  42548. // Alpha test
  42549. if (engine.getAlphaTesting()) {
  42550. defines.push("#define ALPHATEST");
  42551. }
  42552. var previousEffect = this._effect;
  42553. var join = defines.join("\n");
  42554. this._effect = engine.createEffect(this._shaderPath, {
  42555. attributes: attribs,
  42556. uniformsNames: this._options.uniforms,
  42557. uniformBuffersNames: this._options.uniformBuffers,
  42558. samplers: this._options.samplers,
  42559. defines: join,
  42560. fallbacks: fallbacks,
  42561. onCompiled: this.onCompiled,
  42562. onError: this.onError
  42563. }, engine);
  42564. if (!this._effect.isReady()) {
  42565. return false;
  42566. }
  42567. if (previousEffect !== this._effect) {
  42568. scene.resetCachedMaterial();
  42569. }
  42570. this._renderId = scene.getRenderId();
  42571. return true;
  42572. };
  42573. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42574. var scene = this.getScene();
  42575. if (this._options.uniforms.indexOf("world") !== -1) {
  42576. this._effect.setMatrix("world", world);
  42577. }
  42578. if (this._options.uniforms.indexOf("worldView") !== -1) {
  42579. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  42580. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  42581. }
  42582. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  42583. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  42584. }
  42585. };
  42586. ShaderMaterial.prototype.bind = function (world, mesh) {
  42587. // Std values
  42588. this.bindOnlyWorldMatrix(world);
  42589. if (this.getScene().getCachedMaterial() !== this) {
  42590. if (this._options.uniforms.indexOf("view") !== -1) {
  42591. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  42592. }
  42593. if (this._options.uniforms.indexOf("projection") !== -1) {
  42594. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  42595. }
  42596. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  42597. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  42598. }
  42599. // Bones
  42600. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  42601. var name;
  42602. // Texture
  42603. for (name in this._textures) {
  42604. this._effect.setTexture(name, this._textures[name]);
  42605. }
  42606. // Texture arrays
  42607. for (name in this._textureArrays) {
  42608. this._effect.setTextureArray(name, this._textureArrays[name]);
  42609. }
  42610. // Float
  42611. for (name in this._floats) {
  42612. this._effect.setFloat(name, this._floats[name]);
  42613. }
  42614. // Float s
  42615. for (name in this._floatsArrays) {
  42616. this._effect.setArray(name, this._floatsArrays[name]);
  42617. }
  42618. // Color3
  42619. for (name in this._colors3) {
  42620. this._effect.setColor3(name, this._colors3[name]);
  42621. }
  42622. for (name in this._colors3Arrays) {
  42623. this._effect.setArray3(name, this._colors3Arrays[name]);
  42624. }
  42625. // Color4
  42626. for (name in this._colors4) {
  42627. var color = this._colors4[name];
  42628. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  42629. }
  42630. // Vector2
  42631. for (name in this._vectors2) {
  42632. this._effect.setVector2(name, this._vectors2[name]);
  42633. }
  42634. // Vector3
  42635. for (name in this._vectors3) {
  42636. this._effect.setVector3(name, this._vectors3[name]);
  42637. }
  42638. // Vector4
  42639. for (name in this._vectors4) {
  42640. this._effect.setVector4(name, this._vectors4[name]);
  42641. }
  42642. // Matrix
  42643. for (name in this._matrices) {
  42644. this._effect.setMatrix(name, this._matrices[name]);
  42645. }
  42646. // Matrix 3x3
  42647. for (name in this._matrices3x3) {
  42648. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  42649. }
  42650. // Matrix 2x2
  42651. for (name in this._matrices2x2) {
  42652. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  42653. }
  42654. // Vector3Array
  42655. for (name in this._vectors3Arrays) {
  42656. this._effect.setArray3(name, this._vectors3Arrays[name]);
  42657. }
  42658. }
  42659. this._afterBind(mesh);
  42660. };
  42661. ShaderMaterial.prototype.getActiveTextures = function () {
  42662. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42663. for (var name in this._textures) {
  42664. activeTextures.push(this._textures[name]);
  42665. }
  42666. for (var name in this._textureArrays) {
  42667. var array = this._textureArrays[name];
  42668. for (var index = 0; index < array.length; index++) {
  42669. activeTextures.push(array[index]);
  42670. }
  42671. }
  42672. return activeTextures;
  42673. };
  42674. ShaderMaterial.prototype.hasTexture = function (texture) {
  42675. if (_super.prototype.hasTexture.call(this, texture)) {
  42676. return true;
  42677. }
  42678. for (var name in this._textures) {
  42679. if (this._textures[name] === texture) {
  42680. return true;
  42681. }
  42682. }
  42683. for (var name in this._textureArrays) {
  42684. var array = this._textureArrays[name];
  42685. for (var index = 0; index < array.length; index++) {
  42686. if (array[index] === texture) {
  42687. return true;
  42688. }
  42689. }
  42690. }
  42691. return false;
  42692. };
  42693. ShaderMaterial.prototype.clone = function (name) {
  42694. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  42695. return newShaderMaterial;
  42696. };
  42697. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42698. if (forceDisposeTextures) {
  42699. var name;
  42700. for (name in this._textures) {
  42701. this._textures[name].dispose();
  42702. }
  42703. for (name in this._textureArrays) {
  42704. var array = this._textureArrays[name];
  42705. for (var index = 0; index < array.length; index++) {
  42706. array[index].dispose();
  42707. }
  42708. }
  42709. }
  42710. this._textures = {};
  42711. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42712. };
  42713. ShaderMaterial.prototype.serialize = function () {
  42714. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42715. serializationObject.customType = "BABYLON.ShaderMaterial";
  42716. serializationObject.options = this._options;
  42717. serializationObject.shaderPath = this._shaderPath;
  42718. var name;
  42719. // Texture
  42720. serializationObject.textures = {};
  42721. for (name in this._textures) {
  42722. serializationObject.textures[name] = this._textures[name].serialize();
  42723. }
  42724. // Texture arrays
  42725. serializationObject.textureArrays = {};
  42726. for (name in this._textureArrays) {
  42727. serializationObject.textureArrays[name] = [];
  42728. var array = this._textureArrays[name];
  42729. for (var index = 0; index < array.length; index++) {
  42730. serializationObject.textureArrays[name].push(array[index].serialize());
  42731. }
  42732. }
  42733. // Float
  42734. serializationObject.floats = {};
  42735. for (name in this._floats) {
  42736. serializationObject.floats[name] = this._floats[name];
  42737. }
  42738. // Float s
  42739. serializationObject.floatArrays = {};
  42740. for (name in this._floatsArrays) {
  42741. serializationObject.floatArrays[name] = this._floatsArrays[name];
  42742. }
  42743. // Color3
  42744. serializationObject.colors3 = {};
  42745. for (name in this._colors3) {
  42746. serializationObject.colors3[name] = this._colors3[name].asArray();
  42747. }
  42748. // Color3 array
  42749. serializationObject.colors3Arrays = {};
  42750. for (name in this._colors3Arrays) {
  42751. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  42752. }
  42753. // Color4
  42754. serializationObject.colors4 = {};
  42755. for (name in this._colors4) {
  42756. serializationObject.colors4[name] = this._colors4[name].asArray();
  42757. }
  42758. // Vector2
  42759. serializationObject.vectors2 = {};
  42760. for (name in this._vectors2) {
  42761. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  42762. }
  42763. // Vector3
  42764. serializationObject.vectors3 = {};
  42765. for (name in this._vectors3) {
  42766. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  42767. }
  42768. // Vector4
  42769. serializationObject.vectors4 = {};
  42770. for (name in this._vectors4) {
  42771. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  42772. }
  42773. // Matrix
  42774. serializationObject.matrices = {};
  42775. for (name in this._matrices) {
  42776. serializationObject.matrices[name] = this._matrices[name].asArray();
  42777. }
  42778. // Matrix 3x3
  42779. serializationObject.matrices3x3 = {};
  42780. for (name in this._matrices3x3) {
  42781. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  42782. }
  42783. // Matrix 2x2
  42784. serializationObject.matrices2x2 = {};
  42785. for (name in this._matrices2x2) {
  42786. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  42787. }
  42788. // Vector3Array
  42789. serializationObject.vectors3Arrays = {};
  42790. for (name in this._vectors3Arrays) {
  42791. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  42792. }
  42793. return serializationObject;
  42794. };
  42795. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  42796. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  42797. var name;
  42798. // Texture
  42799. for (name in source.textures) {
  42800. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  42801. }
  42802. // Texture arrays
  42803. for (name in source.textureArrays) {
  42804. var array = source.textureArrays[name];
  42805. var textureArray = new Array();
  42806. for (var index = 0; index < array.length; index++) {
  42807. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  42808. }
  42809. material.setTextureArray(name, textureArray);
  42810. }
  42811. // Float
  42812. for (name in source.floats) {
  42813. material.setFloat(name, source.floats[name]);
  42814. }
  42815. // Float s
  42816. for (name in source.floatsArrays) {
  42817. material.setFloats(name, source.floatsArrays[name]);
  42818. }
  42819. // Color3
  42820. for (name in source.colors3) {
  42821. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  42822. }
  42823. // Color3 arrays
  42824. for (name in source.colors3Arrays) {
  42825. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  42826. if (i % 3 === 0) {
  42827. arr.push([num]);
  42828. }
  42829. else {
  42830. arr[arr.length - 1].push(num);
  42831. }
  42832. return arr;
  42833. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  42834. material.setColor3Array(name, colors);
  42835. }
  42836. // Color4
  42837. for (name in source.colors4) {
  42838. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  42839. }
  42840. // Vector2
  42841. for (name in source.vectors2) {
  42842. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  42843. }
  42844. // Vector3
  42845. for (name in source.vectors3) {
  42846. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  42847. }
  42848. // Vector4
  42849. for (name in source.vectors4) {
  42850. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  42851. }
  42852. // Matrix
  42853. for (name in source.matrices) {
  42854. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  42855. }
  42856. // Matrix 3x3
  42857. for (name in source.matrices3x3) {
  42858. material.setMatrix3x3(name, source.matrices3x3[name]);
  42859. }
  42860. // Matrix 2x2
  42861. for (name in source.matrices2x2) {
  42862. material.setMatrix2x2(name, source.matrices2x2[name]);
  42863. }
  42864. // Vector3Array
  42865. for (name in source.vectors3Arrays) {
  42866. material.setArray3(name, source.vectors3Arrays[name]);
  42867. }
  42868. return material;
  42869. };
  42870. return ShaderMaterial;
  42871. }(BABYLON.Material));
  42872. BABYLON.ShaderMaterial = ShaderMaterial;
  42873. })(BABYLON || (BABYLON = {}));
  42874. //# sourceMappingURL=babylon.shaderMaterial.js.map
  42875. var BABYLON;
  42876. (function (BABYLON) {
  42877. var MeshBuilder = (function () {
  42878. function MeshBuilder() {
  42879. }
  42880. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  42881. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  42882. return BABYLON.Mesh.DOUBLESIDE;
  42883. }
  42884. if (orientation === undefined || orientation === null) {
  42885. return BABYLON.Mesh.FRONTSIDE;
  42886. }
  42887. return orientation;
  42888. };
  42889. /**
  42890. * Creates a box mesh.
  42891. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  42892. * The parameter `size` sets the size (float) of each box side (default 1).
  42893. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  42894. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements).
  42895. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  42896. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42897. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42898. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42900. */
  42901. MeshBuilder.CreateBox = function (name, options, scene) {
  42902. var box = new BABYLON.Mesh(name, scene);
  42903. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42904. box.sideOrientation = options.sideOrientation;
  42905. var vertexData = BABYLON.VertexData.CreateBox(options);
  42906. vertexData.applyToMesh(box, options.updatable);
  42907. return box;
  42908. };
  42909. /**
  42910. * Creates a sphere mesh.
  42911. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  42912. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  42913. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  42914. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  42915. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  42916. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  42917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42918. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42921. */
  42922. MeshBuilder.CreateSphere = function (name, options, scene) {
  42923. var sphere = new BABYLON.Mesh(name, scene);
  42924. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42925. sphere.sideOrientation = options.sideOrientation;
  42926. var vertexData = BABYLON.VertexData.CreateSphere(options);
  42927. vertexData.applyToMesh(sphere, options.updatable);
  42928. return sphere;
  42929. };
  42930. /**
  42931. * Creates a plane polygonal mesh. By default, this is a disc.
  42932. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  42933. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  42934. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  42935. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  42936. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42937. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42938. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42939. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42940. */
  42941. MeshBuilder.CreateDisc = function (name, options, scene) {
  42942. var disc = new BABYLON.Mesh(name, scene);
  42943. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42944. disc.sideOrientation = options.sideOrientation;
  42945. var vertexData = BABYLON.VertexData.CreateDisc(options);
  42946. vertexData.applyToMesh(disc, options.updatable);
  42947. return disc;
  42948. };
  42949. /**
  42950. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  42951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  42952. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  42953. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  42954. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  42955. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  42956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42957. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42958. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42960. */
  42961. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  42962. var sphere = new BABYLON.Mesh(name, scene);
  42963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42964. sphere.sideOrientation = options.sideOrientation;
  42965. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  42966. vertexData.applyToMesh(sphere, options.updatable);
  42967. return sphere;
  42968. };
  42969. ;
  42970. /**
  42971. * Creates a ribbon mesh.
  42972. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  42973. *
  42974. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  42975. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  42976. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  42977. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  42978. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  42979. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  42980. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  42981. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42982. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42983. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42984. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42985. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  42986. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  42987. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  42988. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  42989. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  42990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42991. */
  42992. MeshBuilder.CreateRibbon = function (name, options, scene) {
  42993. var pathArray = options.pathArray;
  42994. var closeArray = options.closeArray;
  42995. var closePath = options.closePath;
  42996. var offset = options.offset;
  42997. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42998. var instance = options.instance;
  42999. var updatable = options.updatable;
  43000. if (instance) {
  43001. // positionFunction : ribbon case
  43002. // only pathArray and sideOrientation parameters are taken into account for positions update
  43003. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  43004. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  43005. var positionFunction = function (positions) {
  43006. var minlg = pathArray[0].length;
  43007. var i = 0;
  43008. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  43009. for (var si = 1; si <= ns; si++) {
  43010. for (var p = 0; p < pathArray.length; p++) {
  43011. var path = pathArray[p];
  43012. var l = path.length;
  43013. minlg = (minlg < l) ? minlg : l;
  43014. var j = 0;
  43015. while (j < minlg) {
  43016. positions[i] = path[j].x;
  43017. positions[i + 1] = path[j].y;
  43018. positions[i + 2] = path[j].z;
  43019. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  43020. BABYLON.Tmp.Vector3[0].x = path[j].x;
  43021. }
  43022. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  43023. BABYLON.Tmp.Vector3[1].x = path[j].x;
  43024. }
  43025. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  43026. BABYLON.Tmp.Vector3[0].y = path[j].y;
  43027. }
  43028. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  43029. BABYLON.Tmp.Vector3[1].y = path[j].y;
  43030. }
  43031. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  43032. BABYLON.Tmp.Vector3[0].z = path[j].z;
  43033. }
  43034. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  43035. BABYLON.Tmp.Vector3[1].z = path[j].z;
  43036. }
  43037. j++;
  43038. i += 3;
  43039. }
  43040. if (instance._closePath) {
  43041. positions[i] = path[0].x;
  43042. positions[i + 1] = path[0].y;
  43043. positions[i + 2] = path[0].z;
  43044. i += 3;
  43045. }
  43046. }
  43047. }
  43048. };
  43049. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43050. positionFunction(positions);
  43051. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  43052. instance._boundingInfo.update(instance._worldMatrix);
  43053. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  43054. if (options.colors) {
  43055. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43056. for (var c = 0; c < options.colors.length; c++) {
  43057. colors[c * 4] = options.colors[c].r;
  43058. colors[c * 4 + 1] = options.colors[c].g;
  43059. colors[c * 4 + 2] = options.colors[c].b;
  43060. colors[c * 4 + 3] = options.colors[c].a;
  43061. }
  43062. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  43063. }
  43064. if (options.uvs) {
  43065. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43066. for (var i = 0; i < options.uvs.length; i++) {
  43067. uvs[i * 2] = options.uvs[i].x;
  43068. uvs[i * 2 + 1] = options.uvs[i].y;
  43069. }
  43070. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  43071. }
  43072. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  43073. var indices = instance.getIndices();
  43074. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43075. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  43076. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  43077. if (instance._closePath) {
  43078. var indexFirst = 0;
  43079. var indexLast = 0;
  43080. for (var p = 0; p < pathArray.length; p++) {
  43081. indexFirst = instance._idx[p] * 3;
  43082. if (p + 1 < pathArray.length) {
  43083. indexLast = (instance._idx[p + 1] - 1) * 3;
  43084. }
  43085. else {
  43086. indexLast = normals.length - 3;
  43087. }
  43088. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  43089. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  43090. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  43091. normals[indexLast] = normals[indexFirst];
  43092. normals[indexLast + 1] = normals[indexFirst + 1];
  43093. normals[indexLast + 2] = normals[indexFirst + 2];
  43094. }
  43095. }
  43096. if (!(instance.areNormalsFrozen)) {
  43097. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  43098. }
  43099. }
  43100. return instance;
  43101. }
  43102. else {
  43103. var ribbon = new BABYLON.Mesh(name, scene);
  43104. ribbon.sideOrientation = sideOrientation;
  43105. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  43106. if (closePath) {
  43107. ribbon._idx = vertexData._idx;
  43108. }
  43109. ribbon._closePath = closePath;
  43110. ribbon._closeArray = closeArray;
  43111. vertexData.applyToMesh(ribbon, updatable);
  43112. return ribbon;
  43113. }
  43114. };
  43115. /**
  43116. * Creates a cylinder or a cone mesh.
  43117. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  43118. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  43119. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  43120. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  43121. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  43122. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  43123. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  43124. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  43125. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  43126. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  43127. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  43128. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  43129. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  43130. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  43131. * If `enclose` is false, a ring surface is one element.
  43132. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  43133. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  43134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43135. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43138. */
  43139. MeshBuilder.CreateCylinder = function (name, options, scene) {
  43140. var cylinder = new BABYLON.Mesh(name, scene);
  43141. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43142. cylinder.sideOrientation = options.sideOrientation;
  43143. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  43144. vertexData.applyToMesh(cylinder, options.updatable);
  43145. return cylinder;
  43146. };
  43147. /**
  43148. * Creates a torus mesh.
  43149. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  43150. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  43151. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  43152. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  43153. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43154. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43155. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43157. */
  43158. MeshBuilder.CreateTorus = function (name, options, scene) {
  43159. var torus = new BABYLON.Mesh(name, scene);
  43160. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43161. torus.sideOrientation = options.sideOrientation;
  43162. var vertexData = BABYLON.VertexData.CreateTorus(options);
  43163. vertexData.applyToMesh(torus, options.updatable);
  43164. return torus;
  43165. };
  43166. /**
  43167. * Creates a torus knot mesh.
  43168. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  43169. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  43170. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  43171. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  43172. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  43173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43174. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43175. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43177. */
  43178. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  43179. var torusKnot = new BABYLON.Mesh(name, scene);
  43180. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43181. torusKnot.sideOrientation = options.sideOrientation;
  43182. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  43183. vertexData.applyToMesh(torusKnot, options.updatable);
  43184. return torusKnot;
  43185. };
  43186. /**
  43187. * Creates a line system mesh.
  43188. * A line system is a pool of many lines gathered in a single mesh.
  43189. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  43190. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  43191. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  43192. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  43193. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  43194. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  43195. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  43196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43197. */
  43198. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  43199. var instance = options.instance;
  43200. var lines = options.lines;
  43201. if (instance) {
  43202. var positionFunction = function (positions) {
  43203. var i = 0;
  43204. for (var l = 0; l < lines.length; l++) {
  43205. var points = lines[l];
  43206. for (var p = 0; p < points.length; p++) {
  43207. positions[i] = points[p].x;
  43208. positions[i + 1] = points[p].y;
  43209. positions[i + 2] = points[p].z;
  43210. i += 3;
  43211. }
  43212. }
  43213. };
  43214. instance.updateMeshPositions(positionFunction, false);
  43215. return instance;
  43216. }
  43217. // line system creation
  43218. var lineSystem = new BABYLON.LinesMesh(name, scene);
  43219. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  43220. vertexData.applyToMesh(lineSystem, options.updatable);
  43221. return lineSystem;
  43222. };
  43223. /**
  43224. * Creates a line mesh.
  43225. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  43226. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  43227. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43228. * The parameter `points` is an array successive Vector3.
  43229. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  43230. * When updating an instance, remember that only point positions can change, not the number of points.
  43231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43232. */
  43233. MeshBuilder.CreateLines = function (name, options, scene) {
  43234. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  43235. return lines;
  43236. };
  43237. /**
  43238. * Creates a dashed line mesh.
  43239. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  43240. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  43241. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43242. * The parameter `points` is an array successive Vector3.
  43243. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  43244. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  43245. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  43246. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  43247. * When updating an instance, remember that only point positions can change, not the number of points.
  43248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43249. */
  43250. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  43251. var points = options.points;
  43252. var instance = options.instance;
  43253. var gapSize = options.gapSize;
  43254. var dashNb = options.dashNb;
  43255. var dashSize = options.dashSize;
  43256. if (instance) {
  43257. var positionFunction = function (positions) {
  43258. var curvect = BABYLON.Vector3.Zero();
  43259. var nbSeg = positions.length / 6;
  43260. var lg = 0;
  43261. var nb = 0;
  43262. var shft = 0;
  43263. var dashshft = 0;
  43264. var curshft = 0;
  43265. var p = 0;
  43266. var i = 0;
  43267. var j = 0;
  43268. for (i = 0; i < points.length - 1; i++) {
  43269. points[i + 1].subtractToRef(points[i], curvect);
  43270. lg += curvect.length();
  43271. }
  43272. shft = lg / nbSeg;
  43273. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  43274. for (i = 0; i < points.length - 1; i++) {
  43275. points[i + 1].subtractToRef(points[i], curvect);
  43276. nb = Math.floor(curvect.length() / shft);
  43277. curvect.normalize();
  43278. j = 0;
  43279. while (j < nb && p < positions.length) {
  43280. curshft = shft * j;
  43281. positions[p] = points[i].x + curshft * curvect.x;
  43282. positions[p + 1] = points[i].y + curshft * curvect.y;
  43283. positions[p + 2] = points[i].z + curshft * curvect.z;
  43284. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  43285. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  43286. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  43287. p += 6;
  43288. j++;
  43289. }
  43290. }
  43291. while (p < positions.length) {
  43292. positions[p] = points[i].x;
  43293. positions[p + 1] = points[i].y;
  43294. positions[p + 2] = points[i].z;
  43295. p += 3;
  43296. }
  43297. };
  43298. instance.updateMeshPositions(positionFunction, false);
  43299. return instance;
  43300. }
  43301. // dashed lines creation
  43302. var dashedLines = new BABYLON.LinesMesh(name, scene);
  43303. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  43304. vertexData.applyToMesh(dashedLines, options.updatable);
  43305. dashedLines.dashSize = dashSize;
  43306. dashedLines.gapSize = gapSize;
  43307. return dashedLines;
  43308. };
  43309. /**
  43310. * Creates an extruded shape mesh.
  43311. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  43312. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  43313. *
  43314. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43315. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  43316. * extruded along the Z axis.
  43317. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43318. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  43319. * The parameter `scale` (float, default 1) is the value to scale the shape.
  43320. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  43321. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  43322. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43324. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43326. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43328. */
  43329. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  43330. var path = options.path;
  43331. var shape = options.shape;
  43332. var scale = options.scale || 1;
  43333. var rotation = options.rotation || 0;
  43334. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43335. var updatable = options.updatable;
  43336. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43337. var instance = options.instance;
  43338. var invertUV = options.invertUV || false;
  43339. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43340. };
  43341. /**
  43342. * Creates an custom extruded shape mesh.
  43343. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  43344. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  43345. *
  43346. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43347. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  43348. * extruded along the Z axis.
  43349. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43350. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  43351. * and the distance of this point from the begining of the path :
  43352. * ```javascript
  43353. * var rotationFunction = function(i, distance) {
  43354. * // do things
  43355. * return rotationValue; }
  43356. * ```
  43357. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  43358. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  43359. * and the distance of this point from the begining of the path :
  43360. * ```javascript
  43361. * var scaleFunction = function(i, distance) {
  43362. * // do things
  43363. * return scaleValue;}
  43364. * ```
  43365. * It must returns a float value that will be the scale value applied to the shape on each path point.
  43366. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  43367. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  43368. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  43369. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  43370. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43372. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43374. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43376. */
  43377. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  43378. var path = options.path;
  43379. var shape = options.shape;
  43380. var scaleFunction = options.scaleFunction || (function () { return 1; });
  43381. var rotationFunction = options.rotationFunction || (function () { return 0; });
  43382. var ribbonCloseArray = options.ribbonCloseArray || false;
  43383. var ribbonClosePath = options.ribbonClosePath || false;
  43384. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43385. var updatable = options.updatable;
  43386. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43387. var instance = options.instance;
  43388. var invertUV = options.invertUV || false;
  43389. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43390. };
  43391. /**
  43392. * Creates lathe mesh.
  43393. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  43394. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  43395. *
  43396. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  43397. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  43398. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  43399. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  43400. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  43401. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  43402. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  43403. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43404. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43405. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43406. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43407. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43408. */
  43409. MeshBuilder.CreateLathe = function (name, options, scene) {
  43410. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  43411. var closed = (options.closed === undefined) ? true : options.closed;
  43412. var shape = options.shape;
  43413. var radius = options.radius || 1;
  43414. var tessellation = options.tessellation || 64;
  43415. var updatable = options.updatable;
  43416. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43417. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  43418. var pi2 = Math.PI * 2;
  43419. var paths = new Array();
  43420. var invertUV = options.invertUV || false;
  43421. var i = 0;
  43422. var p = 0;
  43423. var step = pi2 / tessellation * arc;
  43424. var rotated;
  43425. var path = new Array();
  43426. ;
  43427. for (i = 0; i <= tessellation; i++) {
  43428. var path = [];
  43429. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  43430. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  43431. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  43432. }
  43433. for (p = 0; p < shape.length; p++) {
  43434. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  43435. path.push(rotated);
  43436. }
  43437. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  43438. 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));
  43439. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  43440. }
  43441. paths.push(path);
  43442. }
  43443. // lathe ribbon
  43444. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43445. return lathe;
  43446. };
  43447. /**
  43448. * Creates a plane mesh.
  43449. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43450. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  43451. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  43452. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  43453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43454. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43455. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43457. */
  43458. MeshBuilder.CreatePlane = function (name, options, scene) {
  43459. var plane = new BABYLON.Mesh(name, scene);
  43460. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43461. plane.sideOrientation = options.sideOrientation;
  43462. var vertexData = BABYLON.VertexData.CreatePlane(options);
  43463. vertexData.applyToMesh(plane, options.updatable);
  43464. if (options.sourcePlane) {
  43465. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  43466. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  43467. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  43468. plane.rotate(vectorProduct, product);
  43469. }
  43470. return plane;
  43471. };
  43472. /**
  43473. * Creates a ground mesh.
  43474. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43475. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  43476. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  43477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43478. */
  43479. MeshBuilder.CreateGround = function (name, options, scene) {
  43480. var ground = new BABYLON.GroundMesh(name, scene);
  43481. ground._setReady(false);
  43482. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  43483. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  43484. ground._width = options.width || 1;
  43485. ground._height = options.height || 1;
  43486. ground._maxX = ground._width / 2;
  43487. ground._maxZ = ground._height / 2;
  43488. ground._minX = -ground._maxX;
  43489. ground._minZ = -ground._maxZ;
  43490. var vertexData = BABYLON.VertexData.CreateGround(options);
  43491. vertexData.applyToMesh(ground, options.updatable);
  43492. ground._setReady(true);
  43493. return ground;
  43494. };
  43495. /**
  43496. * Creates a tiled ground mesh.
  43497. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  43498. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  43499. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  43500. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  43501. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  43502. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  43503. * numbers of subdivisions on the ground width and height of each tile.
  43504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43505. */
  43506. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  43507. var tiledGround = new BABYLON.Mesh(name, scene);
  43508. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  43509. vertexData.applyToMesh(tiledGround, options.updatable);
  43510. return tiledGround;
  43511. };
  43512. /**
  43513. * Creates a ground mesh from a height map.
  43514. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  43515. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  43516. * The parameter `url` sets the URL of the height map image resource.
  43517. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  43518. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  43519. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  43520. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  43521. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  43522. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  43523. * This function is passed the newly built mesh :
  43524. * ```javascript
  43525. * function(mesh) { // do things
  43526. * return; }
  43527. * ```
  43528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43529. */
  43530. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  43531. var width = options.width || 10.0;
  43532. var height = options.height || 10.0;
  43533. var subdivisions = options.subdivisions || 1 | 0;
  43534. var minHeight = options.minHeight || 0.0;
  43535. var maxHeight = options.maxHeight || 10.0;
  43536. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  43537. var updatable = options.updatable;
  43538. var onReady = options.onReady;
  43539. var ground = new BABYLON.GroundMesh(name, scene);
  43540. ground._subdivisionsX = subdivisions;
  43541. ground._subdivisionsY = subdivisions;
  43542. ground._width = width;
  43543. ground._height = height;
  43544. ground._maxX = ground._width / 2.0;
  43545. ground._maxZ = ground._height / 2.0;
  43546. ground._minX = -ground._maxX;
  43547. ground._minZ = -ground._maxZ;
  43548. ground._setReady(false);
  43549. var onload = function (img) {
  43550. // Getting height map data
  43551. var canvas = document.createElement("canvas");
  43552. var context = canvas.getContext("2d");
  43553. var bufferWidth = img.width;
  43554. var bufferHeight = img.height;
  43555. canvas.width = bufferWidth;
  43556. canvas.height = bufferHeight;
  43557. context.drawImage(img, 0, 0);
  43558. // Create VertexData from map data
  43559. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  43560. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  43561. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  43562. width: width, height: height,
  43563. subdivisions: subdivisions,
  43564. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  43565. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  43566. });
  43567. vertexData.applyToMesh(ground, updatable);
  43568. ground._setReady(true);
  43569. //execute ready callback, if set
  43570. if (onReady) {
  43571. onReady(ground);
  43572. }
  43573. };
  43574. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  43575. return ground;
  43576. };
  43577. /**
  43578. * Creates a polygon mesh.
  43579. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  43580. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  43581. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43583. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43584. * Remember you can only change the shape positions, not their number when updating a polygon.
  43585. */
  43586. MeshBuilder.CreatePolygon = function (name, options, scene) {
  43587. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43588. var shape = options.shape;
  43589. var holes = options.holes || [];
  43590. var depth = options.depth || 0;
  43591. var contours = [];
  43592. var hole = [];
  43593. for (var i = 0; i < shape.length; i++) {
  43594. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  43595. }
  43596. var epsilon = 0.00000001;
  43597. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  43598. contours.pop();
  43599. }
  43600. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  43601. for (var hNb = 0; hNb < holes.length; hNb++) {
  43602. hole = [];
  43603. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  43604. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  43605. }
  43606. polygonTriangulation.addHole(hole);
  43607. }
  43608. var polygon = polygonTriangulation.build(options.updatable, depth);
  43609. polygon.sideOrientation = options.sideOrientation;
  43610. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  43611. vertexData.applyToMesh(polygon, options.updatable);
  43612. return polygon;
  43613. };
  43614. ;
  43615. /**
  43616. * Creates an extruded polygon mesh, with depth in the Y direction.
  43617. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements).
  43618. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43619. */
  43620. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  43621. return MeshBuilder.CreatePolygon(name, options, scene);
  43622. };
  43623. ;
  43624. /**
  43625. * Creates a tube mesh.
  43626. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  43627. *
  43628. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  43629. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  43630. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  43631. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  43632. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  43633. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  43634. * It must return a radius value (positive float) :
  43635. * ```javascript
  43636. * var radiusFunction = function(i, distance) {
  43637. * // do things
  43638. * return radius; }
  43639. * ```
  43640. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  43641. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  43642. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  43643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43644. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43646. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43648. */
  43649. MeshBuilder.CreateTube = function (name, options, scene) {
  43650. var path = options.path;
  43651. var radius = options.radius || 1.0;
  43652. var tessellation = options.tessellation || 64 | 0;
  43653. var radiusFunction = options.radiusFunction;
  43654. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  43655. var invertUV = options.invertUV || false;
  43656. var updatable = options.updatable;
  43657. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43658. var instance = options.instance;
  43659. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  43660. // tube geometry
  43661. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  43662. var tangents = path3D.getTangents();
  43663. var normals = path3D.getNormals();
  43664. var distances = path3D.getDistances();
  43665. var pi2 = Math.PI * 2;
  43666. var step = pi2 / tessellation * arc;
  43667. var returnRadius = function () { return radius; };
  43668. var radiusFunctionFinal = radiusFunction || returnRadius;
  43669. var circlePath;
  43670. var rad;
  43671. var normal;
  43672. var rotated;
  43673. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43674. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43675. for (var i = 0; i < path.length; i++) {
  43676. rad = radiusFunctionFinal(i, distances[i]); // current radius
  43677. circlePath = Array(); // current circle array
  43678. normal = normals[i]; // current normal
  43679. for (var t = 0; t < tessellation; t++) {
  43680. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  43681. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  43682. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  43683. rotated.scaleInPlace(rad).addInPlace(path[i]);
  43684. circlePath[t] = rotated;
  43685. }
  43686. circlePaths[index] = circlePath;
  43687. index++;
  43688. }
  43689. // cap
  43690. var capPath = function (nbPoints, pathIndex) {
  43691. var pointCap = Array();
  43692. for (var i = 0; i < nbPoints; i++) {
  43693. pointCap.push(path[pathIndex]);
  43694. }
  43695. return pointCap;
  43696. };
  43697. switch (cap) {
  43698. case BABYLON.Mesh.NO_CAP:
  43699. break;
  43700. case BABYLON.Mesh.CAP_START:
  43701. circlePaths[0] = capPath(tessellation, 0);
  43702. circlePaths[1] = circlePaths[2].slice(0);
  43703. break;
  43704. case BABYLON.Mesh.CAP_END:
  43705. circlePaths[index] = circlePaths[index - 1].slice(0);
  43706. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43707. break;
  43708. case BABYLON.Mesh.CAP_ALL:
  43709. circlePaths[0] = capPath(tessellation, 0);
  43710. circlePaths[1] = circlePaths[2].slice(0);
  43711. circlePaths[index] = circlePaths[index - 1].slice(0);
  43712. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43713. break;
  43714. default:
  43715. break;
  43716. }
  43717. return circlePaths;
  43718. };
  43719. var path3D;
  43720. var pathArray;
  43721. if (instance) {
  43722. var arc = options.arc || instance.arc;
  43723. path3D = (instance.path3D).update(path);
  43724. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  43725. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  43726. instance.path3D = path3D;
  43727. instance.pathArray = pathArray;
  43728. instance.arc = arc;
  43729. return instance;
  43730. }
  43731. // tube creation
  43732. path3D = new BABYLON.Path3D(path);
  43733. var newPathArray = new Array();
  43734. cap = (cap < 0 || cap > 3) ? 0 : cap;
  43735. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  43736. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43737. tube.pathArray = pathArray;
  43738. tube.path3D = path3D;
  43739. tube.tessellation = tessellation;
  43740. tube.cap = cap;
  43741. tube.arc = options.arc;
  43742. return tube;
  43743. };
  43744. /**
  43745. * Creates a polyhedron mesh.
  43746. *
  43747. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  43748. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  43749. * to choose the wanted type.
  43750. * The parameter `size` (positive float, default 1) sets the polygon size.
  43751. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  43752. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  43753. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  43754. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  43755. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43756. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  43757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43758. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43761. */
  43762. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  43763. var polyhedron = new BABYLON.Mesh(name, scene);
  43764. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43765. polyhedron.sideOrientation = options.sideOrientation;
  43766. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  43767. vertexData.applyToMesh(polyhedron, options.updatable);
  43768. return polyhedron;
  43769. };
  43770. /**
  43771. * Creates a decal mesh.
  43772. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  43773. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  43774. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  43775. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  43776. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  43777. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  43778. */
  43779. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  43780. var indices = sourceMesh.getIndices();
  43781. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43782. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43783. var position = options.position || BABYLON.Vector3.Zero();
  43784. var normal = options.normal || BABYLON.Vector3.Up();
  43785. var size = options.size || BABYLON.Vector3.One();
  43786. var angle = options.angle || 0;
  43787. // Getting correct rotation
  43788. if (!normal) {
  43789. var target = new BABYLON.Vector3(0, 0, 1);
  43790. var camera = sourceMesh.getScene().activeCamera;
  43791. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  43792. normal = camera.globalPosition.subtract(cameraWorldTarget);
  43793. }
  43794. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  43795. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  43796. var pitch = Math.atan2(normal.y, len);
  43797. // Matrix
  43798. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  43799. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  43800. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  43801. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  43802. var vertexData = new BABYLON.VertexData();
  43803. vertexData.indices = [];
  43804. vertexData.positions = [];
  43805. vertexData.normals = [];
  43806. vertexData.uvs = [];
  43807. var currentVertexDataIndex = 0;
  43808. var extractDecalVector3 = function (indexId) {
  43809. var vertexId = indices[indexId];
  43810. var result = new BABYLON.PositionNormalVertex();
  43811. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  43812. // Send vector to decal local world
  43813. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  43814. // Get normal
  43815. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  43816. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  43817. return result;
  43818. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  43819. var clip = function (vertices, axis) {
  43820. if (vertices.length === 0) {
  43821. return vertices;
  43822. }
  43823. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  43824. var clipVertices = function (v0, v1) {
  43825. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  43826. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  43827. };
  43828. var result = new Array();
  43829. for (var index = 0; index < vertices.length; index += 3) {
  43830. var v1Out;
  43831. var v2Out;
  43832. var v3Out;
  43833. var total = 0;
  43834. var nV1, nV2, nV3, nV4;
  43835. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  43836. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  43837. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  43838. v1Out = d1 > 0;
  43839. v2Out = d2 > 0;
  43840. v3Out = d3 > 0;
  43841. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  43842. switch (total) {
  43843. case 0:
  43844. result.push(vertices[index]);
  43845. result.push(vertices[index + 1]);
  43846. result.push(vertices[index + 2]);
  43847. break;
  43848. case 1:
  43849. if (v1Out) {
  43850. nV1 = vertices[index + 1];
  43851. nV2 = vertices[index + 2];
  43852. nV3 = clipVertices(vertices[index], nV1);
  43853. nV4 = clipVertices(vertices[index], nV2);
  43854. }
  43855. if (v2Out) {
  43856. nV1 = vertices[index];
  43857. nV2 = vertices[index + 2];
  43858. nV3 = clipVertices(vertices[index + 1], nV1);
  43859. nV4 = clipVertices(vertices[index + 1], nV2);
  43860. result.push(nV3);
  43861. result.push(nV2.clone());
  43862. result.push(nV1.clone());
  43863. result.push(nV2.clone());
  43864. result.push(nV3.clone());
  43865. result.push(nV4);
  43866. break;
  43867. }
  43868. if (v3Out) {
  43869. nV1 = vertices[index];
  43870. nV2 = vertices[index + 1];
  43871. nV3 = clipVertices(vertices[index + 2], nV1);
  43872. nV4 = clipVertices(vertices[index + 2], nV2);
  43873. }
  43874. result.push(nV1.clone());
  43875. result.push(nV2.clone());
  43876. result.push(nV3);
  43877. result.push(nV4);
  43878. result.push(nV3.clone());
  43879. result.push(nV2.clone());
  43880. break;
  43881. case 2:
  43882. if (!v1Out) {
  43883. nV1 = vertices[index].clone();
  43884. nV2 = clipVertices(nV1, vertices[index + 1]);
  43885. nV3 = clipVertices(nV1, vertices[index + 2]);
  43886. result.push(nV1);
  43887. result.push(nV2);
  43888. result.push(nV3);
  43889. }
  43890. if (!v2Out) {
  43891. nV1 = vertices[index + 1].clone();
  43892. nV2 = clipVertices(nV1, vertices[index + 2]);
  43893. nV3 = clipVertices(nV1, vertices[index]);
  43894. result.push(nV1);
  43895. result.push(nV2);
  43896. result.push(nV3);
  43897. }
  43898. if (!v3Out) {
  43899. nV1 = vertices[index + 2].clone();
  43900. nV2 = clipVertices(nV1, vertices[index]);
  43901. nV3 = clipVertices(nV1, vertices[index + 1]);
  43902. result.push(nV1);
  43903. result.push(nV2);
  43904. result.push(nV3);
  43905. }
  43906. break;
  43907. case 3:
  43908. break;
  43909. }
  43910. }
  43911. return result;
  43912. };
  43913. for (var index = 0; index < indices.length; index += 3) {
  43914. var faceVertices = new Array();
  43915. faceVertices.push(extractDecalVector3(index));
  43916. faceVertices.push(extractDecalVector3(index + 1));
  43917. faceVertices.push(extractDecalVector3(index + 2));
  43918. // Clip
  43919. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  43920. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  43921. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  43922. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  43923. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  43924. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  43925. if (faceVertices.length === 0) {
  43926. continue;
  43927. }
  43928. // Add UVs and get back to world
  43929. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  43930. var vertex = faceVertices[vIndex];
  43931. //TODO check for Int32Array | Uint32Array | Uint16Array
  43932. vertexData.indices.push(currentVertexDataIndex);
  43933. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  43934. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  43935. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  43936. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  43937. currentVertexDataIndex++;
  43938. }
  43939. }
  43940. // Return mesh
  43941. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  43942. vertexData.applyToMesh(decal);
  43943. decal.position = position.clone();
  43944. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  43945. return decal;
  43946. };
  43947. // Privates
  43948. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  43949. // extrusion geometry
  43950. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  43951. var tangents = path3D.getTangents();
  43952. var normals = path3D.getNormals();
  43953. var binormals = path3D.getBinormals();
  43954. var distances = path3D.getDistances();
  43955. var angle = 0;
  43956. var returnScale = function () { return scale; };
  43957. var returnRotation = function () { return rotation; };
  43958. var rotate = custom ? rotateFunction : returnRotation;
  43959. var scl = custom ? scaleFunction : returnScale;
  43960. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43961. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43962. for (var i = 0; i < curve.length; i++) {
  43963. var shapePath = new Array();
  43964. var angleStep = rotate(i, distances[i]);
  43965. var scaleRatio = scl(i, distances[i]);
  43966. for (var p = 0; p < shape.length; p++) {
  43967. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  43968. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  43969. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  43970. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  43971. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  43972. shapePath[p] = rotated;
  43973. }
  43974. shapePaths[index] = shapePath;
  43975. angle += angleStep;
  43976. index++;
  43977. }
  43978. // cap
  43979. var capPath = function (shapePath) {
  43980. var pointCap = Array();
  43981. var barycenter = BABYLON.Vector3.Zero();
  43982. var i;
  43983. for (i = 0; i < shapePath.length; i++) {
  43984. barycenter.addInPlace(shapePath[i]);
  43985. }
  43986. barycenter.scaleInPlace(1.0 / shapePath.length);
  43987. for (i = 0; i < shapePath.length; i++) {
  43988. pointCap.push(barycenter);
  43989. }
  43990. return pointCap;
  43991. };
  43992. switch (cap) {
  43993. case BABYLON.Mesh.NO_CAP:
  43994. break;
  43995. case BABYLON.Mesh.CAP_START:
  43996. shapePaths[0] = capPath(shapePaths[2]);
  43997. shapePaths[1] = shapePaths[2];
  43998. break;
  43999. case BABYLON.Mesh.CAP_END:
  44000. shapePaths[index] = shapePaths[index - 1];
  44001. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44002. break;
  44003. case BABYLON.Mesh.CAP_ALL:
  44004. shapePaths[0] = capPath(shapePaths[2]);
  44005. shapePaths[1] = shapePaths[2];
  44006. shapePaths[index] = shapePaths[index - 1];
  44007. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44008. break;
  44009. default:
  44010. break;
  44011. }
  44012. return shapePaths;
  44013. };
  44014. var path3D;
  44015. var pathArray;
  44016. if (instance) {
  44017. path3D = (instance.path3D).update(curve);
  44018. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  44019. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  44020. return instance;
  44021. }
  44022. // extruded shape creation
  44023. path3D = new BABYLON.Path3D(curve);
  44024. var newShapePaths = new Array();
  44025. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44026. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  44027. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  44028. extrudedGeneric.pathArray = pathArray;
  44029. extrudedGeneric.path3D = path3D;
  44030. extrudedGeneric.cap = cap;
  44031. return extrudedGeneric;
  44032. };
  44033. return MeshBuilder;
  44034. }());
  44035. BABYLON.MeshBuilder = MeshBuilder;
  44036. })(BABYLON || (BABYLON = {}));
  44037. //# sourceMappingURL=babylon.meshBuilder.js.map
  44038. var BABYLON;
  44039. (function (BABYLON) {
  44040. var AudioEngine = (function () {
  44041. function AudioEngine() {
  44042. this._audioContext = null;
  44043. this._audioContextInitialized = false;
  44044. this.canUseWebAudio = false;
  44045. this.WarnedWebAudioUnsupported = false;
  44046. this.unlocked = false;
  44047. this.isMP3supported = false;
  44048. this.isOGGsupported = false;
  44049. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  44050. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  44051. this.canUseWebAudio = true;
  44052. }
  44053. var audioElem = document.createElement('audio');
  44054. try {
  44055. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  44056. this.isMP3supported = true;
  44057. }
  44058. }
  44059. catch (e) {
  44060. // protect error during capability check.
  44061. }
  44062. try {
  44063. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  44064. this.isOGGsupported = true;
  44065. }
  44066. }
  44067. catch (e) {
  44068. // protect error during capability check.
  44069. }
  44070. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  44071. this._unlockiOSaudio();
  44072. }
  44073. else {
  44074. this.unlocked = true;
  44075. }
  44076. }
  44077. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44078. get: function () {
  44079. if (!this._audioContextInitialized) {
  44080. this._initializeAudioContext();
  44081. }
  44082. return this._audioContext;
  44083. },
  44084. enumerable: true,
  44085. configurable: true
  44086. });
  44087. AudioEngine.prototype._unlockiOSaudio = function () {
  44088. var _this = this;
  44089. var unlockaudio = function () {
  44090. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44091. var source = _this.audioContext.createBufferSource();
  44092. source.buffer = buffer;
  44093. source.connect(_this.audioContext.destination);
  44094. source.start(0);
  44095. setTimeout(function () {
  44096. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44097. _this.unlocked = true;
  44098. window.removeEventListener('touchend', unlockaudio, false);
  44099. if (_this.onAudioUnlocked) {
  44100. _this.onAudioUnlocked();
  44101. }
  44102. }
  44103. }, 0);
  44104. };
  44105. window.addEventListener('touchend', unlockaudio, false);
  44106. };
  44107. AudioEngine.prototype._initializeAudioContext = function () {
  44108. try {
  44109. if (this.canUseWebAudio) {
  44110. this._audioContext = new AudioContext();
  44111. // create a global volume gain node
  44112. this.masterGain = this._audioContext.createGain();
  44113. this.masterGain.gain.value = 1;
  44114. this.masterGain.connect(this._audioContext.destination);
  44115. this._audioContextInitialized = true;
  44116. }
  44117. }
  44118. catch (e) {
  44119. this.canUseWebAudio = false;
  44120. BABYLON.Tools.Error("Web Audio: " + e.message);
  44121. }
  44122. };
  44123. AudioEngine.prototype.dispose = function () {
  44124. if (this.canUseWebAudio && this._audioContextInitialized) {
  44125. if (this._connectedAnalyser) {
  44126. this._connectedAnalyser.stopDebugCanvas();
  44127. this._connectedAnalyser.dispose();
  44128. this.masterGain.disconnect();
  44129. this.masterGain.connect(this._audioContext.destination);
  44130. this._connectedAnalyser = null;
  44131. }
  44132. this.masterGain.gain.value = 1;
  44133. }
  44134. this.WarnedWebAudioUnsupported = false;
  44135. };
  44136. AudioEngine.prototype.getGlobalVolume = function () {
  44137. if (this.canUseWebAudio && this._audioContextInitialized) {
  44138. return this.masterGain.gain.value;
  44139. }
  44140. else {
  44141. return -1;
  44142. }
  44143. };
  44144. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  44145. if (this.canUseWebAudio && this._audioContextInitialized) {
  44146. this.masterGain.gain.value = newVolume;
  44147. }
  44148. };
  44149. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  44150. if (this._connectedAnalyser) {
  44151. this._connectedAnalyser.stopDebugCanvas();
  44152. }
  44153. if (this.canUseWebAudio && this._audioContextInitialized) {
  44154. this._connectedAnalyser = analyser;
  44155. this.masterGain.disconnect();
  44156. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  44157. }
  44158. };
  44159. return AudioEngine;
  44160. }());
  44161. BABYLON.AudioEngine = AudioEngine;
  44162. })(BABYLON || (BABYLON = {}));
  44163. //# sourceMappingURL=babylon.audioEngine.js.map
  44164. var BABYLON;
  44165. (function (BABYLON) {
  44166. var Sound = (function () {
  44167. /**
  44168. * Create a sound and attach it to a scene
  44169. * @param name Name of your sound
  44170. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  44171. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  44172. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  44173. */
  44174. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  44175. var _this = this;
  44176. this.autoplay = false;
  44177. this.loop = false;
  44178. this.useCustomAttenuation = false;
  44179. this.spatialSound = false;
  44180. this.refDistance = 1;
  44181. this.rolloffFactor = 1;
  44182. this.maxDistance = 100;
  44183. this.distanceModel = "linear";
  44184. this._panningModel = "equalpower";
  44185. this._playbackRate = 1;
  44186. this._streaming = false;
  44187. this._startTime = 0;
  44188. this._startOffset = 0;
  44189. this._position = BABYLON.Vector3.Zero();
  44190. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  44191. this._volume = 1;
  44192. this._isLoaded = false;
  44193. this._isReadyToPlay = false;
  44194. this.isPlaying = false;
  44195. this.isPaused = false;
  44196. this._isDirectional = false;
  44197. // Used if you'd like to create a directional sound.
  44198. // If not set, the sound will be omnidirectional
  44199. this._coneInnerAngle = 360;
  44200. this._coneOuterAngle = 360;
  44201. this._coneOuterGain = 0;
  44202. this._isOutputConnected = false;
  44203. this._urlType = "Unknown";
  44204. this.name = name;
  44205. this._scene = scene;
  44206. this._readyToPlayCallback = readyToPlayCallback;
  44207. // Default custom attenuation function is a linear attenuation
  44208. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  44209. if (currentDistance < maxDistance) {
  44210. return currentVolume * (1 - currentDistance / maxDistance);
  44211. }
  44212. else {
  44213. return 0;
  44214. }
  44215. };
  44216. if (options) {
  44217. this.autoplay = options.autoplay || false;
  44218. this.loop = options.loop || false;
  44219. // if volume === 0, we need another way to check this option
  44220. if (options.volume !== undefined) {
  44221. this._volume = options.volume;
  44222. }
  44223. this.spatialSound = options.spatialSound || false;
  44224. this.maxDistance = options.maxDistance || 100;
  44225. this.useCustomAttenuation = options.useCustomAttenuation || false;
  44226. this.rolloffFactor = options.rolloffFactor || 1;
  44227. this.refDistance = options.refDistance || 1;
  44228. this.distanceModel = options.distanceModel || "linear";
  44229. this._playbackRate = options.playbackRate || 1;
  44230. this._streaming = options.streaming || false;
  44231. }
  44232. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44233. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  44234. this._soundGain.gain.value = this._volume;
  44235. this._inputAudioNode = this._soundGain;
  44236. this._ouputAudioNode = this._soundGain;
  44237. if (this.spatialSound) {
  44238. this._createSpatialParameters();
  44239. }
  44240. this._scene.mainSoundTrack.AddSound(this);
  44241. var validParameter = true;
  44242. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  44243. if (urlOrArrayBuffer) {
  44244. if (typeof (urlOrArrayBuffer) === "string")
  44245. this._urlType = "String";
  44246. if (Array.isArray(urlOrArrayBuffer))
  44247. this._urlType = "Array";
  44248. if (urlOrArrayBuffer instanceof ArrayBuffer)
  44249. this._urlType = "ArrayBuffer";
  44250. var urls = [];
  44251. var codecSupportedFound = false;
  44252. switch (this._urlType) {
  44253. case "ArrayBuffer":
  44254. if (urlOrArrayBuffer.byteLength > 0) {
  44255. codecSupportedFound = true;
  44256. this._soundLoaded(urlOrArrayBuffer);
  44257. }
  44258. break;
  44259. case "String":
  44260. urls.push(urlOrArrayBuffer);
  44261. case "Array":
  44262. if (urls.length === 0)
  44263. urls = urlOrArrayBuffer;
  44264. // If we found a supported format, we load it immediately and stop the loop
  44265. for (var i = 0; i < urls.length; i++) {
  44266. var url = urls[i];
  44267. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  44268. codecSupportedFound = true;
  44269. }
  44270. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  44271. codecSupportedFound = true;
  44272. }
  44273. if (url.indexOf(".wav", url.length - 4) !== -1) {
  44274. codecSupportedFound = true;
  44275. }
  44276. if (url.indexOf("blob:") !== -1) {
  44277. codecSupportedFound = true;
  44278. }
  44279. if (codecSupportedFound) {
  44280. // Loading sound using XHR2
  44281. if (!this._streaming) {
  44282. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  44283. }
  44284. else {
  44285. this._htmlAudioElement = new Audio(url);
  44286. this._htmlAudioElement.controls = false;
  44287. this._htmlAudioElement.loop = this.loop;
  44288. this._htmlAudioElement.crossOrigin = "anonymous";
  44289. this._htmlAudioElement.preload = "auto";
  44290. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  44291. _this._isReadyToPlay = true;
  44292. if (_this.autoplay) {
  44293. _this.play();
  44294. }
  44295. if (_this._readyToPlayCallback) {
  44296. _this._readyToPlayCallback();
  44297. }
  44298. });
  44299. document.body.appendChild(this._htmlAudioElement);
  44300. }
  44301. break;
  44302. }
  44303. }
  44304. break;
  44305. default:
  44306. validParameter = false;
  44307. break;
  44308. }
  44309. if (!validParameter) {
  44310. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  44311. }
  44312. else {
  44313. if (!codecSupportedFound) {
  44314. this._isReadyToPlay = true;
  44315. // Simulating a ready to play event to avoid breaking code path
  44316. if (this._readyToPlayCallback) {
  44317. window.setTimeout(function () {
  44318. _this._readyToPlayCallback();
  44319. }, 1000);
  44320. }
  44321. }
  44322. }
  44323. }
  44324. }
  44325. else {
  44326. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  44327. this._scene.mainSoundTrack.AddSound(this);
  44328. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  44329. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  44330. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  44331. }
  44332. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  44333. if (this._readyToPlayCallback) {
  44334. window.setTimeout(function () {
  44335. _this._readyToPlayCallback();
  44336. }, 1000);
  44337. }
  44338. }
  44339. }
  44340. Sound.prototype.dispose = function () {
  44341. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  44342. if (this.isPlaying) {
  44343. this.stop();
  44344. }
  44345. this._isReadyToPlay = false;
  44346. if (this.soundTrackId === -1) {
  44347. this._scene.mainSoundTrack.RemoveSound(this);
  44348. }
  44349. else {
  44350. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  44351. }
  44352. if (this._soundGain) {
  44353. this._soundGain.disconnect();
  44354. this._soundGain = null;
  44355. }
  44356. if (this._soundPanner) {
  44357. this._soundPanner.disconnect();
  44358. this._soundPanner = null;
  44359. }
  44360. if (this._soundSource) {
  44361. this._soundSource.disconnect();
  44362. this._soundSource = null;
  44363. }
  44364. this._audioBuffer = null;
  44365. if (this._htmlAudioElement) {
  44366. this._htmlAudioElement.pause();
  44367. this._htmlAudioElement.src = "";
  44368. document.body.removeChild(this._htmlAudioElement);
  44369. }
  44370. if (this._connectedMesh) {
  44371. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44372. this._connectedMesh = null;
  44373. }
  44374. }
  44375. };
  44376. Sound.prototype.isReady = function () {
  44377. return this._isReadyToPlay;
  44378. };
  44379. Sound.prototype._soundLoaded = function (audioData) {
  44380. var _this = this;
  44381. this._isLoaded = true;
  44382. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  44383. _this._audioBuffer = buffer;
  44384. _this._isReadyToPlay = true;
  44385. if (_this.autoplay) {
  44386. _this.play();
  44387. }
  44388. if (_this._readyToPlayCallback) {
  44389. _this._readyToPlayCallback();
  44390. }
  44391. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  44392. };
  44393. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  44394. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44395. this._audioBuffer = audioBuffer;
  44396. this._isReadyToPlay = true;
  44397. }
  44398. };
  44399. Sound.prototype.updateOptions = function (options) {
  44400. if (options) {
  44401. this.loop = options.loop || this.loop;
  44402. this.maxDistance = options.maxDistance || this.maxDistance;
  44403. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  44404. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  44405. this.refDistance = options.refDistance || this.refDistance;
  44406. this.distanceModel = options.distanceModel || this.distanceModel;
  44407. this._playbackRate = options.playbackRate || this._playbackRate;
  44408. this._updateSpatialParameters();
  44409. if (this.isPlaying) {
  44410. if (this._streaming) {
  44411. this._htmlAudioElement.playbackRate = this._playbackRate;
  44412. }
  44413. else {
  44414. this._soundSource.playbackRate.value = this._playbackRate;
  44415. }
  44416. }
  44417. }
  44418. };
  44419. Sound.prototype._createSpatialParameters = function () {
  44420. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44421. if (this._scene.headphone) {
  44422. this._panningModel = "HRTF";
  44423. }
  44424. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  44425. this._updateSpatialParameters();
  44426. this._soundPanner.connect(this._ouputAudioNode);
  44427. this._inputAudioNode = this._soundPanner;
  44428. }
  44429. };
  44430. Sound.prototype._updateSpatialParameters = function () {
  44431. if (this.spatialSound) {
  44432. if (this.useCustomAttenuation) {
  44433. // Tricks to disable in a way embedded Web Audio attenuation
  44434. this._soundPanner.distanceModel = "linear";
  44435. this._soundPanner.maxDistance = Number.MAX_VALUE;
  44436. this._soundPanner.refDistance = 1;
  44437. this._soundPanner.rolloffFactor = 1;
  44438. this._soundPanner.panningModel = this._panningModel;
  44439. }
  44440. else {
  44441. this._soundPanner.distanceModel = this.distanceModel;
  44442. this._soundPanner.maxDistance = this.maxDistance;
  44443. this._soundPanner.refDistance = this.refDistance;
  44444. this._soundPanner.rolloffFactor = this.rolloffFactor;
  44445. this._soundPanner.panningModel = this._panningModel;
  44446. }
  44447. }
  44448. };
  44449. Sound.prototype.switchPanningModelToHRTF = function () {
  44450. this._panningModel = "HRTF";
  44451. this._switchPanningModel();
  44452. };
  44453. Sound.prototype.switchPanningModelToEqualPower = function () {
  44454. this._panningModel = "equalpower";
  44455. this._switchPanningModel();
  44456. };
  44457. Sound.prototype._switchPanningModel = function () {
  44458. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44459. this._soundPanner.panningModel = this._panningModel;
  44460. }
  44461. };
  44462. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  44463. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44464. if (this._isOutputConnected) {
  44465. this._ouputAudioNode.disconnect();
  44466. }
  44467. this._ouputAudioNode.connect(soundTrackAudioNode);
  44468. this._isOutputConnected = true;
  44469. }
  44470. };
  44471. /**
  44472. * Transform this sound into a directional source
  44473. * @param coneInnerAngle Size of the inner cone in degree
  44474. * @param coneOuterAngle Size of the outer cone in degree
  44475. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  44476. */
  44477. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  44478. if (coneOuterAngle < coneInnerAngle) {
  44479. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  44480. return;
  44481. }
  44482. this._coneInnerAngle = coneInnerAngle;
  44483. this._coneOuterAngle = coneOuterAngle;
  44484. this._coneOuterGain = coneOuterGain;
  44485. this._isDirectional = true;
  44486. if (this.isPlaying && this.loop) {
  44487. this.stop();
  44488. this.play();
  44489. }
  44490. };
  44491. Sound.prototype.setPosition = function (newPosition) {
  44492. this._position = newPosition;
  44493. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44494. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44495. }
  44496. };
  44497. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  44498. this._localDirection = newLocalDirection;
  44499. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  44500. this._updateDirection();
  44501. }
  44502. };
  44503. Sound.prototype._updateDirection = function () {
  44504. var mat = this._connectedMesh.getWorldMatrix();
  44505. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  44506. direction.normalize();
  44507. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  44508. };
  44509. Sound.prototype.updateDistanceFromListener = function () {
  44510. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  44511. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  44512. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  44513. }
  44514. };
  44515. Sound.prototype.setAttenuationFunction = function (callback) {
  44516. this._customAttenuationFunction = callback;
  44517. };
  44518. /**
  44519. * Play the sound
  44520. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  44521. * @param offset (optional) Start the sound setting it at a specific time
  44522. */
  44523. Sound.prototype.play = function (time, offset) {
  44524. var _this = this;
  44525. if (this._isReadyToPlay && this._scene.audioEnabled) {
  44526. try {
  44527. if (this._startOffset < 0) {
  44528. time = -this._startOffset;
  44529. this._startOffset = 0;
  44530. }
  44531. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44532. if (!this._soundSource || !this._streamingSource) {
  44533. if (this.spatialSound) {
  44534. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44535. if (this._isDirectional) {
  44536. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  44537. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  44538. this._soundPanner.coneOuterGain = this._coneOuterGain;
  44539. if (this._connectedMesh) {
  44540. this._updateDirection();
  44541. }
  44542. else {
  44543. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  44544. }
  44545. }
  44546. }
  44547. }
  44548. if (this._streaming) {
  44549. if (!this._streamingSource) {
  44550. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  44551. this._htmlAudioElement.onended = function () { _this._onended(); };
  44552. this._htmlAudioElement.playbackRate = this._playbackRate;
  44553. }
  44554. this._streamingSource.disconnect();
  44555. this._streamingSource.connect(this._inputAudioNode);
  44556. this._htmlAudioElement.play();
  44557. }
  44558. else {
  44559. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  44560. this._soundSource.buffer = this._audioBuffer;
  44561. this._soundSource.connect(this._inputAudioNode);
  44562. this._soundSource.loop = this.loop;
  44563. this._soundSource.playbackRate.value = this._playbackRate;
  44564. this._soundSource.onended = function () { _this._onended(); };
  44565. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  44566. }
  44567. this._startTime = startTime;
  44568. this.isPlaying = true;
  44569. this.isPaused = false;
  44570. }
  44571. catch (ex) {
  44572. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  44573. }
  44574. }
  44575. };
  44576. Sound.prototype._onended = function () {
  44577. this.isPlaying = false;
  44578. if (this.onended) {
  44579. this.onended();
  44580. }
  44581. };
  44582. /**
  44583. * Stop the sound
  44584. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  44585. */
  44586. Sound.prototype.stop = function (time) {
  44587. if (this.isPlaying) {
  44588. if (this._streaming) {
  44589. this._htmlAudioElement.pause();
  44590. // Test needed for Firefox or it will generate an Invalid State Error
  44591. if (this._htmlAudioElement.currentTime > 0) {
  44592. this._htmlAudioElement.currentTime = 0;
  44593. }
  44594. }
  44595. else {
  44596. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44597. this._soundSource.stop(stopTime);
  44598. this._soundSource.onended = null;
  44599. if (!this.isPaused) {
  44600. this._startOffset = 0;
  44601. }
  44602. }
  44603. this.isPlaying = false;
  44604. }
  44605. };
  44606. Sound.prototype.pause = function () {
  44607. if (this.isPlaying) {
  44608. this.isPaused = true;
  44609. if (this._streaming) {
  44610. this._htmlAudioElement.pause();
  44611. }
  44612. else {
  44613. this.stop(0);
  44614. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  44615. }
  44616. }
  44617. };
  44618. Sound.prototype.setVolume = function (newVolume, time) {
  44619. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44620. if (time) {
  44621. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  44622. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  44623. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  44624. }
  44625. else {
  44626. this._soundGain.gain.value = newVolume;
  44627. }
  44628. }
  44629. this._volume = newVolume;
  44630. };
  44631. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  44632. this._playbackRate = newPlaybackRate;
  44633. if (this.isPlaying) {
  44634. if (this._streaming) {
  44635. this._htmlAudioElement.playbackRate = this._playbackRate;
  44636. }
  44637. else {
  44638. this._soundSource.playbackRate.value = this._playbackRate;
  44639. }
  44640. }
  44641. };
  44642. Sound.prototype.getVolume = function () {
  44643. return this._volume;
  44644. };
  44645. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  44646. var _this = this;
  44647. if (this._connectedMesh) {
  44648. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44649. this._registerFunc = null;
  44650. }
  44651. this._connectedMesh = meshToConnectTo;
  44652. if (!this.spatialSound) {
  44653. this.spatialSound = true;
  44654. this._createSpatialParameters();
  44655. if (this.isPlaying && this.loop) {
  44656. this.stop();
  44657. this.play();
  44658. }
  44659. }
  44660. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  44661. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  44662. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  44663. };
  44664. Sound.prototype.detachFromMesh = function () {
  44665. if (this._connectedMesh) {
  44666. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44667. this._registerFunc = null;
  44668. this._connectedMesh = null;
  44669. }
  44670. };
  44671. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  44672. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  44673. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  44674. this._updateDirection();
  44675. }
  44676. };
  44677. Sound.prototype.clone = function () {
  44678. var _this = this;
  44679. if (!this._streaming) {
  44680. var setBufferAndRun = function () {
  44681. if (_this._isReadyToPlay) {
  44682. clonedSound._audioBuffer = _this.getAudioBuffer();
  44683. clonedSound._isReadyToPlay = true;
  44684. if (clonedSound.autoplay) {
  44685. clonedSound.play();
  44686. }
  44687. }
  44688. else {
  44689. window.setTimeout(setBufferAndRun, 300);
  44690. }
  44691. };
  44692. var currentOptions = {
  44693. autoplay: this.autoplay, loop: this.loop,
  44694. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  44695. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  44696. refDistance: this.refDistance, distanceModel: this.distanceModel
  44697. };
  44698. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  44699. if (this.useCustomAttenuation) {
  44700. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  44701. }
  44702. clonedSound.setPosition(this._position);
  44703. clonedSound.setPlaybackRate(this._playbackRate);
  44704. setBufferAndRun();
  44705. return clonedSound;
  44706. }
  44707. else {
  44708. return null;
  44709. }
  44710. };
  44711. Sound.prototype.getAudioBuffer = function () {
  44712. return this._audioBuffer;
  44713. };
  44714. Sound.prototype.serialize = function () {
  44715. var serializationObject = {
  44716. name: this.name,
  44717. url: this.name,
  44718. autoplay: this.autoplay,
  44719. loop: this.loop,
  44720. volume: this._volume,
  44721. spatialSound: this.spatialSound,
  44722. maxDistance: this.maxDistance,
  44723. rolloffFactor: this.rolloffFactor,
  44724. refDistance: this.refDistance,
  44725. distanceModel: this.distanceModel,
  44726. playbackRate: this._playbackRate,
  44727. panningModel: this._panningModel,
  44728. soundTrackId: this.soundTrackId
  44729. };
  44730. if (this.spatialSound) {
  44731. if (this._connectedMesh)
  44732. serializationObject.connectedMeshId = this._connectedMesh.id;
  44733. serializationObject.position = this._position.asArray();
  44734. serializationObject.refDistance = this.refDistance;
  44735. serializationObject.distanceModel = this.distanceModel;
  44736. serializationObject.isDirectional = this._isDirectional;
  44737. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  44738. serializationObject.coneInnerAngle = this._coneInnerAngle;
  44739. serializationObject.coneOuterAngle = this._coneOuterAngle;
  44740. serializationObject.coneOuterGain = this._coneOuterGain;
  44741. }
  44742. return serializationObject;
  44743. };
  44744. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  44745. var soundName = parsedSound.name;
  44746. var soundUrl;
  44747. if (parsedSound.url) {
  44748. soundUrl = rootUrl + parsedSound.url;
  44749. }
  44750. else {
  44751. soundUrl = rootUrl + soundName;
  44752. }
  44753. var options = {
  44754. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  44755. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  44756. rolloffFactor: parsedSound.rolloffFactor,
  44757. refDistance: parsedSound.refDistance,
  44758. distanceModel: parsedSound.distanceModel,
  44759. playbackRate: parsedSound.playbackRate
  44760. };
  44761. var newSound;
  44762. if (!sourceSound) {
  44763. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  44764. scene._addPendingData(newSound);
  44765. }
  44766. else {
  44767. var setBufferAndRun = function () {
  44768. if (sourceSound._isReadyToPlay) {
  44769. newSound._audioBuffer = sourceSound.getAudioBuffer();
  44770. newSound._isReadyToPlay = true;
  44771. if (newSound.autoplay) {
  44772. newSound.play();
  44773. }
  44774. }
  44775. else {
  44776. window.setTimeout(setBufferAndRun, 300);
  44777. }
  44778. };
  44779. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  44780. setBufferAndRun();
  44781. }
  44782. if (parsedSound.position) {
  44783. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  44784. newSound.setPosition(soundPosition);
  44785. }
  44786. if (parsedSound.isDirectional) {
  44787. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  44788. if (parsedSound.localDirectionToMesh) {
  44789. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  44790. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  44791. }
  44792. }
  44793. if (parsedSound.connectedMeshId) {
  44794. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  44795. if (connectedMesh) {
  44796. newSound.attachToMesh(connectedMesh);
  44797. }
  44798. }
  44799. return newSound;
  44800. };
  44801. return Sound;
  44802. }());
  44803. BABYLON.Sound = Sound;
  44804. })(BABYLON || (BABYLON = {}));
  44805. //# sourceMappingURL=babylon.sound.js.map
  44806. var BABYLON;
  44807. (function (BABYLON) {
  44808. var SoundTrack = (function () {
  44809. function SoundTrack(scene, options) {
  44810. this.id = -1;
  44811. this._isMainTrack = false;
  44812. this._isInitialized = false;
  44813. this._scene = scene;
  44814. this.soundCollection = new Array();
  44815. this._options = options;
  44816. if (!this._isMainTrack) {
  44817. this._scene.soundTracks.push(this);
  44818. this.id = this._scene.soundTracks.length - 1;
  44819. }
  44820. }
  44821. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  44822. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44823. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  44824. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  44825. if (this._options) {
  44826. if (this._options.volume) {
  44827. this._outputAudioNode.gain.value = this._options.volume;
  44828. }
  44829. if (this._options.mainTrack) {
  44830. this._isMainTrack = this._options.mainTrack;
  44831. }
  44832. }
  44833. this._isInitialized = true;
  44834. }
  44835. };
  44836. SoundTrack.prototype.dispose = function () {
  44837. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44838. if (this._connectedAnalyser) {
  44839. this._connectedAnalyser.stopDebugCanvas();
  44840. }
  44841. while (this.soundCollection.length) {
  44842. this.soundCollection[0].dispose();
  44843. }
  44844. if (this._outputAudioNode) {
  44845. this._outputAudioNode.disconnect();
  44846. }
  44847. this._outputAudioNode = null;
  44848. }
  44849. };
  44850. SoundTrack.prototype.AddSound = function (sound) {
  44851. if (!this._isInitialized) {
  44852. this._initializeSoundTrackAudioGraph();
  44853. }
  44854. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44855. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  44856. }
  44857. if (sound.soundTrackId) {
  44858. if (sound.soundTrackId === -1) {
  44859. this._scene.mainSoundTrack.RemoveSound(sound);
  44860. }
  44861. else {
  44862. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44863. }
  44864. }
  44865. this.soundCollection.push(sound);
  44866. sound.soundTrackId = this.id;
  44867. };
  44868. SoundTrack.prototype.RemoveSound = function (sound) {
  44869. var index = this.soundCollection.indexOf(sound);
  44870. if (index !== -1) {
  44871. this.soundCollection.splice(index, 1);
  44872. }
  44873. };
  44874. SoundTrack.prototype.setVolume = function (newVolume) {
  44875. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44876. this._outputAudioNode.gain.value = newVolume;
  44877. }
  44878. };
  44879. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  44880. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44881. for (var i = 0; i < this.soundCollection.length; i++) {
  44882. this.soundCollection[i].switchPanningModelToHRTF();
  44883. }
  44884. }
  44885. };
  44886. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  44887. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44888. for (var i = 0; i < this.soundCollection.length; i++) {
  44889. this.soundCollection[i].switchPanningModelToEqualPower();
  44890. }
  44891. }
  44892. };
  44893. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  44894. if (this._connectedAnalyser) {
  44895. this._connectedAnalyser.stopDebugCanvas();
  44896. }
  44897. this._connectedAnalyser = analyser;
  44898. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44899. this._outputAudioNode.disconnect();
  44900. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  44901. }
  44902. };
  44903. return SoundTrack;
  44904. }());
  44905. BABYLON.SoundTrack = SoundTrack;
  44906. })(BABYLON || (BABYLON = {}));
  44907. //# sourceMappingURL=babylon.soundtrack.js.map
  44908. var BABYLON;
  44909. (function (BABYLON) {
  44910. var Analyser = (function () {
  44911. function Analyser(scene) {
  44912. this.SMOOTHING = 0.75;
  44913. this.FFT_SIZE = 512;
  44914. this.BARGRAPHAMPLITUDE = 256;
  44915. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  44916. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  44917. this._scene = scene;
  44918. this._audioEngine = BABYLON.Engine.audioEngine;
  44919. if (this._audioEngine.canUseWebAudio) {
  44920. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  44921. this._webAudioAnalyser.minDecibels = -140;
  44922. this._webAudioAnalyser.maxDecibels = 0;
  44923. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44924. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44925. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  44926. }
  44927. }
  44928. Analyser.prototype.getFrequencyBinCount = function () {
  44929. if (this._audioEngine.canUseWebAudio) {
  44930. return this._webAudioAnalyser.frequencyBinCount;
  44931. }
  44932. else {
  44933. return 0;
  44934. }
  44935. };
  44936. Analyser.prototype.getByteFrequencyData = function () {
  44937. if (this._audioEngine.canUseWebAudio) {
  44938. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44939. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44940. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  44941. }
  44942. return this._byteFreqs;
  44943. };
  44944. Analyser.prototype.getByteTimeDomainData = function () {
  44945. if (this._audioEngine.canUseWebAudio) {
  44946. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44947. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44948. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  44949. }
  44950. return this._byteTime;
  44951. };
  44952. Analyser.prototype.getFloatFrequencyData = function () {
  44953. if (this._audioEngine.canUseWebAudio) {
  44954. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44955. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44956. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  44957. }
  44958. return this._floatFreqs;
  44959. };
  44960. Analyser.prototype.drawDebugCanvas = function () {
  44961. var _this = this;
  44962. if (this._audioEngine.canUseWebAudio) {
  44963. if (!this._debugCanvas) {
  44964. this._debugCanvas = document.createElement("canvas");
  44965. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  44966. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  44967. this._debugCanvas.style.position = "absolute";
  44968. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  44969. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  44970. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  44971. document.body.appendChild(this._debugCanvas);
  44972. this._registerFunc = function () {
  44973. _this.drawDebugCanvas();
  44974. };
  44975. this._scene.registerBeforeRender(this._registerFunc);
  44976. }
  44977. if (this._registerFunc) {
  44978. var workingArray = this.getByteFrequencyData();
  44979. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  44980. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  44981. // Draw the frequency domain chart.
  44982. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  44983. var value = workingArray[i];
  44984. var percent = value / this.BARGRAPHAMPLITUDE;
  44985. var height = this.DEBUGCANVASSIZE.height * percent;
  44986. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  44987. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  44988. var hue = i / this.getFrequencyBinCount() * 360;
  44989. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  44990. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  44991. }
  44992. }
  44993. }
  44994. };
  44995. Analyser.prototype.stopDebugCanvas = function () {
  44996. if (this._debugCanvas) {
  44997. this._scene.unregisterBeforeRender(this._registerFunc);
  44998. this._registerFunc = null;
  44999. document.body.removeChild(this._debugCanvas);
  45000. this._debugCanvas = null;
  45001. this._debugCanvasContext = null;
  45002. }
  45003. };
  45004. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45005. if (this._audioEngine.canUseWebAudio) {
  45006. inputAudioNode.connect(this._webAudioAnalyser);
  45007. this._webAudioAnalyser.connect(outputAudioNode);
  45008. }
  45009. };
  45010. Analyser.prototype.dispose = function () {
  45011. if (this._audioEngine.canUseWebAudio) {
  45012. this._webAudioAnalyser.disconnect();
  45013. }
  45014. };
  45015. return Analyser;
  45016. }());
  45017. BABYLON.Analyser = Analyser;
  45018. })(BABYLON || (BABYLON = {}));
  45019. //# sourceMappingURL=babylon.analyser.js.map
  45020. var BABYLON;
  45021. (function (BABYLON) {
  45022. var CubeTexture = (function (_super) {
  45023. __extends(CubeTexture, _super);
  45024. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  45025. if (onLoad === void 0) { onLoad = null; }
  45026. if (onError === void 0) { onError = null; }
  45027. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45028. if (prefiltered === void 0) { prefiltered = false; }
  45029. if (forcedExtension === void 0) { forcedExtension = null; }
  45030. var _this = _super.call(this, scene) || this;
  45031. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  45032. _this.name = rootUrl;
  45033. _this.url = rootUrl;
  45034. _this._noMipmap = noMipmap;
  45035. _this.hasAlpha = false;
  45036. _this._format = format;
  45037. _this._prefiltered = prefiltered;
  45038. _this.isCube = true;
  45039. _this._textureMatrix = BABYLON.Matrix.Identity();
  45040. if (prefiltered) {
  45041. _this.gammaSpace = false;
  45042. }
  45043. if (!rootUrl && !files) {
  45044. return _this;
  45045. }
  45046. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  45047. if (!files) {
  45048. if (!extensions) {
  45049. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  45050. }
  45051. files = [];
  45052. for (var index = 0; index < extensions.length; index++) {
  45053. files.push(rootUrl + extensions[index]);
  45054. }
  45055. _this._extensions = extensions;
  45056. }
  45057. _this._files = files;
  45058. if (!_this._texture) {
  45059. if (!scene.useDelayedTextureLoading) {
  45060. if (prefiltered) {
  45061. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  45062. }
  45063. else {
  45064. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  45065. }
  45066. }
  45067. else {
  45068. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  45069. }
  45070. }
  45071. else if (onLoad) {
  45072. if (_this._texture.isReady) {
  45073. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  45074. }
  45075. else {
  45076. _this._texture.onLoadedObservable.add(onLoad);
  45077. }
  45078. }
  45079. return _this;
  45080. }
  45081. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  45082. return new CubeTexture("", scene, null, noMipmap, files);
  45083. };
  45084. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  45085. if (forcedExtension === void 0) { forcedExtension = null; }
  45086. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  45087. };
  45088. // Methods
  45089. CubeTexture.prototype.delayLoad = function () {
  45090. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45091. return;
  45092. }
  45093. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45094. this._texture = this._getFromCache(this.url, this._noMipmap);
  45095. if (!this._texture) {
  45096. if (this._prefiltered) {
  45097. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  45098. }
  45099. else {
  45100. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  45101. }
  45102. }
  45103. };
  45104. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  45105. return this._textureMatrix;
  45106. };
  45107. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  45108. this._textureMatrix = value;
  45109. };
  45110. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45111. var texture = BABYLON.SerializationHelper.Parse(function () {
  45112. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  45113. }, parsedTexture, scene);
  45114. // Animations
  45115. if (parsedTexture.animations) {
  45116. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  45117. var parsedAnimation = parsedTexture.animations[animationIndex];
  45118. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45119. }
  45120. }
  45121. return texture;
  45122. };
  45123. CubeTexture.prototype.clone = function () {
  45124. var _this = this;
  45125. return BABYLON.SerializationHelper.Clone(function () {
  45126. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  45127. }, this);
  45128. };
  45129. return CubeTexture;
  45130. }(BABYLON.BaseTexture));
  45131. BABYLON.CubeTexture = CubeTexture;
  45132. })(BABYLON || (BABYLON = {}));
  45133. //# sourceMappingURL=babylon.cubeTexture.js.map
  45134. var BABYLON;
  45135. (function (BABYLON) {
  45136. var RenderTargetTexture = (function (_super) {
  45137. __extends(RenderTargetTexture, _super);
  45138. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  45139. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  45140. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45141. if (isCube === void 0) { isCube = false; }
  45142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45143. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45144. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  45145. if (isMulti === void 0) { isMulti = false; }
  45146. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  45147. _this.isCube = isCube;
  45148. /**
  45149. * Use this list to define the list of mesh you want to render.
  45150. */
  45151. _this.renderList = new Array();
  45152. _this.renderParticles = true;
  45153. _this.renderSprites = false;
  45154. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  45155. _this.ignoreCameraViewport = false;
  45156. // Events
  45157. /**
  45158. * An event triggered when the texture is unbind.
  45159. * @type {BABYLON.Observable}
  45160. */
  45161. _this.onBeforeBindObservable = new BABYLON.Observable();
  45162. /**
  45163. * An event triggered when the texture is unbind.
  45164. * @type {BABYLON.Observable}
  45165. */
  45166. _this.onAfterUnbindObservable = new BABYLON.Observable();
  45167. /**
  45168. * An event triggered before rendering the texture
  45169. * @type {BABYLON.Observable}
  45170. */
  45171. _this.onBeforeRenderObservable = new BABYLON.Observable();
  45172. /**
  45173. * An event triggered after rendering the texture
  45174. * @type {BABYLON.Observable}
  45175. */
  45176. _this.onAfterRenderObservable = new BABYLON.Observable();
  45177. /**
  45178. * An event triggered after the texture clear
  45179. * @type {BABYLON.Observable}
  45180. */
  45181. _this.onClearObservable = new BABYLON.Observable();
  45182. _this._currentRefreshId = -1;
  45183. _this._refreshRate = 1;
  45184. _this._samples = 1;
  45185. scene = _this.getScene();
  45186. _this.name = name;
  45187. _this.isRenderTarget = true;
  45188. _this._size = size;
  45189. _this._generateMipMaps = generateMipMaps;
  45190. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  45191. // Rendering groups
  45192. _this._renderingManager = new BABYLON.RenderingManager(scene);
  45193. if (isMulti) {
  45194. return _this;
  45195. }
  45196. _this._renderTargetOptions = {
  45197. generateMipMaps: generateMipMaps,
  45198. type: type,
  45199. samplingMode: samplingMode,
  45200. generateDepthBuffer: generateDepthBuffer,
  45201. generateStencilBuffer: generateStencilBuffer
  45202. };
  45203. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  45204. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45205. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45206. }
  45207. if (isCube) {
  45208. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  45209. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  45210. _this._textureMatrix = BABYLON.Matrix.Identity();
  45211. }
  45212. else {
  45213. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  45214. }
  45215. return _this;
  45216. }
  45217. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  45218. get: function () {
  45219. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  45220. },
  45221. enumerable: true,
  45222. configurable: true
  45223. });
  45224. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  45225. get: function () {
  45226. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  45227. },
  45228. enumerable: true,
  45229. configurable: true
  45230. });
  45231. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  45232. get: function () {
  45233. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  45234. },
  45235. enumerable: true,
  45236. configurable: true
  45237. });
  45238. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  45239. set: function (callback) {
  45240. if (this._onAfterUnbindObserver) {
  45241. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  45242. }
  45243. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  45244. },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  45249. set: function (callback) {
  45250. if (this._onBeforeRenderObserver) {
  45251. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45252. }
  45253. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45254. },
  45255. enumerable: true,
  45256. configurable: true
  45257. });
  45258. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  45259. set: function (callback) {
  45260. if (this._onAfterRenderObserver) {
  45261. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45262. }
  45263. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45264. },
  45265. enumerable: true,
  45266. configurable: true
  45267. });
  45268. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  45269. set: function (callback) {
  45270. if (this._onClearObserver) {
  45271. this.onClearObservable.remove(this._onClearObserver);
  45272. }
  45273. this._onClearObserver = this.onClearObservable.add(callback);
  45274. },
  45275. enumerable: true,
  45276. configurable: true
  45277. });
  45278. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  45279. get: function () {
  45280. return this._renderTargetOptions;
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  45286. get: function () {
  45287. return this._samples;
  45288. },
  45289. set: function (value) {
  45290. if (this._samples === value) {
  45291. return;
  45292. }
  45293. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  45294. },
  45295. enumerable: true,
  45296. configurable: true
  45297. });
  45298. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  45299. this._currentRefreshId = -1;
  45300. };
  45301. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  45302. get: function () {
  45303. return this._refreshRate;
  45304. },
  45305. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  45306. set: function (value) {
  45307. this._refreshRate = value;
  45308. this.resetRefreshCounter();
  45309. },
  45310. enumerable: true,
  45311. configurable: true
  45312. });
  45313. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  45314. if (!this._postProcessManager) {
  45315. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  45316. this._postProcesses = new Array();
  45317. }
  45318. this._postProcesses.push(postProcess);
  45319. this._postProcesses[0].autoClear = false;
  45320. };
  45321. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  45322. if (!this._postProcesses) {
  45323. return;
  45324. }
  45325. if (dispose) {
  45326. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  45327. var postProcess = _a[_i];
  45328. postProcess.dispose();
  45329. postProcess = null;
  45330. }
  45331. }
  45332. this._postProcesses = [];
  45333. };
  45334. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  45335. if (!this._postProcesses) {
  45336. return;
  45337. }
  45338. var index = this._postProcesses.indexOf(postProcess);
  45339. if (index === -1) {
  45340. return;
  45341. }
  45342. this._postProcesses.splice(index, 1);
  45343. if (this._postProcesses.length > 0) {
  45344. this._postProcesses[0].autoClear = false;
  45345. }
  45346. };
  45347. RenderTargetTexture.prototype._shouldRender = function () {
  45348. if (this._currentRefreshId === -1) {
  45349. this._currentRefreshId = 1;
  45350. return true;
  45351. }
  45352. if (this.refreshRate === this._currentRefreshId) {
  45353. this._currentRefreshId = 1;
  45354. return true;
  45355. }
  45356. this._currentRefreshId++;
  45357. return false;
  45358. };
  45359. RenderTargetTexture.prototype.getRenderSize = function () {
  45360. return this._size;
  45361. };
  45362. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  45363. get: function () {
  45364. return true;
  45365. },
  45366. enumerable: true,
  45367. configurable: true
  45368. });
  45369. RenderTargetTexture.prototype.scale = function (ratio) {
  45370. var newSize = this._size * ratio;
  45371. this.resize(newSize);
  45372. };
  45373. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  45374. if (this.isCube) {
  45375. return this._textureMatrix;
  45376. }
  45377. return _super.prototype.getReflectionTextureMatrix.call(this);
  45378. };
  45379. RenderTargetTexture.prototype.resize = function (size) {
  45380. this.releaseInternalTexture();
  45381. if (this.isCube) {
  45382. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  45383. }
  45384. else {
  45385. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  45386. }
  45387. };
  45388. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  45389. var scene = this.getScene();
  45390. var engine = scene.getEngine();
  45391. if (this.useCameraPostProcesses !== undefined) {
  45392. useCameraPostProcess = this.useCameraPostProcesses;
  45393. }
  45394. if (this._waitingRenderList) {
  45395. this.renderList = [];
  45396. for (var index = 0; index < this._waitingRenderList.length; index++) {
  45397. var id = this._waitingRenderList[index];
  45398. this.renderList.push(scene.getMeshByID(id));
  45399. }
  45400. delete this._waitingRenderList;
  45401. }
  45402. // Is predicate defined?
  45403. if (this.renderListPredicate) {
  45404. this.renderList.splice(0); // Clear previous renderList
  45405. var sceneMeshes = this.getScene().meshes;
  45406. for (var index = 0; index < sceneMeshes.length; index++) {
  45407. var mesh = sceneMeshes[index];
  45408. if (this.renderListPredicate(mesh)) {
  45409. this.renderList.push(mesh);
  45410. }
  45411. }
  45412. }
  45413. if (this.renderList && this.renderList.length === 0) {
  45414. return;
  45415. }
  45416. this.onBeforeBindObservable.notifyObservers(this);
  45417. // Set custom projection.
  45418. // Needs to be before binding to prevent changing the aspect ratio.
  45419. var camera;
  45420. if (this.activeCamera) {
  45421. camera = this.activeCamera;
  45422. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  45423. if (this.activeCamera !== scene.activeCamera) {
  45424. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  45425. }
  45426. }
  45427. else {
  45428. camera = scene.activeCamera;
  45429. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  45430. }
  45431. // Prepare renderingManager
  45432. this._renderingManager.reset();
  45433. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  45434. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  45435. var sceneRenderId = scene.getRenderId();
  45436. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  45437. var mesh = currentRenderList[meshIndex];
  45438. if (mesh) {
  45439. if (!mesh.isReady()) {
  45440. // Reset _currentRefreshId
  45441. this.resetRefreshCounter();
  45442. continue;
  45443. }
  45444. mesh._preActivateForIntermediateRendering(sceneRenderId);
  45445. var isMasked = void 0;
  45446. if (!this.renderList) {
  45447. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  45448. }
  45449. else {
  45450. isMasked = false;
  45451. }
  45452. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  45453. mesh._activate(sceneRenderId);
  45454. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45455. var subMesh = mesh.subMeshes[subIndex];
  45456. scene._activeIndices.addCount(subMesh.indexCount, false);
  45457. this._renderingManager.dispatch(subMesh);
  45458. }
  45459. }
  45460. }
  45461. }
  45462. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  45463. var particleSystem = scene.particleSystems[particleIndex];
  45464. var emitter = particleSystem.emitter;
  45465. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  45466. continue;
  45467. }
  45468. if (currentRenderList.indexOf(emitter) >= 0) {
  45469. this._renderingManager.dispatchParticles(particleSystem);
  45470. }
  45471. }
  45472. if (this.isCube) {
  45473. for (var face = 0; face < 6; face++) {
  45474. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45475. scene.incrementRenderId();
  45476. scene.resetCachedMaterial();
  45477. }
  45478. }
  45479. else {
  45480. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45481. }
  45482. this.onAfterUnbindObservable.notifyObservers(this);
  45483. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  45484. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  45485. }
  45486. engine.setViewport(scene.activeCamera.viewport);
  45487. scene.resetCachedMaterial();
  45488. };
  45489. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  45490. var _this = this;
  45491. var scene = this.getScene();
  45492. var engine = scene.getEngine();
  45493. // Bind
  45494. if (this._postProcessManager) {
  45495. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  45496. }
  45497. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  45498. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  45499. }
  45500. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  45501. // Clear
  45502. if (this.onClearObservable.hasObservers()) {
  45503. this.onClearObservable.notifyObservers(engine);
  45504. }
  45505. else {
  45506. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  45507. }
  45508. if (!this._doNotChangeAspectRatio) {
  45509. scene.updateTransformMatrix(true);
  45510. }
  45511. // Render
  45512. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  45513. if (this._postProcessManager) {
  45514. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  45515. }
  45516. else if (useCameraPostProcess) {
  45517. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  45518. }
  45519. if (!this._doNotChangeAspectRatio) {
  45520. scene.updateTransformMatrix(true);
  45521. }
  45522. // Dump ?
  45523. if (dumpForDebug) {
  45524. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  45525. }
  45526. // Unbind
  45527. if (!this.isCube || faceIndex === 5) {
  45528. if (this.isCube) {
  45529. if (faceIndex === 5) {
  45530. engine.generateMipMapsForCubemap(this._texture);
  45531. }
  45532. }
  45533. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  45534. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  45535. });
  45536. }
  45537. else {
  45538. this.onAfterRenderObservable.notifyObservers(faceIndex);
  45539. }
  45540. };
  45541. /**
  45542. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  45543. * This allowed control for front to back rendering or reversly depending of the special needs.
  45544. *
  45545. * @param renderingGroupId The rendering group id corresponding to its index
  45546. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  45547. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  45548. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  45549. */
  45550. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  45551. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  45552. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  45553. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  45554. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  45555. };
  45556. /**
  45557. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  45558. *
  45559. * @param renderingGroupId The rendering group id corresponding to its index
  45560. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  45561. */
  45562. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  45563. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  45564. };
  45565. RenderTargetTexture.prototype.clone = function () {
  45566. var textureSize = this.getSize();
  45567. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  45568. // Base texture
  45569. newTexture.hasAlpha = this.hasAlpha;
  45570. newTexture.level = this.level;
  45571. // RenderTarget Texture
  45572. newTexture.coordinatesMode = this.coordinatesMode;
  45573. newTexture.renderList = this.renderList.slice(0);
  45574. return newTexture;
  45575. };
  45576. RenderTargetTexture.prototype.serialize = function () {
  45577. if (!this.name) {
  45578. return null;
  45579. }
  45580. var serializationObject = _super.prototype.serialize.call(this);
  45581. serializationObject.renderTargetSize = this.getRenderSize();
  45582. serializationObject.renderList = [];
  45583. for (var index = 0; index < this.renderList.length; index++) {
  45584. serializationObject.renderList.push(this.renderList[index].id);
  45585. }
  45586. return serializationObject;
  45587. };
  45588. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  45589. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  45590. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  45591. };
  45592. RenderTargetTexture.prototype.dispose = function () {
  45593. if (this._postProcessManager) {
  45594. this._postProcessManager.dispose();
  45595. this._postProcessManager = null;
  45596. }
  45597. this.clearPostProcesses(true);
  45598. this.renderList = null;
  45599. // Remove from custom render targets
  45600. var scene = this.getScene();
  45601. var index = scene.customRenderTargets.indexOf(this);
  45602. if (index >= 0) {
  45603. scene.customRenderTargets.splice(index, 1);
  45604. }
  45605. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  45606. var camera = _a[_i];
  45607. index = camera.customRenderTargets.indexOf(this);
  45608. if (index >= 0) {
  45609. camera.customRenderTargets.splice(index, 1);
  45610. }
  45611. }
  45612. _super.prototype.dispose.call(this);
  45613. };
  45614. RenderTargetTexture.prototype._rebuild = function () {
  45615. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  45616. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  45617. }
  45618. if (this._postProcessManager) {
  45619. this._postProcessManager._rebuild();
  45620. }
  45621. };
  45622. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  45623. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  45624. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  45625. return RenderTargetTexture;
  45626. }(BABYLON.Texture));
  45627. BABYLON.RenderTargetTexture = RenderTargetTexture;
  45628. })(BABYLON || (BABYLON = {}));
  45629. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  45630. var BABYLON;
  45631. (function (BABYLON) {
  45632. ;
  45633. var MultiRenderTarget = (function (_super) {
  45634. __extends(MultiRenderTarget, _super);
  45635. function MultiRenderTarget(name, size, count, scene, options) {
  45636. var _this = this;
  45637. options = options || {};
  45638. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  45639. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  45640. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  45641. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  45642. if (!_this.isSupported) {
  45643. _this.dispose();
  45644. return;
  45645. }
  45646. var types = [];
  45647. var samplingModes = [];
  45648. for (var i = 0; i < count; i++) {
  45649. if (options.types && options.types[i]) {
  45650. types.push(options.types[i]);
  45651. }
  45652. else {
  45653. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  45654. }
  45655. if (options.samplingModes && options.samplingModes[i]) {
  45656. samplingModes.push(options.samplingModes[i]);
  45657. }
  45658. else {
  45659. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45660. }
  45661. }
  45662. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  45663. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  45664. _this._count = count;
  45665. _this._size = size;
  45666. _this._multiRenderTargetOptions = {
  45667. samplingModes: samplingModes,
  45668. generateMipMaps: generateMipMaps,
  45669. generateDepthBuffer: generateDepthBuffer,
  45670. generateStencilBuffer: generateStencilBuffer,
  45671. generateDepthTexture: generateDepthTexture,
  45672. types: types,
  45673. textureCount: count
  45674. };
  45675. _this._internalTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  45676. _this._createInternalTextures();
  45677. return _this;
  45678. }
  45679. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  45680. get: function () {
  45681. var engine = this.getScene().getEngine();
  45682. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  45683. },
  45684. enumerable: true,
  45685. configurable: true
  45686. });
  45687. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  45688. get: function () {
  45689. return this._textures;
  45690. },
  45691. enumerable: true,
  45692. configurable: true
  45693. });
  45694. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  45695. get: function () {
  45696. return this._textures[this._textures.length - 1];
  45697. },
  45698. enumerable: true,
  45699. configurable: true
  45700. });
  45701. MultiRenderTarget.prototype._createInternalTextures = function () {
  45702. this._textures = [];
  45703. for (var i = 0; i < this._internalTextures.length; i++) {
  45704. var texture = new BABYLON.Texture(null, this.getScene());
  45705. texture._texture = this._internalTextures[i];
  45706. this._textures.push(texture);
  45707. }
  45708. // Keeps references to frame buffer and stencil/depth buffer
  45709. this._texture = this._internalTextures[0];
  45710. };
  45711. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  45712. get: function () {
  45713. return this._samples;
  45714. },
  45715. set: function (value) {
  45716. if (this._samples === value) {
  45717. return;
  45718. }
  45719. for (var i = 0; i < this._internalTextures.length; i++) {
  45720. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  45721. }
  45722. },
  45723. enumerable: true,
  45724. configurable: true
  45725. });
  45726. MultiRenderTarget.prototype.resize = function (size) {
  45727. this.releaseInternalTextures();
  45728. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  45729. this._createInternalTextures();
  45730. };
  45731. MultiRenderTarget.prototype.dispose = function () {
  45732. this.releaseInternalTextures();
  45733. _super.prototype.dispose.call(this);
  45734. };
  45735. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  45736. if (!this._internalTextures) {
  45737. return;
  45738. }
  45739. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  45740. if (this._internalTextures[i] !== undefined) {
  45741. this._internalTextures[i].dispose();
  45742. this._internalTextures.splice(i, 1);
  45743. }
  45744. }
  45745. };
  45746. return MultiRenderTarget;
  45747. }(BABYLON.RenderTargetTexture));
  45748. BABYLON.MultiRenderTarget = MultiRenderTarget;
  45749. })(BABYLON || (BABYLON = {}));
  45750. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  45751. /// <reference path="babylon.renderTargetTexture.ts" />
  45752. var BABYLON;
  45753. (function (BABYLON) {
  45754. var MirrorTexture = (function (_super) {
  45755. __extends(MirrorTexture, _super);
  45756. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  45757. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45759. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45760. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  45761. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  45762. _this._transformMatrix = BABYLON.Matrix.Zero();
  45763. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  45764. _this._blurKernelX = 0;
  45765. _this._blurKernelY = 0;
  45766. _this._blurRatio = 1.0;
  45767. _this.onBeforeRenderObservable.add(function () {
  45768. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  45769. _this._savedViewMatrix = scene.getViewMatrix();
  45770. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  45771. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  45772. scene.clipPlane = _this.mirrorPlane;
  45773. scene.getEngine().cullBackFaces = false;
  45774. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  45775. });
  45776. _this.onAfterRenderObservable.add(function () {
  45777. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  45778. scene.getEngine().cullBackFaces = true;
  45779. scene._mirroredCameraPosition = null;
  45780. delete scene.clipPlane;
  45781. });
  45782. return _this;
  45783. }
  45784. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  45785. get: function () {
  45786. return this._blurRatio;
  45787. },
  45788. set: function (value) {
  45789. if (this._blurRatio === value) {
  45790. return;
  45791. }
  45792. this._blurRatio = value;
  45793. this._preparePostProcesses();
  45794. },
  45795. enumerable: true,
  45796. configurable: true
  45797. });
  45798. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  45799. set: function (value) {
  45800. this.blurKernelX = value;
  45801. this.blurKernelY = value;
  45802. },
  45803. enumerable: true,
  45804. configurable: true
  45805. });
  45806. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  45807. get: function () {
  45808. return this._blurKernelX;
  45809. },
  45810. set: function (value) {
  45811. if (this._blurKernelX === value) {
  45812. return;
  45813. }
  45814. this._blurKernelX = value;
  45815. this._preparePostProcesses();
  45816. },
  45817. enumerable: true,
  45818. configurable: true
  45819. });
  45820. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  45821. get: function () {
  45822. return this._blurKernelY;
  45823. },
  45824. set: function (value) {
  45825. if (this._blurKernelY === value) {
  45826. return;
  45827. }
  45828. this._blurKernelY = value;
  45829. this._preparePostProcesses();
  45830. },
  45831. enumerable: true,
  45832. configurable: true
  45833. });
  45834. MirrorTexture.prototype._preparePostProcesses = function () {
  45835. this.clearPostProcesses(true);
  45836. if (this._blurKernelX && this._blurKernelY) {
  45837. var engine = this.getScene().getEngine();
  45838. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45839. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  45840. this._blurX.autoClear = false;
  45841. if (this._blurRatio === 1 && this.samples < 2) {
  45842. this._blurX.outputTexture = this._texture;
  45843. }
  45844. else {
  45845. this._blurX.alwaysForcePOT = true;
  45846. }
  45847. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  45848. this._blurY.autoClear = false;
  45849. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  45850. this.addPostProcess(this._blurX);
  45851. this.addPostProcess(this._blurY);
  45852. }
  45853. };
  45854. MirrorTexture.prototype.clone = function () {
  45855. var textureSize = this.getSize();
  45856. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  45857. // Base texture
  45858. newTexture.hasAlpha = this.hasAlpha;
  45859. newTexture.level = this.level;
  45860. // Mirror Texture
  45861. newTexture.mirrorPlane = this.mirrorPlane.clone();
  45862. newTexture.renderList = this.renderList.slice(0);
  45863. return newTexture;
  45864. };
  45865. MirrorTexture.prototype.serialize = function () {
  45866. if (!this.name) {
  45867. return null;
  45868. }
  45869. var serializationObject = _super.prototype.serialize.call(this);
  45870. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  45871. return serializationObject;
  45872. };
  45873. return MirrorTexture;
  45874. }(BABYLON.RenderTargetTexture));
  45875. BABYLON.MirrorTexture = MirrorTexture;
  45876. })(BABYLON || (BABYLON = {}));
  45877. //# sourceMappingURL=babylon.mirrorTexture.js.map
  45878. /// <reference path="babylon.renderTargetTexture.ts" />
  45879. var BABYLON;
  45880. (function (BABYLON) {
  45881. /**
  45882. * Creates a refraction texture used by refraction channel of the standard material.
  45883. * @param name the texture name
  45884. * @param size size of the underlying texture
  45885. * @param scene root scene
  45886. */
  45887. var RefractionTexture = (function (_super) {
  45888. __extends(RefractionTexture, _super);
  45889. function RefractionTexture(name, size, scene, generateMipMaps) {
  45890. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  45891. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  45892. _this.depth = 2.0;
  45893. _this.onBeforeRenderObservable.add(function () {
  45894. scene.clipPlane = _this.refractionPlane;
  45895. });
  45896. _this.onAfterRenderObservable.add(function () {
  45897. delete scene.clipPlane;
  45898. });
  45899. return _this;
  45900. }
  45901. RefractionTexture.prototype.clone = function () {
  45902. var textureSize = this.getSize();
  45903. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  45904. // Base texture
  45905. newTexture.hasAlpha = this.hasAlpha;
  45906. newTexture.level = this.level;
  45907. // Refraction Texture
  45908. newTexture.refractionPlane = this.refractionPlane.clone();
  45909. newTexture.renderList = this.renderList.slice(0);
  45910. newTexture.depth = this.depth;
  45911. return newTexture;
  45912. };
  45913. RefractionTexture.prototype.serialize = function () {
  45914. if (!this.name) {
  45915. return null;
  45916. }
  45917. var serializationObject = _super.prototype.serialize.call(this);
  45918. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  45919. serializationObject.depth = this.depth;
  45920. return serializationObject;
  45921. };
  45922. return RefractionTexture;
  45923. }(BABYLON.RenderTargetTexture));
  45924. BABYLON.RefractionTexture = RefractionTexture;
  45925. })(BABYLON || (BABYLON = {}));
  45926. //# sourceMappingURL=babylon.refractionTexture.js.map
  45927. /// <reference path="babylon.texture.ts" />
  45928. var BABYLON;
  45929. (function (BABYLON) {
  45930. var DynamicTexture = (function (_super) {
  45931. __extends(DynamicTexture, _super);
  45932. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  45933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45934. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45935. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  45936. _this.name = name;
  45937. var engine = _this.getScene().getEngine();
  45938. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45939. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45940. _this._generateMipMaps = generateMipMaps;
  45941. if (options.getContext) {
  45942. _this._canvas = options;
  45943. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45944. }
  45945. else {
  45946. _this._canvas = document.createElement("canvas");
  45947. if (options.width) {
  45948. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45949. }
  45950. else {
  45951. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  45952. }
  45953. }
  45954. var textureSize = _this.getSize();
  45955. _this._canvas.width = textureSize.width;
  45956. _this._canvas.height = textureSize.height;
  45957. _this._context = _this._canvas.getContext("2d");
  45958. return _this;
  45959. }
  45960. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  45961. get: function () {
  45962. return true;
  45963. },
  45964. enumerable: true,
  45965. configurable: true
  45966. });
  45967. DynamicTexture.prototype._recreate = function (textureSize) {
  45968. this._canvas.width = textureSize.width;
  45969. this._canvas.height = textureSize.height;
  45970. this.releaseInternalTexture();
  45971. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  45972. };
  45973. DynamicTexture.prototype.scale = function (ratio) {
  45974. var textureSize = this.getSize();
  45975. textureSize.width *= ratio;
  45976. textureSize.height *= ratio;
  45977. this._recreate(textureSize);
  45978. };
  45979. DynamicTexture.prototype.scaleTo = function (width, height) {
  45980. var textureSize = this.getSize();
  45981. textureSize.width = width;
  45982. textureSize.height = height;
  45983. this._recreate(textureSize);
  45984. };
  45985. DynamicTexture.prototype.getContext = function () {
  45986. return this._context;
  45987. };
  45988. DynamicTexture.prototype.clear = function () {
  45989. var size = this.getSize();
  45990. this._context.fillRect(0, 0, size.width, size.height);
  45991. };
  45992. DynamicTexture.prototype.update = function (invertY) {
  45993. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  45994. };
  45995. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  45996. if (update === void 0) { update = true; }
  45997. var size = this.getSize();
  45998. if (clearColor) {
  45999. this._context.fillStyle = clearColor;
  46000. this._context.fillRect(0, 0, size.width, size.height);
  46001. }
  46002. this._context.font = font;
  46003. if (x === null || x === undefined) {
  46004. var textSize = this._context.measureText(text);
  46005. x = (size.width - textSize.width) / 2;
  46006. }
  46007. if (y === null || y === undefined) {
  46008. var fontSize = parseInt((font.replace(/\D/g, '')));
  46009. ;
  46010. y = (size.height / 2) + (fontSize / 3.65);
  46011. }
  46012. this._context.fillStyle = color;
  46013. this._context.fillText(text, x, y);
  46014. if (update) {
  46015. this.update(invertY);
  46016. }
  46017. };
  46018. DynamicTexture.prototype.clone = function () {
  46019. var textureSize = this.getSize();
  46020. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  46021. // Base texture
  46022. newTexture.hasAlpha = this.hasAlpha;
  46023. newTexture.level = this.level;
  46024. // Dynamic Texture
  46025. newTexture.wrapU = this.wrapU;
  46026. newTexture.wrapV = this.wrapV;
  46027. return newTexture;
  46028. };
  46029. DynamicTexture.prototype._rebuild = function () {
  46030. this.update();
  46031. };
  46032. return DynamicTexture;
  46033. }(BABYLON.Texture));
  46034. BABYLON.DynamicTexture = DynamicTexture;
  46035. })(BABYLON || (BABYLON = {}));
  46036. //# sourceMappingURL=babylon.dynamicTexture.js.map
  46037. var BABYLON;
  46038. (function (BABYLON) {
  46039. var VideoTexture = (function (_super) {
  46040. __extends(VideoTexture, _super);
  46041. /**
  46042. * Creates a video texture.
  46043. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  46044. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  46045. * @param {BABYLON.Scene} scene is obviously the current scene.
  46046. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  46047. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  46048. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  46049. */
  46050. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  46051. if (generateMipMaps === void 0) { generateMipMaps = false; }
  46052. if (invertY === void 0) { invertY = false; }
  46053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46054. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46055. _this._autoLaunch = true;
  46056. var urls;
  46057. _this.name = name;
  46058. if (urlsOrVideo instanceof HTMLVideoElement) {
  46059. _this.video = urlsOrVideo;
  46060. }
  46061. else {
  46062. urls = urlsOrVideo;
  46063. _this.video = document.createElement("video");
  46064. _this.video.autoplay = false;
  46065. _this.video.loop = true;
  46066. }
  46067. _this._generateMipMaps = generateMipMaps;
  46068. _this._samplingMode = samplingMode;
  46069. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  46070. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46071. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46072. }
  46073. else {
  46074. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46075. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46076. _this._generateMipMaps = false;
  46077. }
  46078. if (urls) {
  46079. _this.video.addEventListener("canplay", function () {
  46080. _this._createTexture();
  46081. });
  46082. urls.forEach(function (url) {
  46083. var source = document.createElement("source");
  46084. source.src = url;
  46085. _this.video.appendChild(source);
  46086. });
  46087. }
  46088. else {
  46089. _this._createTexture();
  46090. }
  46091. _this._lastUpdate = BABYLON.Tools.Now;
  46092. return _this;
  46093. }
  46094. VideoTexture.prototype.__setTextureReady = function () {
  46095. this._texture.isReady = true;
  46096. };
  46097. VideoTexture.prototype._createTexture = function () {
  46098. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  46099. if (this._autoLaunch) {
  46100. this._autoLaunch = false;
  46101. this.video.play();
  46102. }
  46103. this._setTextureReady = this.__setTextureReady.bind(this);
  46104. this.video.addEventListener("playing", this._setTextureReady);
  46105. };
  46106. VideoTexture.prototype.update = function () {
  46107. var now = BABYLON.Tools.Now;
  46108. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  46109. return false;
  46110. }
  46111. this._lastUpdate = now;
  46112. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  46113. return true;
  46114. };
  46115. VideoTexture.prototype.dispose = function () {
  46116. _super.prototype.dispose.call(this);
  46117. this.video.removeEventListener("playing", this._setTextureReady);
  46118. };
  46119. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  46120. var video = document.createElement("video");
  46121. var constraintsDeviceId;
  46122. if (constraints && constraints.deviceId) {
  46123. constraintsDeviceId = {
  46124. exact: constraints.deviceId
  46125. };
  46126. }
  46127. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  46128. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  46129. if (navigator.getUserMedia) {
  46130. navigator.getUserMedia({
  46131. video: {
  46132. deviceId: constraintsDeviceId,
  46133. width: {
  46134. min: (constraints && constraints.minWidth) || 256,
  46135. max: (constraints && constraints.maxWidth) || 640
  46136. },
  46137. height: {
  46138. min: (constraints && constraints.minHeight) || 256,
  46139. max: (constraints && constraints.maxHeight) || 480
  46140. }
  46141. }
  46142. }, function (stream) {
  46143. if (video.mozSrcObject !== undefined) {
  46144. video.mozSrcObject = stream;
  46145. }
  46146. else {
  46147. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  46148. }
  46149. video.play();
  46150. if (onReady) {
  46151. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  46152. }
  46153. }, function (e) {
  46154. BABYLON.Tools.Error(e.name);
  46155. });
  46156. }
  46157. };
  46158. return VideoTexture;
  46159. }(BABYLON.Texture));
  46160. BABYLON.VideoTexture = VideoTexture;
  46161. })(BABYLON || (BABYLON = {}));
  46162. //# sourceMappingURL=babylon.videoTexture.js.map
  46163. var BABYLON;
  46164. (function (BABYLON) {
  46165. var RawTexture = (function (_super) {
  46166. __extends(RawTexture, _super);
  46167. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  46168. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46169. if (invertY === void 0) { invertY = false; }
  46170. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46171. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46172. _this.format = format;
  46173. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  46174. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46175. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46176. return _this;
  46177. }
  46178. RawTexture.prototype.update = function (data) {
  46179. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  46180. };
  46181. // Statics
  46182. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46183. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46184. if (invertY === void 0) { invertY = false; }
  46185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46186. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  46187. };
  46188. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46189. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46190. if (invertY === void 0) { invertY = false; }
  46191. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46192. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46193. };
  46194. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46195. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46196. if (invertY === void 0) { invertY = false; }
  46197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46198. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46199. };
  46200. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46201. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46202. if (invertY === void 0) { invertY = false; }
  46203. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46204. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  46205. };
  46206. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46207. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46208. if (invertY === void 0) { invertY = false; }
  46209. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46210. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  46211. };
  46212. return RawTexture;
  46213. }(BABYLON.Texture));
  46214. BABYLON.RawTexture = RawTexture;
  46215. })(BABYLON || (BABYLON = {}));
  46216. //# sourceMappingURL=babylon.rawTexture.js.map
  46217. var BABYLON;
  46218. (function (BABYLON) {
  46219. var PostProcess = (function () {
  46220. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  46221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  46222. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46223. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  46224. if (blockCompilation === void 0) { blockCompilation = false; }
  46225. this.name = name;
  46226. this.width = -1;
  46227. this.height = -1;
  46228. this.autoClear = true;
  46229. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  46230. /*
  46231. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  46232. Can only be used on a single postprocess or on the last one of a chain.
  46233. */
  46234. this.enablePixelPerfectMode = false;
  46235. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  46236. this.alwaysForcePOT = false;
  46237. this.samples = 1;
  46238. this._reusable = false;
  46239. this._textures = new BABYLON.SmartArray(2);
  46240. this._currentRenderTextureInd = 0;
  46241. this._scaleRatio = new BABYLON.Vector2(1, 1);
  46242. this._texelSize = BABYLON.Vector2.Zero();
  46243. // Events
  46244. /**
  46245. * An event triggered when the postprocess is activated.
  46246. * @type {BABYLON.Observable}
  46247. */
  46248. this.onActivateObservable = new BABYLON.Observable();
  46249. /**
  46250. * An event triggered when the postprocess changes its size.
  46251. * @type {BABYLON.Observable}
  46252. */
  46253. this.onSizeChangedObservable = new BABYLON.Observable();
  46254. /**
  46255. * An event triggered when the postprocess applies its effect.
  46256. * @type {BABYLON.Observable}
  46257. */
  46258. this.onApplyObservable = new BABYLON.Observable();
  46259. /**
  46260. * An event triggered before rendering the postprocess
  46261. * @type {BABYLON.Observable}
  46262. */
  46263. this.onBeforeRenderObservable = new BABYLON.Observable();
  46264. /**
  46265. * An event triggered after rendering the postprocess
  46266. * @type {BABYLON.Observable}
  46267. */
  46268. this.onAfterRenderObservable = new BABYLON.Observable();
  46269. if (camera != null) {
  46270. this._camera = camera;
  46271. this._scene = camera.getScene();
  46272. camera.attachPostProcess(this);
  46273. this._engine = this._scene.getEngine();
  46274. this._scene.postProcesses.push(this);
  46275. }
  46276. else {
  46277. this._engine = engine;
  46278. this._engine.postProcesses.push(this);
  46279. }
  46280. this._options = options;
  46281. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  46282. this._reusable = reusable || false;
  46283. this._textureType = textureType;
  46284. this._samplers = samplers || [];
  46285. this._samplers.push("textureSampler");
  46286. this._fragmentUrl = fragmentUrl;
  46287. this._vertexUrl = vertexUrl;
  46288. this._parameters = parameters || [];
  46289. this._parameters.push("scale");
  46290. this._indexParameters = indexParameters;
  46291. if (!blockCompilation) {
  46292. this.updateEffect(defines);
  46293. }
  46294. }
  46295. Object.defineProperty(PostProcess.prototype, "onActivate", {
  46296. set: function (callback) {
  46297. if (this._onActivateObserver) {
  46298. this.onActivateObservable.remove(this._onActivateObserver);
  46299. }
  46300. this._onActivateObserver = this.onActivateObservable.add(callback);
  46301. },
  46302. enumerable: true,
  46303. configurable: true
  46304. });
  46305. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  46306. set: function (callback) {
  46307. if (this._onSizeChangedObserver) {
  46308. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  46309. }
  46310. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  46311. },
  46312. enumerable: true,
  46313. configurable: true
  46314. });
  46315. Object.defineProperty(PostProcess.prototype, "onApply", {
  46316. set: function (callback) {
  46317. if (this._onApplyObserver) {
  46318. this.onApplyObservable.remove(this._onApplyObserver);
  46319. }
  46320. this._onApplyObserver = this.onApplyObservable.add(callback);
  46321. },
  46322. enumerable: true,
  46323. configurable: true
  46324. });
  46325. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  46326. set: function (callback) {
  46327. if (this._onBeforeRenderObserver) {
  46328. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46329. }
  46330. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46331. },
  46332. enumerable: true,
  46333. configurable: true
  46334. });
  46335. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  46336. set: function (callback) {
  46337. if (this._onAfterRenderObserver) {
  46338. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46339. }
  46340. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46341. },
  46342. enumerable: true,
  46343. configurable: true
  46344. });
  46345. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  46346. get: function () {
  46347. return this._textures.data[this._currentRenderTextureInd];
  46348. },
  46349. set: function (value) {
  46350. this._forcedOutputTexture = value;
  46351. },
  46352. enumerable: true,
  46353. configurable: true
  46354. });
  46355. PostProcess.prototype.getCamera = function () {
  46356. return this._camera;
  46357. };
  46358. Object.defineProperty(PostProcess.prototype, "texelSize", {
  46359. get: function () {
  46360. if (this._shareOutputWithPostProcess) {
  46361. return this._shareOutputWithPostProcess.texelSize;
  46362. }
  46363. if (this._forcedOutputTexture) {
  46364. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  46365. }
  46366. return this._texelSize;
  46367. },
  46368. enumerable: true,
  46369. configurable: true
  46370. });
  46371. PostProcess.prototype.getEngine = function () {
  46372. return this._engine;
  46373. };
  46374. PostProcess.prototype.getEffect = function () {
  46375. return this._effect;
  46376. };
  46377. PostProcess.prototype.shareOutputWith = function (postProcess) {
  46378. this._disposeTextures();
  46379. this._shareOutputWithPostProcess = postProcess;
  46380. return this;
  46381. };
  46382. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  46383. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  46384. };
  46385. PostProcess.prototype.isReusable = function () {
  46386. return this._reusable;
  46387. };
  46388. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  46389. PostProcess.prototype.markTextureDirty = function () {
  46390. this.width = -1;
  46391. };
  46392. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  46393. var _this = this;
  46394. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  46395. camera = camera || this._camera;
  46396. var scene = camera.getScene();
  46397. var engine = scene.getEngine();
  46398. var maxSize = engine.getCaps().maxTextureSize;
  46399. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  46400. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  46401. var desiredWidth = this._options.width || requiredWidth;
  46402. var desiredHeight = this._options.height || requiredHeight;
  46403. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  46404. if (!this._options.width) {
  46405. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  46406. }
  46407. if (!this._options.height) {
  46408. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  46409. }
  46410. }
  46411. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  46412. if (this._textures.length > 0) {
  46413. for (var i = 0; i < this._textures.length; i++) {
  46414. this._engine._releaseTexture(this._textures.data[i]);
  46415. }
  46416. this._textures.reset();
  46417. }
  46418. this.width = desiredWidth;
  46419. this.height = desiredHeight;
  46420. var textureSize = { width: this.width, height: this.height };
  46421. var textureOptions = {
  46422. generateMipMaps: false,
  46423. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  46424. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  46425. samplingMode: this.renderTargetSamplingMode,
  46426. type: this._textureType
  46427. };
  46428. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  46429. if (this._reusable) {
  46430. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  46431. }
  46432. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  46433. this.onSizeChangedObservable.notifyObservers(this);
  46434. }
  46435. this._textures.forEach(function (texture) {
  46436. if (texture.samples !== _this.samples) {
  46437. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  46438. }
  46439. });
  46440. }
  46441. var target;
  46442. if (this._shareOutputWithPostProcess) {
  46443. target = this._shareOutputWithPostProcess.outputTexture;
  46444. }
  46445. else if (this._forcedOutputTexture) {
  46446. target = this._forcedOutputTexture;
  46447. this.width = this._forcedOutputTexture.width;
  46448. this.height = this._forcedOutputTexture.height;
  46449. }
  46450. else {
  46451. target = this.outputTexture;
  46452. }
  46453. if (this.enablePixelPerfectMode) {
  46454. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  46455. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  46456. }
  46457. else {
  46458. this._scaleRatio.copyFromFloats(1, 1);
  46459. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  46460. }
  46461. this.onActivateObservable.notifyObservers(camera);
  46462. // Clear
  46463. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  46464. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  46465. }
  46466. if (this._reusable) {
  46467. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  46468. }
  46469. };
  46470. Object.defineProperty(PostProcess.prototype, "isSupported", {
  46471. get: function () {
  46472. return this._effect.isSupported;
  46473. },
  46474. enumerable: true,
  46475. configurable: true
  46476. });
  46477. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  46478. get: function () {
  46479. if (this._shareOutputWithPostProcess) {
  46480. return this._shareOutputWithPostProcess.aspectRatio;
  46481. }
  46482. if (this._forcedOutputTexture) {
  46483. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  46484. }
  46485. return this.width / this.height;
  46486. },
  46487. enumerable: true,
  46488. configurable: true
  46489. });
  46490. PostProcess.prototype.apply = function () {
  46491. // Check
  46492. if (!this._effect || !this._effect.isReady())
  46493. return null;
  46494. // States
  46495. this._engine.enableEffect(this._effect);
  46496. this._engine.setState(false);
  46497. this._engine.setDepthBuffer(false);
  46498. this._engine.setDepthWrite(false);
  46499. // Alpha
  46500. this._engine.setAlphaMode(this.alphaMode);
  46501. if (this.alphaConstants) {
  46502. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  46503. }
  46504. // Texture
  46505. var source;
  46506. if (this._shareOutputWithPostProcess) {
  46507. source = this._shareOutputWithPostProcess.outputTexture;
  46508. }
  46509. else if (this._forcedOutputTexture) {
  46510. source = this._forcedOutputTexture;
  46511. }
  46512. else {
  46513. source = this.outputTexture;
  46514. }
  46515. this._effect._bindTexture("textureSampler", source);
  46516. // Parameters
  46517. this._effect.setVector2("scale", this._scaleRatio);
  46518. this.onApplyObservable.notifyObservers(this._effect);
  46519. return this._effect;
  46520. };
  46521. PostProcess.prototype._disposeTextures = function () {
  46522. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  46523. return;
  46524. }
  46525. if (this._textures.length > 0) {
  46526. for (var i = 0; i < this._textures.length; i++) {
  46527. this._engine._releaseTexture(this._textures.data[i]);
  46528. }
  46529. }
  46530. this._textures.dispose();
  46531. };
  46532. PostProcess.prototype.dispose = function (camera) {
  46533. camera = camera || this._camera;
  46534. this._disposeTextures();
  46535. if (this._scene) {
  46536. var index_1 = this._scene.postProcesses.indexOf(this);
  46537. if (index_1 !== -1) {
  46538. this._scene.postProcesses.splice(index_1, 1);
  46539. }
  46540. }
  46541. else {
  46542. var index_2 = this._engine.postProcesses.indexOf(this);
  46543. if (index_2 !== -1) {
  46544. this._engine.postProcesses.splice(index_2, 1);
  46545. }
  46546. }
  46547. if (!camera) {
  46548. return;
  46549. }
  46550. camera.detachPostProcess(this);
  46551. var index = camera._postProcesses.indexOf(this);
  46552. if (index === 0 && camera._postProcesses.length > 0) {
  46553. this._camera._postProcesses[0].markTextureDirty();
  46554. }
  46555. this.onActivateObservable.clear();
  46556. this.onAfterRenderObservable.clear();
  46557. this.onApplyObservable.clear();
  46558. this.onBeforeRenderObservable.clear();
  46559. this.onSizeChangedObservable.clear();
  46560. };
  46561. return PostProcess;
  46562. }());
  46563. BABYLON.PostProcess = PostProcess;
  46564. })(BABYLON || (BABYLON = {}));
  46565. //# sourceMappingURL=babylon.postProcess.js.map
  46566. var BABYLON;
  46567. (function (BABYLON) {
  46568. var PassPostProcess = (function (_super) {
  46569. __extends(PassPostProcess, _super);
  46570. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  46571. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46572. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  46573. }
  46574. return PassPostProcess;
  46575. }(BABYLON.PostProcess));
  46576. BABYLON.PassPostProcess = PassPostProcess;
  46577. })(BABYLON || (BABYLON = {}));
  46578. //# sourceMappingURL=babylon.passPostProcess.js.map
  46579. var BABYLON;
  46580. (function (BABYLON) {
  46581. var ShadowGenerator = (function () {
  46582. /**
  46583. * Creates a ShadowGenerator object.
  46584. * A ShadowGenerator is the required tool to use the shadows.
  46585. * Each light casting shadows needs to use its own ShadowGenerator.
  46586. * Required parameters :
  46587. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  46588. * - `light`: the light object generating the shadows.
  46589. * - `useFullFloatFirst`: by default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  46590. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  46591. */
  46592. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  46593. // Members
  46594. this._bias = 0.00005;
  46595. this._blurBoxOffset = 1;
  46596. this._blurScale = 2;
  46597. this._blurKernel = 1;
  46598. this._useKernelBlur = false;
  46599. this._filter = ShadowGenerator.FILTER_NONE;
  46600. this._darkness = 0;
  46601. this._transparencyShadow = false;
  46602. /**
  46603. * Controls the extent to which the shadows fade out at the edge of the frustum
  46604. * Used only by directionals and spots
  46605. */
  46606. this.frustumEdgeFalloff = 0;
  46607. this.forceBackFacesOnly = false;
  46608. this._lightDirection = BABYLON.Vector3.Zero();
  46609. this._viewMatrix = BABYLON.Matrix.Zero();
  46610. this._projectionMatrix = BABYLON.Matrix.Zero();
  46611. this._transformMatrix = BABYLON.Matrix.Zero();
  46612. this._worldViewProjection = BABYLON.Matrix.Zero();
  46613. this._currentFaceIndex = 0;
  46614. this._currentFaceIndexCache = 0;
  46615. this._isCube = false;
  46616. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  46617. this._mapSize = mapSize;
  46618. this._light = light;
  46619. this._scene = light.getScene();
  46620. light._shadowGenerator = this;
  46621. // Texture type fallback from float to int if not supported.
  46622. var caps = this._scene.getEngine().getCaps();
  46623. if (!useFullFloatFirst) {
  46624. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  46625. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46626. }
  46627. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  46628. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46629. }
  46630. else {
  46631. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46632. }
  46633. }
  46634. else {
  46635. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  46636. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46637. }
  46638. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  46639. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46640. }
  46641. else {
  46642. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46643. }
  46644. }
  46645. this._initializeGenerator();
  46646. }
  46647. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  46648. // Static
  46649. get: function () {
  46650. return ShadowGenerator._FILTER_NONE;
  46651. },
  46652. enumerable: true,
  46653. configurable: true
  46654. });
  46655. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  46656. get: function () {
  46657. return ShadowGenerator._FILTER_POISSONSAMPLING;
  46658. },
  46659. enumerable: true,
  46660. configurable: true
  46661. });
  46662. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  46663. get: function () {
  46664. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  46665. },
  46666. enumerable: true,
  46667. configurable: true
  46668. });
  46669. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  46670. get: function () {
  46671. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  46672. },
  46673. enumerable: true,
  46674. configurable: true
  46675. });
  46676. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  46677. get: function () {
  46678. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  46679. },
  46680. enumerable: true,
  46681. configurable: true
  46682. });
  46683. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  46684. get: function () {
  46685. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  46686. },
  46687. enumerable: true,
  46688. configurable: true
  46689. });
  46690. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  46691. get: function () {
  46692. return this._bias;
  46693. },
  46694. set: function (bias) {
  46695. this._bias = bias;
  46696. },
  46697. enumerable: true,
  46698. configurable: true
  46699. });
  46700. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  46701. get: function () {
  46702. return this._blurBoxOffset;
  46703. },
  46704. set: function (value) {
  46705. if (this._blurBoxOffset === value) {
  46706. return;
  46707. }
  46708. this._blurBoxOffset = value;
  46709. this._disposeBlurPostProcesses();
  46710. },
  46711. enumerable: true,
  46712. configurable: true
  46713. });
  46714. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  46715. get: function () {
  46716. return this._blurScale;
  46717. },
  46718. set: function (value) {
  46719. if (this._blurScale === value) {
  46720. return;
  46721. }
  46722. this._blurScale = value;
  46723. this._disposeBlurPostProcesses();
  46724. },
  46725. enumerable: true,
  46726. configurable: true
  46727. });
  46728. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  46729. get: function () {
  46730. return this._blurKernel;
  46731. },
  46732. set: function (value) {
  46733. if (this._blurKernel === value) {
  46734. return;
  46735. }
  46736. this._blurKernel = value;
  46737. this._disposeBlurPostProcesses();
  46738. },
  46739. enumerable: true,
  46740. configurable: true
  46741. });
  46742. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  46743. get: function () {
  46744. return this._useKernelBlur;
  46745. },
  46746. set: function (value) {
  46747. if (this._useKernelBlur === value) {
  46748. return;
  46749. }
  46750. this._useKernelBlur = value;
  46751. this._disposeBlurPostProcesses();
  46752. },
  46753. enumerable: true,
  46754. configurable: true
  46755. });
  46756. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  46757. get: function () {
  46758. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  46759. },
  46760. set: function (value) {
  46761. this._depthScale = value;
  46762. },
  46763. enumerable: true,
  46764. configurable: true
  46765. });
  46766. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  46767. get: function () {
  46768. return this._filter;
  46769. },
  46770. set: function (value) {
  46771. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  46772. if (this._light.needCube()) {
  46773. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  46774. this.useExponentialShadowMap = true;
  46775. return;
  46776. }
  46777. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  46778. this.useCloseExponentialShadowMap = true;
  46779. return;
  46780. }
  46781. }
  46782. if (this._filter === value) {
  46783. return;
  46784. }
  46785. this._filter = value;
  46786. this._disposeBlurPostProcesses();
  46787. this._applyFilterValues();
  46788. this._light._markMeshesAsLightDirty();
  46789. },
  46790. enumerable: true,
  46791. configurable: true
  46792. });
  46793. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  46794. get: function () {
  46795. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  46796. },
  46797. set: function (value) {
  46798. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  46799. return;
  46800. }
  46801. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  46802. },
  46803. enumerable: true,
  46804. configurable: true
  46805. });
  46806. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  46807. get: function () {
  46808. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46809. return this.useExponentialShadowMap;
  46810. },
  46811. set: function (value) {
  46812. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46813. this.useExponentialShadowMap = value;
  46814. },
  46815. enumerable: true,
  46816. configurable: true
  46817. });
  46818. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  46819. get: function () {
  46820. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46821. return this.useBlurExponentialShadowMap;
  46822. },
  46823. set: function (value) {
  46824. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46825. this.useBlurExponentialShadowMap = value;
  46826. },
  46827. enumerable: true,
  46828. configurable: true
  46829. });
  46830. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  46831. get: function () {
  46832. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  46833. },
  46834. set: function (value) {
  46835. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  46836. return;
  46837. }
  46838. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46839. },
  46840. enumerable: true,
  46841. configurable: true
  46842. });
  46843. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  46844. get: function () {
  46845. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  46846. },
  46847. set: function (value) {
  46848. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  46849. return;
  46850. }
  46851. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46852. },
  46853. enumerable: true,
  46854. configurable: true
  46855. });
  46856. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  46857. get: function () {
  46858. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  46859. },
  46860. set: function (value) {
  46861. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  46862. return;
  46863. }
  46864. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46865. },
  46866. enumerable: true,
  46867. configurable: true
  46868. });
  46869. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  46870. get: function () {
  46871. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  46872. },
  46873. set: function (value) {
  46874. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  46875. return;
  46876. }
  46877. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46878. },
  46879. enumerable: true,
  46880. configurable: true
  46881. });
  46882. /**
  46883. * Returns the darkness value (float).
  46884. */
  46885. ShadowGenerator.prototype.getDarkness = function () {
  46886. return this._darkness;
  46887. };
  46888. /**
  46889. * Sets the ShadowGenerator darkness value (float <= 1.0).
  46890. * Returns the ShadowGenerator.
  46891. */
  46892. ShadowGenerator.prototype.setDarkness = function (darkness) {
  46893. if (darkness >= 1.0)
  46894. this._darkness = 1.0;
  46895. else if (darkness <= 0.0)
  46896. this._darkness = 0.0;
  46897. else
  46898. this._darkness = darkness;
  46899. return this;
  46900. };
  46901. /**
  46902. * Sets the ability to have transparent shadow (boolean).
  46903. * Returns the ShadowGenerator.
  46904. */
  46905. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  46906. this._transparencyShadow = hasShadow;
  46907. return this;
  46908. };
  46909. /**
  46910. * Returns a RenderTargetTexture object : the shadow map texture.
  46911. */
  46912. ShadowGenerator.prototype.getShadowMap = function () {
  46913. return this._shadowMap;
  46914. };
  46915. /**
  46916. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  46917. */
  46918. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  46919. if (this._shadowMap2) {
  46920. return this._shadowMap2;
  46921. }
  46922. return this._shadowMap;
  46923. };
  46924. /**
  46925. * Returns the associated light object.
  46926. */
  46927. ShadowGenerator.prototype.getLight = function () {
  46928. return this._light;
  46929. };
  46930. ShadowGenerator.prototype._initializeGenerator = function () {
  46931. this._light._markMeshesAsLightDirty();
  46932. this._initializeShadowMap();
  46933. };
  46934. ShadowGenerator.prototype._initializeShadowMap = function () {
  46935. var _this = this;
  46936. // Render target
  46937. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  46938. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46939. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46940. this._shadowMap.anisotropicFilteringLevel = 1;
  46941. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46942. this._shadowMap.renderParticles = false;
  46943. // Record Face Index before render.
  46944. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  46945. _this._currentFaceIndex = faceIndex;
  46946. });
  46947. // Custom render function.
  46948. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  46949. // Blur if required afer render.
  46950. this._shadowMap.onAfterUnbindObservable.add(function () {
  46951. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  46952. return;
  46953. }
  46954. if (!_this._blurPostProcesses) {
  46955. _this._initializeBlurRTTAndPostProcesses();
  46956. }
  46957. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  46958. });
  46959. // Clear according to the chosen filter.
  46960. this._shadowMap.onClearObservable.add(function (engine) {
  46961. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  46962. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  46963. }
  46964. else {
  46965. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46966. }
  46967. });
  46968. };
  46969. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  46970. var _this = this;
  46971. var engine = this._scene.getEngine();
  46972. var targetSize = this._mapSize / this.blurScale;
  46973. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  46974. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  46975. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46976. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46977. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46978. }
  46979. if (this.useKernelBlur) {
  46980. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  46981. this._kernelBlurXPostprocess.width = targetSize;
  46982. this._kernelBlurXPostprocess.height = targetSize;
  46983. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  46984. effect.setTexture("textureSampler", _this._shadowMap);
  46985. });
  46986. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  46987. this._kernelBlurXPostprocess.autoClear = false;
  46988. this._kernelBlurYPostprocess.autoClear = false;
  46989. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46990. this._kernelBlurXPostprocess.packedFloat = true;
  46991. this._kernelBlurYPostprocess.packedFloat = true;
  46992. }
  46993. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  46994. }
  46995. else {
  46996. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  46997. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  46998. effect.setFloat2("screenSize", targetSize, targetSize);
  46999. effect.setTexture("textureSampler", _this._shadowMap);
  47000. });
  47001. this._boxBlurPostprocess.autoClear = false;
  47002. this._blurPostProcesses = [this._boxBlurPostprocess];
  47003. }
  47004. };
  47005. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47006. var index;
  47007. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47008. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  47009. }
  47010. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47011. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  47012. }
  47013. if (this._transparencyShadow) {
  47014. for (index = 0; index < transparentSubMeshes.length; index++) {
  47015. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  47016. }
  47017. }
  47018. };
  47019. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  47020. var _this = this;
  47021. var mesh = subMesh.getRenderingMesh();
  47022. var scene = this._scene;
  47023. var engine = scene.getEngine();
  47024. // Culling
  47025. engine.setState(subMesh.getMaterial().backFaceCulling);
  47026. // Managing instances
  47027. var batch = mesh._getInstancesRenderList(subMesh._id);
  47028. if (batch.mustReturn) {
  47029. return;
  47030. }
  47031. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47032. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  47033. engine.enableEffect(this._effect);
  47034. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47035. var material = subMesh.getMaterial();
  47036. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  47037. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  47038. this._effect.setVector3("lightPosition", this.getLight().position);
  47039. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  47040. // Alpha test
  47041. if (material && material.needAlphaTesting()) {
  47042. var alphaTexture = material.getAlphaTestTexture();
  47043. if (alphaTexture) {
  47044. this._effect.setTexture("diffuseSampler", alphaTexture);
  47045. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  47046. }
  47047. }
  47048. // Bones
  47049. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47050. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47051. }
  47052. if (this.forceBackFacesOnly) {
  47053. engine.setState(true, 0, false, true);
  47054. }
  47055. // Draw
  47056. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47057. if (this.forceBackFacesOnly) {
  47058. engine.setState(true, 0, false, false);
  47059. }
  47060. }
  47061. else {
  47062. // Need to reset refresh rate of the shadowMap
  47063. this._shadowMap.resetRefreshCounter();
  47064. }
  47065. };
  47066. ShadowGenerator.prototype._applyFilterValues = function () {
  47067. if (this.filter === ShadowGenerator.FILTER_NONE) {
  47068. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  47069. }
  47070. else {
  47071. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47072. }
  47073. };
  47074. /**
  47075. * Force shader compilation including textures ready check
  47076. */
  47077. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  47078. var _this = this;
  47079. var scene = this._scene;
  47080. var engine = scene.getEngine();
  47081. var subMeshes = new Array();
  47082. var currentIndex = 0;
  47083. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  47084. var mesh = _a[_i];
  47085. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  47086. }
  47087. var checkReady = function () {
  47088. if (!_this._scene || !_this._scene.getEngine()) {
  47089. return;
  47090. }
  47091. var subMesh = subMeshes[currentIndex];
  47092. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  47093. currentIndex++;
  47094. if (currentIndex >= subMeshes.length) {
  47095. if (onCompiled) {
  47096. onCompiled(_this);
  47097. }
  47098. return;
  47099. }
  47100. }
  47101. setTimeout(checkReady, 16);
  47102. };
  47103. if (subMeshes.length > 0) {
  47104. checkReady();
  47105. }
  47106. };
  47107. /**
  47108. * Boolean : true when the ShadowGenerator is finally computed.
  47109. */
  47110. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  47111. var defines = [];
  47112. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47113. defines.push("#define FLOAT");
  47114. }
  47115. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47116. defines.push("#define ESM");
  47117. }
  47118. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47119. var mesh = subMesh.getMesh();
  47120. var material = subMesh.getMaterial();
  47121. // Alpha test
  47122. if (material && material.needAlphaTesting()) {
  47123. var alphaTexture = material.getAlphaTestTexture();
  47124. if (alphaTexture) {
  47125. defines.push("#define ALPHATEST");
  47126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47127. attribs.push(BABYLON.VertexBuffer.UVKind);
  47128. defines.push("#define UV1");
  47129. }
  47130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47131. if (alphaTexture.coordinatesIndex === 1) {
  47132. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47133. defines.push("#define UV2");
  47134. }
  47135. }
  47136. }
  47137. }
  47138. // Bones
  47139. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47142. if (mesh.numBoneInfluencers > 4) {
  47143. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47144. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47145. }
  47146. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47147. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47148. }
  47149. else {
  47150. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47151. }
  47152. // Instances
  47153. if (useInstances) {
  47154. defines.push("#define INSTANCES");
  47155. attribs.push("world0");
  47156. attribs.push("world1");
  47157. attribs.push("world2");
  47158. attribs.push("world3");
  47159. }
  47160. // Get correct effect
  47161. var join = defines.join("\n");
  47162. if (this._cachedDefines !== join) {
  47163. this._cachedDefines = join;
  47164. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  47165. }
  47166. return this._effect.isReady();
  47167. };
  47168. /**
  47169. * This creates the defines related to the standard BJS materials.
  47170. */
  47171. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  47172. var scene = this._scene;
  47173. var light = this._light;
  47174. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47175. return;
  47176. }
  47177. defines["SHADOW" + lightIndex] = true;
  47178. if (this.usePoissonSampling) {
  47179. defines["SHADOWPCF" + lightIndex] = true;
  47180. }
  47181. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47182. defines["SHADOWESM" + lightIndex] = true;
  47183. }
  47184. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  47185. defines["SHADOWCLOSEESM" + lightIndex] = true;
  47186. }
  47187. if (light.needCube()) {
  47188. defines["SHADOWCUBE" + lightIndex] = true;
  47189. }
  47190. };
  47191. /**
  47192. * This binds shadow lights related to the standard BJS materials.
  47193. * It implies the unifroms available on the materials are the standard BJS ones.
  47194. */
  47195. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  47196. var light = this._light;
  47197. var scene = this._scene;
  47198. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47199. return;
  47200. }
  47201. if (!light.needCube()) {
  47202. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  47203. }
  47204. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  47205. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  47206. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  47207. };
  47208. // Methods
  47209. /**
  47210. * Returns a Matrix object : the updated transformation matrix.
  47211. */
  47212. ShadowGenerator.prototype.getTransformMatrix = function () {
  47213. var scene = this._scene;
  47214. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  47215. return this._transformMatrix;
  47216. }
  47217. this._currentRenderID = scene.getRenderId();
  47218. this._currentFaceIndexCache = this._currentFaceIndex;
  47219. var lightPosition = this._light.position;
  47220. if (this._light.computeTransformedInformation()) {
  47221. lightPosition = this._light.transformedPosition;
  47222. }
  47223. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  47224. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  47225. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  47226. }
  47227. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  47228. this._cachedPosition = lightPosition.clone();
  47229. this._cachedDirection = this._lightDirection.clone();
  47230. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  47231. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  47232. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  47233. }
  47234. return this._transformMatrix;
  47235. };
  47236. ShadowGenerator.prototype.recreateShadowMap = function () {
  47237. // Track render list.
  47238. var renderList = this._shadowMap.renderList;
  47239. // Clean up existing data.
  47240. this._disposeRTTandPostProcesses();
  47241. // Reinitializes.
  47242. this._initializeGenerator();
  47243. // Reaffect the filter to ensure a correct fallback if necessary.
  47244. this.filter = this.filter;
  47245. // Reaffect the filter.
  47246. this._applyFilterValues();
  47247. // Reaffect Render List.
  47248. this._shadowMap.renderList = renderList;
  47249. };
  47250. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  47251. if (this._shadowMap2) {
  47252. this._shadowMap2.dispose();
  47253. this._shadowMap2 = null;
  47254. }
  47255. if (this._downSamplePostprocess) {
  47256. this._downSamplePostprocess.dispose();
  47257. this._downSamplePostprocess = null;
  47258. }
  47259. if (this._boxBlurPostprocess) {
  47260. this._boxBlurPostprocess.dispose();
  47261. this._boxBlurPostprocess = null;
  47262. }
  47263. if (this._kernelBlurXPostprocess) {
  47264. this._kernelBlurXPostprocess.dispose();
  47265. this._kernelBlurXPostprocess = null;
  47266. }
  47267. if (this._kernelBlurYPostprocess) {
  47268. this._kernelBlurYPostprocess.dispose();
  47269. this._kernelBlurYPostprocess = null;
  47270. }
  47271. this._blurPostProcesses = null;
  47272. };
  47273. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  47274. if (this._shadowMap) {
  47275. this._shadowMap.dispose();
  47276. this._shadowMap = null;
  47277. }
  47278. this._disposeBlurPostProcesses();
  47279. };
  47280. /**
  47281. * Disposes the ShadowGenerator.
  47282. * Returns nothing.
  47283. */
  47284. ShadowGenerator.prototype.dispose = function () {
  47285. this._disposeRTTandPostProcesses();
  47286. this._light._shadowGenerator = null;
  47287. this._light._markMeshesAsLightDirty();
  47288. };
  47289. /**
  47290. * Serializes the ShadowGenerator and returns a serializationObject.
  47291. */
  47292. ShadowGenerator.prototype.serialize = function () {
  47293. var serializationObject = {};
  47294. var shadowMap = this.getShadowMap();
  47295. serializationObject.lightId = this._light.id;
  47296. serializationObject.mapSize = shadowMap.getRenderSize();
  47297. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  47298. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  47299. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47300. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47301. serializationObject.usePoissonSampling = this.usePoissonSampling;
  47302. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  47303. serializationObject.depthScale = this.depthScale;
  47304. serializationObject.darkness = this.getDarkness();
  47305. serializationObject.blurBoxOffset = this.blurBoxOffset;
  47306. serializationObject.blurKernel = this.blurKernel;
  47307. serializationObject.blurScale = this.blurScale;
  47308. serializationObject.useKernelBlur = this.useKernelBlur;
  47309. serializationObject.transparencyShadow = this._transparencyShadow;
  47310. serializationObject.renderList = [];
  47311. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  47312. var mesh = shadowMap.renderList[meshIndex];
  47313. serializationObject.renderList.push(mesh.id);
  47314. }
  47315. return serializationObject;
  47316. };
  47317. /**
  47318. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  47319. */
  47320. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  47321. //casting to point light, as light is missing the position attr and typescript complains.
  47322. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  47323. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  47324. var shadowMap = shadowGenerator.getShadowMap();
  47325. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  47326. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  47327. meshes.forEach(function (mesh) {
  47328. shadowMap.renderList.push(mesh);
  47329. });
  47330. }
  47331. if (parsedShadowGenerator.usePoissonSampling) {
  47332. shadowGenerator.usePoissonSampling = true;
  47333. }
  47334. else if (parsedShadowGenerator.useExponentialShadowMap) {
  47335. shadowGenerator.useExponentialShadowMap = true;
  47336. }
  47337. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47338. shadowGenerator.useBlurExponentialShadowMap = true;
  47339. }
  47340. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  47341. shadowGenerator.useCloseExponentialShadowMap = true;
  47342. }
  47343. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47344. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  47345. }
  47346. else if (parsedShadowGenerator.useVarianceShadowMap) {
  47347. shadowGenerator.useExponentialShadowMap = true;
  47348. }
  47349. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  47350. shadowGenerator.useBlurExponentialShadowMap = true;
  47351. }
  47352. if (parsedShadowGenerator.depthScale) {
  47353. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  47354. }
  47355. if (parsedShadowGenerator.blurScale) {
  47356. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  47357. }
  47358. if (parsedShadowGenerator.blurBoxOffset) {
  47359. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  47360. }
  47361. if (parsedShadowGenerator.useKernelBlur) {
  47362. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  47363. }
  47364. if (parsedShadowGenerator.blurKernel) {
  47365. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  47366. }
  47367. if (parsedShadowGenerator.bias !== undefined) {
  47368. shadowGenerator.bias = parsedShadowGenerator.bias;
  47369. }
  47370. if (parsedShadowGenerator.darkness) {
  47371. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  47372. }
  47373. if (parsedShadowGenerator.transparencyShadow) {
  47374. shadowGenerator.setTransparencyShadow(true);
  47375. }
  47376. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  47377. return shadowGenerator;
  47378. };
  47379. ShadowGenerator._FILTER_NONE = 0;
  47380. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  47381. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  47382. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  47383. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  47384. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  47385. return ShadowGenerator;
  47386. }());
  47387. BABYLON.ShadowGenerator = ShadowGenerator;
  47388. })(BABYLON || (BABYLON = {}));
  47389. //# sourceMappingURL=babylon.shadowGenerator.js.map
  47390. var BABYLON;
  47391. (function (BABYLON) {
  47392. var DefaultLoadingScreen = (function () {
  47393. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  47394. if (_loadingText === void 0) { _loadingText = ""; }
  47395. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  47396. var _this = this;
  47397. this._renderingCanvas = _renderingCanvas;
  47398. this._loadingText = _loadingText;
  47399. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  47400. // Resize
  47401. this._resizeLoadingUI = function () {
  47402. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  47403. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  47404. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  47405. _this._loadingDiv.style.left = canvasRect.left + "px";
  47406. _this._loadingDiv.style.top = canvasRect.top + "px";
  47407. _this._loadingDiv.style.width = canvasRect.width + "px";
  47408. _this._loadingDiv.style.height = canvasRect.height + "px";
  47409. };
  47410. }
  47411. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  47412. if (this._loadingDiv) {
  47413. // Do not add a loading screen if there is already one
  47414. return;
  47415. }
  47416. this._loadingDiv = document.createElement("div");
  47417. this._loadingDiv.id = "babylonjsLoadingDiv";
  47418. this._loadingDiv.style.opacity = "0";
  47419. this._loadingDiv.style.transition = "opacity 1.5s ease";
  47420. // Loading text
  47421. this._loadingTextDiv = document.createElement("div");
  47422. this._loadingTextDiv.style.position = "absolute";
  47423. this._loadingTextDiv.style.left = "0";
  47424. this._loadingTextDiv.style.top = "50%";
  47425. this._loadingTextDiv.style.marginTop = "80px";
  47426. this._loadingTextDiv.style.width = "100%";
  47427. this._loadingTextDiv.style.height = "20px";
  47428. this._loadingTextDiv.style.fontFamily = "Arial";
  47429. this._loadingTextDiv.style.fontSize = "14px";
  47430. this._loadingTextDiv.style.color = "white";
  47431. this._loadingTextDiv.style.textAlign = "center";
  47432. this._loadingTextDiv.innerHTML = "Loading";
  47433. this._loadingDiv.appendChild(this._loadingTextDiv);
  47434. //set the predefined text
  47435. this._loadingTextDiv.innerHTML = this._loadingText;
  47436. // Generating keyframes
  47437. var style = document.createElement('style');
  47438. style.type = 'text/css';
  47439. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  47440. style.innerHTML = keyFrames;
  47441. document.getElementsByTagName('head')[0].appendChild(style);
  47442. // Loading img
  47443. var imgBack = new Image();
  47444. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  47445. imgBack.style.position = "absolute";
  47446. imgBack.style.left = "50%";
  47447. imgBack.style.top = "50%";
  47448. imgBack.style.marginLeft = "-60px";
  47449. imgBack.style.marginTop = "-60px";
  47450. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  47451. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  47452. imgBack.style.transformOrigin = "50% 50%";
  47453. imgBack.style.webkitTransformOrigin = "50% 50%";
  47454. this._loadingDiv.appendChild(imgBack);
  47455. this._resizeLoadingUI();
  47456. window.addEventListener("resize", this._resizeLoadingUI);
  47457. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47458. document.body.appendChild(this._loadingDiv);
  47459. this._loadingDiv.style.opacity = "1";
  47460. };
  47461. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47462. var _this = this;
  47463. if (!this._loadingDiv) {
  47464. return;
  47465. }
  47466. var onTransitionEnd = function () {
  47467. if (!_this._loadingDiv) {
  47468. return;
  47469. }
  47470. document.body.removeChild(_this._loadingDiv);
  47471. window.removeEventListener("resize", _this._resizeLoadingUI);
  47472. _this._loadingDiv = null;
  47473. };
  47474. this._loadingDiv.style.opacity = "0";
  47475. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47476. };
  47477. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47478. set: function (text) {
  47479. this._loadingText = text;
  47480. if (this._loadingTextDiv) {
  47481. this._loadingTextDiv.innerHTML = this._loadingText;
  47482. }
  47483. },
  47484. enumerable: true,
  47485. configurable: true
  47486. });
  47487. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  47488. get: function () {
  47489. return this._loadingDivBackgroundColor;
  47490. },
  47491. set: function (color) {
  47492. this._loadingDivBackgroundColor = color;
  47493. if (!this._loadingDiv) {
  47494. return;
  47495. }
  47496. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47497. },
  47498. enumerable: true,
  47499. configurable: true
  47500. });
  47501. return DefaultLoadingScreen;
  47502. }());
  47503. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  47504. })(BABYLON || (BABYLON = {}));
  47505. //# sourceMappingURL=babylon.loadingScreen.js.map
  47506. var BABYLON;
  47507. (function (BABYLON) {
  47508. var SceneLoader = (function () {
  47509. function SceneLoader() {
  47510. }
  47511. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  47512. get: function () {
  47513. return 0;
  47514. },
  47515. enumerable: true,
  47516. configurable: true
  47517. });
  47518. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  47519. get: function () {
  47520. return 1;
  47521. },
  47522. enumerable: true,
  47523. configurable: true
  47524. });
  47525. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  47526. get: function () {
  47527. return 2;
  47528. },
  47529. enumerable: true,
  47530. configurable: true
  47531. });
  47532. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  47533. get: function () {
  47534. return 3;
  47535. },
  47536. enumerable: true,
  47537. configurable: true
  47538. });
  47539. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  47540. get: function () {
  47541. return SceneLoader._ForceFullSceneLoadingForIncremental;
  47542. },
  47543. set: function (value) {
  47544. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  47545. },
  47546. enumerable: true,
  47547. configurable: true
  47548. });
  47549. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  47550. get: function () {
  47551. return SceneLoader._ShowLoadingScreen;
  47552. },
  47553. set: function (value) {
  47554. SceneLoader._ShowLoadingScreen = value;
  47555. },
  47556. enumerable: true,
  47557. configurable: true
  47558. });
  47559. Object.defineProperty(SceneLoader, "loggingLevel", {
  47560. get: function () {
  47561. return SceneLoader._loggingLevel;
  47562. },
  47563. set: function (value) {
  47564. SceneLoader._loggingLevel = value;
  47565. },
  47566. enumerable: true,
  47567. configurable: true
  47568. });
  47569. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  47570. get: function () {
  47571. return SceneLoader._CleanBoneMatrixWeights;
  47572. },
  47573. set: function (value) {
  47574. SceneLoader._CleanBoneMatrixWeights = value;
  47575. },
  47576. enumerable: true,
  47577. configurable: true
  47578. });
  47579. SceneLoader._getDefaultPlugin = function () {
  47580. return SceneLoader._registeredPlugins[".babylon"];
  47581. };
  47582. SceneLoader._getPluginForExtension = function (extension) {
  47583. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  47584. if (registeredPlugin) {
  47585. return registeredPlugin;
  47586. }
  47587. return SceneLoader._getDefaultPlugin();
  47588. };
  47589. SceneLoader._getPluginForDirectLoad = function (data) {
  47590. for (var extension in SceneLoader._registeredPlugins) {
  47591. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  47592. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  47593. return SceneLoader._registeredPlugins[extension];
  47594. }
  47595. }
  47596. return SceneLoader._getDefaultPlugin();
  47597. };
  47598. SceneLoader._getPluginForFilename = function (sceneFilename) {
  47599. if (sceneFilename.name) {
  47600. sceneFilename = sceneFilename.name;
  47601. }
  47602. var dotPosition = sceneFilename.lastIndexOf(".");
  47603. var queryStringPosition = sceneFilename.indexOf("?");
  47604. if (queryStringPosition === -1) {
  47605. queryStringPosition = sceneFilename.length;
  47606. }
  47607. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  47608. return SceneLoader._getPluginForExtension(extension);
  47609. };
  47610. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  47611. SceneLoader._getDirectLoad = function (sceneFilename) {
  47612. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  47613. return sceneFilename.substr(5);
  47614. }
  47615. return null;
  47616. };
  47617. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47618. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47619. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  47620. var plugin = registeredPlugin.plugin;
  47621. var useArrayBuffer = registeredPlugin.isBinary;
  47622. var database;
  47623. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  47624. var dataCallback = function (data) {
  47625. if (scene.isDisposed) {
  47626. onError("Scene has been disposed");
  47627. return;
  47628. }
  47629. scene.database = database;
  47630. try {
  47631. onSuccess(plugin, data);
  47632. }
  47633. catch (e) {
  47634. onError(null, e);
  47635. }
  47636. };
  47637. var manifestChecked = function (success) {
  47638. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  47639. onError(request.status + " " + request.statusText);
  47640. });
  47641. };
  47642. if (directLoad) {
  47643. dataCallback(directLoad);
  47644. return;
  47645. }
  47646. if (rootUrl.indexOf("file:") === -1) {
  47647. if (scene.getEngine().enableOfflineSupport) {
  47648. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47649. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47650. }
  47651. else {
  47652. manifestChecked(true);
  47653. }
  47654. }
  47655. else {
  47656. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  47657. }
  47658. };
  47659. // Public functions
  47660. SceneLoader.GetPluginForExtension = function (extension) {
  47661. return SceneLoader._getPluginForExtension(extension).plugin;
  47662. };
  47663. SceneLoader.RegisterPlugin = function (plugin) {
  47664. if (typeof plugin.extensions === "string") {
  47665. var extension = plugin.extensions;
  47666. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47667. plugin: plugin,
  47668. isBinary: false
  47669. };
  47670. }
  47671. else {
  47672. var extensions = plugin.extensions;
  47673. Object.keys(extensions).forEach(function (extension) {
  47674. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47675. plugin: plugin,
  47676. isBinary: extensions[extension].isBinary
  47677. };
  47678. });
  47679. }
  47680. };
  47681. /**
  47682. * Import meshes into a scene
  47683. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  47684. * @param rootUrl a string that defines the root url for scene and resources
  47685. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47686. * @param scene the instance of BABYLON.Scene to append to
  47687. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  47688. * @param onProgress a callback with a progress event for each file being loaded
  47689. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47690. */
  47691. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47692. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47693. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47694. return;
  47695. }
  47696. var loadingToken = {};
  47697. scene._addPendingData(loadingToken);
  47698. var errorHandler = function (message, exception) {
  47699. if (onError) {
  47700. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47701. }
  47702. scene._removePendingData(loadingToken);
  47703. };
  47704. var progressHandler = function (event) {
  47705. if (onProgress) {
  47706. onProgress(event);
  47707. }
  47708. };
  47709. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47710. if (plugin.importMesh) {
  47711. var syncedPlugin = plugin;
  47712. var meshes = [];
  47713. var particleSystems = [];
  47714. var skeletons = [];
  47715. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  47716. return;
  47717. }
  47718. if (onSuccess) {
  47719. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47720. onSuccess(meshes, particleSystems, skeletons);
  47721. scene._removePendingData(loadingToken);
  47722. }
  47723. }
  47724. else {
  47725. var asyncedPlugin = plugin;
  47726. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47727. if (onSuccess) {
  47728. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47729. onSuccess(meshes, particleSystems, skeletons);
  47730. scene._removePendingData(loadingToken);
  47731. }
  47732. }, progressHandler, errorHandler);
  47733. }
  47734. }, progressHandler, errorHandler);
  47735. };
  47736. /**
  47737. * Load a scene
  47738. * @param rootUrl a string that defines the root url for scene and resources
  47739. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47740. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47741. * @param onSuccess a callback with the scene when import succeeds
  47742. * @param onProgress a callback with a progress event for each file being loaded
  47743. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47744. */
  47745. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  47746. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  47747. };
  47748. /**
  47749. * Append a scene
  47750. * @param rootUrl a string that defines the root url for scene and resources
  47751. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47752. * @param scene is the instance of BABYLON.Scene to append to
  47753. * @param onSuccess a callback with the scene when import succeeds
  47754. * @param onProgress a callback with a progress event for each file being loaded
  47755. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47756. */
  47757. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47758. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47759. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47760. return;
  47761. }
  47762. if (SceneLoader.ShowLoadingScreen) {
  47763. scene.getEngine().displayLoadingUI();
  47764. }
  47765. var loadingToken = {};
  47766. scene._addPendingData(loadingToken);
  47767. var errorHandler = function (message, exception) {
  47768. if (onError) {
  47769. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47770. }
  47771. scene._removePendingData(loadingToken);
  47772. scene.getEngine().hideLoadingUI();
  47773. };
  47774. var progressHandler = function (event) {
  47775. if (onProgress) {
  47776. onProgress(event);
  47777. }
  47778. };
  47779. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47780. if (plugin.load) {
  47781. var syncedPlugin = plugin;
  47782. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  47783. return;
  47784. }
  47785. if (onSuccess) {
  47786. onSuccess(scene);
  47787. }
  47788. scene.loadingPluginName = plugin.name;
  47789. scene._removePendingData(loadingToken);
  47790. }
  47791. else {
  47792. var asyncedPlugin = plugin;
  47793. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47794. if (onSuccess) {
  47795. onSuccess(scene);
  47796. }
  47797. scene.loadingPluginName = plugin.name;
  47798. scene._removePendingData(loadingToken);
  47799. }, progressHandler, errorHandler);
  47800. }
  47801. if (SceneLoader.ShowLoadingScreen) {
  47802. scene.executeWhenReady(function () {
  47803. scene.getEngine().hideLoadingUI();
  47804. });
  47805. }
  47806. }, progressHandler, errorHandler);
  47807. };
  47808. // Flags
  47809. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47810. SceneLoader._ShowLoadingScreen = true;
  47811. SceneLoader._CleanBoneMatrixWeights = false;
  47812. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47813. // Members
  47814. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  47815. SceneLoader._registeredPlugins = {};
  47816. return SceneLoader;
  47817. }());
  47818. BABYLON.SceneLoader = SceneLoader;
  47819. ;
  47820. })(BABYLON || (BABYLON = {}));
  47821. //# sourceMappingURL=babylon.sceneLoader.js.map
  47822. var BABYLON;
  47823. (function (BABYLON) {
  47824. var Internals;
  47825. (function (Internals) {
  47826. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47827. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47828. var parsedMaterial = parsedData.materials[index];
  47829. if (parsedMaterial.id === id) {
  47830. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47831. }
  47832. }
  47833. return null;
  47834. };
  47835. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47836. for (var i in names) {
  47837. if (mesh.name === names[i]) {
  47838. hierarchyIds.push(mesh.id);
  47839. return true;
  47840. }
  47841. }
  47842. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47843. hierarchyIds.push(mesh.id);
  47844. return true;
  47845. }
  47846. return false;
  47847. };
  47848. var logOperation = function (operation, producer) {
  47849. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47850. };
  47851. BABYLON.SceneLoader.RegisterPlugin({
  47852. name: "babylon.js",
  47853. extensions: ".babylon",
  47854. canDirectLoad: function (data) {
  47855. if (data.indexOf("babylon") !== -1) {
  47856. return true;
  47857. }
  47858. return false;
  47859. },
  47860. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  47861. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47862. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47863. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47864. // and avoid problems with multiple concurrent .babylon loads.
  47865. var log = "importMesh has failed JSON parse";
  47866. try {
  47867. var parsedData = JSON.parse(data);
  47868. log = "";
  47869. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47870. if (!meshesNames) {
  47871. meshesNames = null;
  47872. }
  47873. else if (!Array.isArray(meshesNames)) {
  47874. meshesNames = [meshesNames];
  47875. }
  47876. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  47877. var loadedSkeletonsIds = [];
  47878. var loadedMaterialsIds = [];
  47879. var hierarchyIds = [];
  47880. var index;
  47881. var cache;
  47882. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47883. var parsedMesh = parsedData.meshes[index];
  47884. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  47885. if (meshesNames !== null) {
  47886. // Remove found mesh name from list.
  47887. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  47888. }
  47889. //Geometry?
  47890. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  47891. //does the file contain geometries?
  47892. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  47893. //find the correct geometry and add it to the scene
  47894. var found = false;
  47895. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47896. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  47897. return;
  47898. }
  47899. else {
  47900. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47901. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47902. switch (geometryType) {
  47903. case "boxes":
  47904. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47905. break;
  47906. case "spheres":
  47907. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47908. break;
  47909. case "cylinders":
  47910. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47911. break;
  47912. case "toruses":
  47913. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47914. break;
  47915. case "grounds":
  47916. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47917. break;
  47918. case "planes":
  47919. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47920. break;
  47921. case "torusKnots":
  47922. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47923. break;
  47924. case "vertexData":
  47925. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47926. break;
  47927. }
  47928. found = true;
  47929. }
  47930. });
  47931. }
  47932. });
  47933. if (found === false) {
  47934. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47935. }
  47936. }
  47937. }
  47938. // Material ?
  47939. if (parsedMesh.materialId) {
  47940. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47941. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  47942. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47943. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47944. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47945. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47946. var subMatId = parsedMultiMaterial.materials[matIndex];
  47947. loadedMaterialsIds.push(subMatId);
  47948. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47949. log += "\n\tMaterial " + mat.toString(fullDetails);
  47950. }
  47951. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47952. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47953. materialFound = true;
  47954. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47955. break;
  47956. }
  47957. }
  47958. }
  47959. if (materialFound === false) {
  47960. loadedMaterialsIds.push(parsedMesh.materialId);
  47961. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47962. if (!mat) {
  47963. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47964. }
  47965. else {
  47966. log += "\n\tMaterial " + mat.toString(fullDetails);
  47967. }
  47968. }
  47969. }
  47970. // Skeleton ?
  47971. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  47972. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47973. if (skeletonAlreadyLoaded === false) {
  47974. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47975. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47976. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47977. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47978. skeletons.push(skeleton);
  47979. loadedSkeletonsIds.push(parsedSkeleton.id);
  47980. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47981. }
  47982. }
  47983. }
  47984. }
  47985. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47986. meshes.push(mesh);
  47987. log += "\n\tMesh " + mesh.toString(fullDetails);
  47988. }
  47989. }
  47990. // Connecting parents
  47991. var currentMesh;
  47992. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47993. currentMesh = scene.meshes[index];
  47994. if (currentMesh._waitingParentId) {
  47995. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47996. currentMesh._waitingParentId = undefined;
  47997. }
  47998. }
  47999. // freeze and compute world matrix application
  48000. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48001. currentMesh = scene.meshes[index];
  48002. if (currentMesh._waitingFreezeWorldMatrix) {
  48003. currentMesh.freezeWorldMatrix();
  48004. currentMesh._waitingFreezeWorldMatrix = undefined;
  48005. }
  48006. else {
  48007. currentMesh.computeWorldMatrix(true);
  48008. }
  48009. }
  48010. }
  48011. // Particles
  48012. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48013. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48014. var parsedParticleSystem = parsedData.particleSystems[index];
  48015. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  48016. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48017. }
  48018. }
  48019. }
  48020. return true;
  48021. }
  48022. catch (err) {
  48023. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48024. log = null;
  48025. throw err;
  48026. }
  48027. finally {
  48028. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48029. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48030. }
  48031. }
  48032. },
  48033. load: function (scene, data, rootUrl) {
  48034. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48035. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48036. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48037. // and avoid problems with multiple concurrent .babylon loads.
  48038. var log = "importScene has failed JSON parse";
  48039. try {
  48040. var parsedData = JSON.parse(data);
  48041. log = "";
  48042. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48043. // Scene
  48044. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48045. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48046. }
  48047. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48048. scene.autoClear = parsedData.autoClear;
  48049. }
  48050. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48051. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48052. }
  48053. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48054. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48055. }
  48056. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48057. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48058. }
  48059. // Fog
  48060. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48061. scene.fogMode = parsedData.fogMode;
  48062. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48063. scene.fogStart = parsedData.fogStart;
  48064. scene.fogEnd = parsedData.fogEnd;
  48065. scene.fogDensity = parsedData.fogDensity;
  48066. log += "\tFog mode for scene: ";
  48067. switch (scene.fogMode) {
  48068. // getters not compiling, so using hardcoded
  48069. case 1:
  48070. log += "exp\n";
  48071. break;
  48072. case 2:
  48073. log += "exp2\n";
  48074. break;
  48075. case 3:
  48076. log += "linear\n";
  48077. break;
  48078. }
  48079. }
  48080. //Physics
  48081. if (parsedData.physicsEnabled) {
  48082. var physicsPlugin;
  48083. if (parsedData.physicsEngine === "cannon") {
  48084. physicsPlugin = new BABYLON.CannonJSPlugin();
  48085. }
  48086. else if (parsedData.physicsEngine === "oimo") {
  48087. physicsPlugin = new BABYLON.OimoJSPlugin();
  48088. }
  48089. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  48090. //else - default engine, which is currently oimo
  48091. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  48092. scene.enablePhysics(physicsGravity, physicsPlugin);
  48093. }
  48094. // Metadata
  48095. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  48096. scene.metadata = parsedData.metadata;
  48097. }
  48098. //collisions, if defined. otherwise, default is true
  48099. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  48100. scene.collisionsEnabled = parsedData.collisionsEnabled;
  48101. }
  48102. scene.workerCollisions = !!parsedData.workerCollisions;
  48103. var index;
  48104. var cache;
  48105. // Lights
  48106. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  48107. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  48108. var parsedLight = parsedData.lights[index];
  48109. var light = BABYLON.Light.Parse(parsedLight, scene);
  48110. log += (index === 0 ? "\n\tLights:" : "");
  48111. log += "\n\t\t" + light.toString(fullDetails);
  48112. }
  48113. }
  48114. // Animations
  48115. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  48116. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  48117. var parsedAnimation = parsedData.animations[index];
  48118. var animation = BABYLON.Animation.Parse(parsedAnimation);
  48119. scene.animations.push(animation);
  48120. log += (index === 0 ? "\n\tAnimations:" : "");
  48121. log += "\n\t\t" + animation.toString(fullDetails);
  48122. }
  48123. }
  48124. if (parsedData.autoAnimate) {
  48125. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  48126. }
  48127. // Materials
  48128. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  48129. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48130. var parsedMaterial = parsedData.materials[index];
  48131. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48132. log += (index === 0 ? "\n\tMaterials:" : "");
  48133. log += "\n\t\t" + mat.toString(fullDetails);
  48134. }
  48135. }
  48136. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48137. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  48138. var parsedMultiMaterial = parsedData.multiMaterials[index];
  48139. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48140. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  48141. log += "\n\t\t" + mmat.toString(fullDetails);
  48142. }
  48143. }
  48144. // Morph targets
  48145. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  48146. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  48147. var managerData = _a[_i];
  48148. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  48149. }
  48150. }
  48151. // Skeletons
  48152. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48153. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  48154. var parsedSkeleton = parsedData.skeletons[index];
  48155. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48156. log += (index === 0 ? "\n\tSkeletons:" : "");
  48157. log += "\n\t\t" + skeleton.toString(fullDetails);
  48158. }
  48159. }
  48160. // Geometries
  48161. var geometries = parsedData.geometries;
  48162. if (geometries !== undefined && geometries !== null) {
  48163. // Boxes
  48164. var boxes = geometries.boxes;
  48165. if (boxes !== undefined && boxes !== null) {
  48166. for (index = 0, cache = boxes.length; index < cache; index++) {
  48167. var parsedBox = boxes[index];
  48168. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  48169. }
  48170. }
  48171. // Spheres
  48172. var spheres = geometries.spheres;
  48173. if (spheres !== undefined && spheres !== null) {
  48174. for (index = 0, cache = spheres.length; index < cache; index++) {
  48175. var parsedSphere = spheres[index];
  48176. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  48177. }
  48178. }
  48179. // Cylinders
  48180. var cylinders = geometries.cylinders;
  48181. if (cylinders !== undefined && cylinders !== null) {
  48182. for (index = 0, cache = cylinders.length; index < cache; index++) {
  48183. var parsedCylinder = cylinders[index];
  48184. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  48185. }
  48186. }
  48187. // Toruses
  48188. var toruses = geometries.toruses;
  48189. if (toruses !== undefined && toruses !== null) {
  48190. for (index = 0, cache = toruses.length; index < cache; index++) {
  48191. var parsedTorus = toruses[index];
  48192. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  48193. }
  48194. }
  48195. // Grounds
  48196. var grounds = geometries.grounds;
  48197. if (grounds !== undefined && grounds !== null) {
  48198. for (index = 0, cache = grounds.length; index < cache; index++) {
  48199. var parsedGround = grounds[index];
  48200. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  48201. }
  48202. }
  48203. // Planes
  48204. var planes = geometries.planes;
  48205. if (planes !== undefined && planes !== null) {
  48206. for (index = 0, cache = planes.length; index < cache; index++) {
  48207. var parsedPlane = planes[index];
  48208. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  48209. }
  48210. }
  48211. // TorusKnots
  48212. var torusKnots = geometries.torusKnots;
  48213. if (torusKnots !== undefined && torusKnots !== null) {
  48214. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  48215. var parsedTorusKnot = torusKnots[index];
  48216. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  48217. }
  48218. }
  48219. // VertexData
  48220. var vertexData = geometries.vertexData;
  48221. if (vertexData !== undefined && vertexData !== null) {
  48222. for (index = 0, cache = vertexData.length; index < cache; index++) {
  48223. var parsedVertexData = vertexData[index];
  48224. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  48225. }
  48226. }
  48227. }
  48228. // Meshes
  48229. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48230. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48231. var parsedMesh = parsedData.meshes[index];
  48232. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48233. log += (index === 0 ? "\n\tMeshes:" : "");
  48234. log += "\n\t\t" + mesh.toString(fullDetails);
  48235. }
  48236. }
  48237. // Cameras
  48238. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  48239. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  48240. var parsedCamera = parsedData.cameras[index];
  48241. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  48242. log += (index === 0 ? "\n\tCameras:" : "");
  48243. log += "\n\t\t" + camera.toString(fullDetails);
  48244. }
  48245. }
  48246. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  48247. scene.setActiveCameraByID(parsedData.activeCameraID);
  48248. }
  48249. // Browsing all the graph to connect the dots
  48250. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  48251. var camera = scene.cameras[index];
  48252. if (camera._waitingParentId) {
  48253. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  48254. camera._waitingParentId = undefined;
  48255. }
  48256. }
  48257. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48258. var light = scene.lights[index];
  48259. if (light._waitingParentId) {
  48260. light.parent = scene.getLastEntryByID(light._waitingParentId);
  48261. light._waitingParentId = undefined;
  48262. }
  48263. }
  48264. // Sounds
  48265. var loadedSounds = [];
  48266. var loadedSound;
  48267. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  48268. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48269. var parsedSound = parsedData.sounds[index];
  48270. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48271. if (!parsedSound.url)
  48272. parsedSound.url = parsedSound.name;
  48273. if (!loadedSounds[parsedSound.url]) {
  48274. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48275. loadedSounds[parsedSound.url] = loadedSound;
  48276. }
  48277. else {
  48278. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48279. }
  48280. }
  48281. else {
  48282. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48283. }
  48284. }
  48285. }
  48286. loadedSounds = [];
  48287. // Connect parents & children and parse actions
  48288. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48289. var mesh = scene.meshes[index];
  48290. if (mesh._waitingParentId) {
  48291. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  48292. mesh._waitingParentId = undefined;
  48293. }
  48294. if (mesh._waitingActions) {
  48295. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  48296. mesh._waitingActions = undefined;
  48297. }
  48298. }
  48299. // freeze world matrix application
  48300. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48301. var currentMesh = scene.meshes[index];
  48302. if (currentMesh._waitingFreezeWorldMatrix) {
  48303. currentMesh.freezeWorldMatrix();
  48304. currentMesh._waitingFreezeWorldMatrix = undefined;
  48305. }
  48306. else {
  48307. currentMesh.computeWorldMatrix(true);
  48308. }
  48309. }
  48310. // Particles Systems
  48311. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48312. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48313. var parsedParticleSystem = parsedData.particleSystems[index];
  48314. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  48315. }
  48316. }
  48317. // Lens flares
  48318. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  48319. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  48320. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  48321. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  48322. }
  48323. }
  48324. // Shadows
  48325. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  48326. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  48327. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  48328. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  48329. }
  48330. }
  48331. // Lights exclusions / inclusions
  48332. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48333. var light = scene.lights[index];
  48334. // Excluded check
  48335. if (light._excludedMeshesIds.length > 0) {
  48336. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  48337. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  48338. if (excludedMesh) {
  48339. light.excludedMeshes.push(excludedMesh);
  48340. }
  48341. }
  48342. light._excludedMeshesIds = [];
  48343. }
  48344. // Included check
  48345. if (light._includedOnlyMeshesIds.length > 0) {
  48346. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  48347. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  48348. if (includedOnlyMesh) {
  48349. light.includedOnlyMeshes.push(includedOnlyMesh);
  48350. }
  48351. }
  48352. light._includedOnlyMeshesIds = [];
  48353. }
  48354. }
  48355. // Actions (scene)
  48356. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  48357. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  48358. }
  48359. // Finish
  48360. return true;
  48361. }
  48362. catch (err) {
  48363. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  48364. log = null;
  48365. throw err;
  48366. }
  48367. finally {
  48368. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48369. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48370. }
  48371. }
  48372. }
  48373. });
  48374. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48375. })(BABYLON || (BABYLON = {}));
  48376. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  48377. var BABYLON;
  48378. (function (BABYLON) {
  48379. var FilesInput = (function () {
  48380. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  48381. this._engine = engine;
  48382. this._currentScene = scene;
  48383. this._sceneLoadedCallback = sceneLoadedCallback;
  48384. this._progressCallback = progressCallback;
  48385. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  48386. this._textureLoadingCallback = textureLoadingCallback;
  48387. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  48388. this._onReloadCallback = onReloadCallback;
  48389. }
  48390. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  48391. var _this = this;
  48392. if (elementToMonitor) {
  48393. this._elementToMonitor = elementToMonitor;
  48394. this._dragEnterHandler = function (e) { _this.drag(e); };
  48395. this._dragOverHandler = function (e) { _this.drag(e); };
  48396. this._dropHandler = function (e) { _this.drop(e); };
  48397. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  48398. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  48399. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  48400. }
  48401. };
  48402. FilesInput.prototype.dispose = function () {
  48403. if (!this._elementToMonitor) {
  48404. return;
  48405. }
  48406. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  48407. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  48408. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  48409. };
  48410. FilesInput.prototype.renderFunction = function () {
  48411. if (this._additionalRenderLoopLogicCallback) {
  48412. this._additionalRenderLoopLogicCallback();
  48413. }
  48414. if (this._currentScene) {
  48415. if (this._textureLoadingCallback) {
  48416. var remaining = this._currentScene.getWaitingItemsCount();
  48417. if (remaining > 0) {
  48418. this._textureLoadingCallback(remaining);
  48419. }
  48420. }
  48421. this._currentScene.render();
  48422. }
  48423. };
  48424. FilesInput.prototype.drag = function (e) {
  48425. e.stopPropagation();
  48426. e.preventDefault();
  48427. };
  48428. FilesInput.prototype.drop = function (eventDrop) {
  48429. eventDrop.stopPropagation();
  48430. eventDrop.preventDefault();
  48431. this.loadFiles(eventDrop);
  48432. };
  48433. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  48434. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  48435. reader.readEntries(function (fileEntries) {
  48436. var remaining = fileEntries.length;
  48437. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  48438. var fileEntry = fileEntries_1[_i];
  48439. if (fileEntry.isFile) {
  48440. fileEntry.file(function (file) {
  48441. file.correctName = relativePath + file.name;
  48442. files.push(file);
  48443. remaining--;
  48444. if (remaining === 0) {
  48445. callback();
  48446. }
  48447. });
  48448. }
  48449. else {
  48450. remaining--;
  48451. if (remaining === 0) {
  48452. callback();
  48453. }
  48454. }
  48455. }
  48456. });
  48457. };
  48458. FilesInput.prototype._processFiles = function (files) {
  48459. for (var i = 0; i < files.length; i++) {
  48460. var name = files[i].correctName.toLowerCase();
  48461. var extension = name.split('.').pop();
  48462. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48463. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  48464. this._sceneFileToLoad = files[i];
  48465. }
  48466. else {
  48467. FilesInput.FilesToLoad[name] = files[i];
  48468. }
  48469. }
  48470. if (this._onReloadCallback) {
  48471. this._onReloadCallback(this._sceneFileToLoad);
  48472. }
  48473. else {
  48474. this.reload();
  48475. }
  48476. };
  48477. FilesInput.prototype.loadFiles = function (event) {
  48478. var _this = this;
  48479. if (this._startingProcessingFilesCallback)
  48480. this._startingProcessingFilesCallback();
  48481. // Handling data transfer via drag'n'drop
  48482. if (event && event.dataTransfer && event.dataTransfer.files) {
  48483. this._filesToLoad = event.dataTransfer.files;
  48484. }
  48485. // Handling files from input files
  48486. if (event && event.target && event.target.files) {
  48487. this._filesToLoad = event.target.files;
  48488. }
  48489. if (this._filesToLoad && this._filesToLoad.length > 0) {
  48490. var files_1 = [];
  48491. var folders = [];
  48492. var items = event.dataTransfer ? event.dataTransfer.items : null;
  48493. for (var i = 0; i < this._filesToLoad.length; i++) {
  48494. var fileToLoad = this._filesToLoad[i];
  48495. var name_1 = fileToLoad.name.toLowerCase();
  48496. var type = fileToLoad.type;
  48497. var entry = void 0;
  48498. fileToLoad.correctName = name_1;
  48499. if (items) {
  48500. var item = items[i];
  48501. if (item.getAsEntry) {
  48502. entry = item.getAsEntry();
  48503. }
  48504. else if (item.webkitGetAsEntry) {
  48505. entry = item.webkitGetAsEntry();
  48506. }
  48507. }
  48508. if (!entry) {
  48509. files_1.push(fileToLoad);
  48510. }
  48511. else {
  48512. if (entry.isDirectory) {
  48513. folders.push(entry);
  48514. }
  48515. else {
  48516. files_1.push(fileToLoad);
  48517. }
  48518. }
  48519. }
  48520. if (folders.length === 0) {
  48521. this._processFiles(files_1);
  48522. }
  48523. else {
  48524. var remaining = folders.length;
  48525. // Extract folder content
  48526. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  48527. var folder = folders_1[_i];
  48528. this._handleFolderDrop(folder, files_1, function () {
  48529. remaining--;
  48530. if (remaining === 0) {
  48531. _this._processFiles(files_1);
  48532. }
  48533. });
  48534. }
  48535. }
  48536. }
  48537. };
  48538. FilesInput.prototype.reload = function () {
  48539. var _this = this;
  48540. // If a ".babylon" file has been provided
  48541. if (this._sceneFileToLoad) {
  48542. if (this._currentScene) {
  48543. if (BABYLON.Tools.errorsCount > 0) {
  48544. BABYLON.Tools.ClearLogCache();
  48545. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  48546. }
  48547. this._engine.stopRenderLoop();
  48548. this._currentScene.dispose();
  48549. }
  48550. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  48551. _this._currentScene = newScene;
  48552. if (_this._sceneLoadedCallback) {
  48553. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  48554. }
  48555. // Wait for textures and shaders to be ready
  48556. _this._currentScene.executeWhenReady(function () {
  48557. _this._engine.runRenderLoop(function () {
  48558. _this.renderFunction();
  48559. });
  48560. });
  48561. }, function (progress) {
  48562. if (_this._progressCallback) {
  48563. _this._progressCallback(progress);
  48564. }
  48565. });
  48566. }
  48567. else {
  48568. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  48569. }
  48570. };
  48571. FilesInput.FilesToLoad = new Array();
  48572. return FilesInput;
  48573. }());
  48574. BABYLON.FilesInput = FilesInput;
  48575. })(BABYLON || (BABYLON = {}));
  48576. //# sourceMappingURL=babylon.filesInput.js.map
  48577. var BABYLON;
  48578. (function (BABYLON) {
  48579. /**
  48580. * This class implement a typical dictionary using a string as key and the generic type T as value.
  48581. * The underlying implementation relies on an associative array to ensure the best performances.
  48582. * The value can be anything including 'null' but except 'undefined'
  48583. */
  48584. var StringDictionary = (function () {
  48585. function StringDictionary() {
  48586. this._count = 0;
  48587. this._data = {};
  48588. }
  48589. /**
  48590. * This will clear this dictionary and copy the content from the 'source' one.
  48591. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  48592. * @param source the dictionary to take the content from and copy to this dictionary
  48593. */
  48594. StringDictionary.prototype.copyFrom = function (source) {
  48595. var _this = this;
  48596. this.clear();
  48597. source.forEach(function (t, v) { return _this.add(t, v); });
  48598. };
  48599. /**
  48600. * Get a value based from its key
  48601. * @param key the given key to get the matching value from
  48602. * @return the value if found, otherwise undefined is returned
  48603. */
  48604. StringDictionary.prototype.get = function (key) {
  48605. var val = this._data[key];
  48606. if (val !== undefined) {
  48607. return val;
  48608. }
  48609. return undefined;
  48610. };
  48611. /**
  48612. * Get a value from its key or add it if it doesn't exist.
  48613. * This method will ensure you that a given key/data will be present in the dictionary.
  48614. * @param key the given key to get the matching value from
  48615. * @param factory the factory that will create the value if the key is not present in the dictionary.
  48616. * The factory will only be invoked if there's no data for the given key.
  48617. * @return the value corresponding to the key.
  48618. */
  48619. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  48620. var val = this.get(key);
  48621. if (val !== undefined) {
  48622. return val;
  48623. }
  48624. val = factory(key);
  48625. if (val) {
  48626. this.add(key, val);
  48627. }
  48628. return val;
  48629. };
  48630. /**
  48631. * Get a value from its key if present in the dictionary otherwise add it
  48632. * @param key the key to get the value from
  48633. * @param val if there's no such key/value pair in the dictionary add it with this value
  48634. * @return the value corresponding to the key
  48635. */
  48636. StringDictionary.prototype.getOrAdd = function (key, val) {
  48637. var curVal = this.get(key);
  48638. if (curVal !== undefined) {
  48639. return curVal;
  48640. }
  48641. this.add(key, val);
  48642. return val;
  48643. };
  48644. /**
  48645. * Check if there's a given key in the dictionary
  48646. * @param key the key to check for
  48647. * @return true if the key is present, false otherwise
  48648. */
  48649. StringDictionary.prototype.contains = function (key) {
  48650. return this._data[key] !== undefined;
  48651. };
  48652. /**
  48653. * Add a new key and its corresponding value
  48654. * @param key the key to add
  48655. * @param value the value corresponding to the key
  48656. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  48657. */
  48658. StringDictionary.prototype.add = function (key, value) {
  48659. if (this._data[key] !== undefined) {
  48660. return false;
  48661. }
  48662. this._data[key] = value;
  48663. ++this._count;
  48664. return true;
  48665. };
  48666. StringDictionary.prototype.set = function (key, value) {
  48667. if (this._data[key] === undefined) {
  48668. return false;
  48669. }
  48670. this._data[key] = value;
  48671. return true;
  48672. };
  48673. /**
  48674. * Get the element of the given key and remove it from the dictionary
  48675. * @param key
  48676. */
  48677. StringDictionary.prototype.getAndRemove = function (key) {
  48678. var val = this.get(key);
  48679. if (val !== undefined) {
  48680. delete this._data[key];
  48681. --this._count;
  48682. return val;
  48683. }
  48684. return null;
  48685. };
  48686. /**
  48687. * Remove a key/value from the dictionary.
  48688. * @param key the key to remove
  48689. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  48690. */
  48691. StringDictionary.prototype.remove = function (key) {
  48692. if (this.contains(key)) {
  48693. delete this._data[key];
  48694. --this._count;
  48695. return true;
  48696. }
  48697. return false;
  48698. };
  48699. /**
  48700. * Clear the whole content of the dictionary
  48701. */
  48702. StringDictionary.prototype.clear = function () {
  48703. this._data = {};
  48704. this._count = 0;
  48705. };
  48706. Object.defineProperty(StringDictionary.prototype, "count", {
  48707. get: function () {
  48708. return this._count;
  48709. },
  48710. enumerable: true,
  48711. configurable: true
  48712. });
  48713. /**
  48714. * Execute a callback on each key/val of the dictionary.
  48715. * Note that you can remove any element in this dictionary in the callback implementation
  48716. * @param callback the callback to execute on a given key/value pair
  48717. */
  48718. StringDictionary.prototype.forEach = function (callback) {
  48719. for (var cur in this._data) {
  48720. var val = this._data[cur];
  48721. callback(cur, val);
  48722. }
  48723. };
  48724. /**
  48725. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  48726. * If the callback returns null or undefined the method will iterate to the next key/value pair
  48727. * Note that you can remove any element in this dictionary in the callback implementation
  48728. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  48729. */
  48730. StringDictionary.prototype.first = function (callback) {
  48731. for (var cur in this._data) {
  48732. var val = this._data[cur];
  48733. var res = callback(cur, val);
  48734. if (res) {
  48735. return res;
  48736. }
  48737. }
  48738. return null;
  48739. };
  48740. return StringDictionary;
  48741. }());
  48742. BABYLON.StringDictionary = StringDictionary;
  48743. })(BABYLON || (BABYLON = {}));
  48744. //# sourceMappingURL=babylon.stringDictionary.js.map
  48745. var BABYLON;
  48746. (function (BABYLON) {
  48747. var Tags = (function () {
  48748. function Tags() {
  48749. }
  48750. Tags.EnableFor = function (obj) {
  48751. obj._tags = obj._tags || {};
  48752. obj.hasTags = function () {
  48753. return Tags.HasTags(obj);
  48754. };
  48755. obj.addTags = function (tagsString) {
  48756. return Tags.AddTagsTo(obj, tagsString);
  48757. };
  48758. obj.removeTags = function (tagsString) {
  48759. return Tags.RemoveTagsFrom(obj, tagsString);
  48760. };
  48761. obj.matchesTagsQuery = function (tagsQuery) {
  48762. return Tags.MatchesQuery(obj, tagsQuery);
  48763. };
  48764. };
  48765. Tags.DisableFor = function (obj) {
  48766. delete obj._tags;
  48767. delete obj.hasTags;
  48768. delete obj.addTags;
  48769. delete obj.removeTags;
  48770. delete obj.matchesTagsQuery;
  48771. };
  48772. Tags.HasTags = function (obj) {
  48773. if (!obj._tags) {
  48774. return false;
  48775. }
  48776. return !BABYLON.Tools.IsEmpty(obj._tags);
  48777. };
  48778. Tags.GetTags = function (obj, asString) {
  48779. if (asString === void 0) { asString = true; }
  48780. if (!obj._tags) {
  48781. return null;
  48782. }
  48783. if (asString) {
  48784. var tagsArray = [];
  48785. for (var tag in obj._tags) {
  48786. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  48787. tagsArray.push(tag);
  48788. }
  48789. }
  48790. return tagsArray.join(" ");
  48791. }
  48792. else {
  48793. return obj._tags;
  48794. }
  48795. };
  48796. // the tags 'true' and 'false' are reserved and cannot be used as tags
  48797. // a tag cannot start with '||', '&&', and '!'
  48798. // it cannot contain whitespaces
  48799. Tags.AddTagsTo = function (obj, tagsString) {
  48800. if (!tagsString) {
  48801. return;
  48802. }
  48803. if (typeof tagsString !== "string") {
  48804. return;
  48805. }
  48806. var tags = tagsString.split(" ");
  48807. tags.forEach(function (tag, index, array) {
  48808. Tags._AddTagTo(obj, tag);
  48809. });
  48810. };
  48811. Tags._AddTagTo = function (obj, tag) {
  48812. tag = tag.trim();
  48813. if (tag === "" || tag === "true" || tag === "false") {
  48814. return;
  48815. }
  48816. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  48817. return;
  48818. }
  48819. Tags.EnableFor(obj);
  48820. obj._tags[tag] = true;
  48821. };
  48822. Tags.RemoveTagsFrom = function (obj, tagsString) {
  48823. if (!Tags.HasTags(obj)) {
  48824. return;
  48825. }
  48826. var tags = tagsString.split(" ");
  48827. for (var t in tags) {
  48828. Tags._RemoveTagFrom(obj, tags[t]);
  48829. }
  48830. };
  48831. Tags._RemoveTagFrom = function (obj, tag) {
  48832. delete obj._tags[tag];
  48833. };
  48834. Tags.MatchesQuery = function (obj, tagsQuery) {
  48835. if (tagsQuery === undefined) {
  48836. return true;
  48837. }
  48838. if (tagsQuery === "") {
  48839. return Tags.HasTags(obj);
  48840. }
  48841. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  48842. };
  48843. return Tags;
  48844. }());
  48845. BABYLON.Tags = Tags;
  48846. })(BABYLON || (BABYLON = {}));
  48847. //# sourceMappingURL=babylon.tags.js.map
  48848. var BABYLON;
  48849. (function (BABYLON) {
  48850. var Internals;
  48851. (function (Internals) {
  48852. var AndOrNotEvaluator = (function () {
  48853. function AndOrNotEvaluator() {
  48854. }
  48855. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  48856. if (!query.match(/\([^\(\)]*\)/g)) {
  48857. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  48858. }
  48859. else {
  48860. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  48861. // remove parenthesis
  48862. r = r.slice(1, r.length - 1);
  48863. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  48864. });
  48865. }
  48866. if (query === "true") {
  48867. return true;
  48868. }
  48869. if (query === "false") {
  48870. return false;
  48871. }
  48872. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  48873. };
  48874. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  48875. evaluateCallback = evaluateCallback || (function (r) {
  48876. return r === "true" ? true : false;
  48877. });
  48878. var result;
  48879. var or = parenthesisContent.split("||");
  48880. for (var i in or) {
  48881. if (or.hasOwnProperty(i)) {
  48882. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  48883. var and = ori.split("&&");
  48884. if (and.length > 1) {
  48885. for (var j = 0; j < and.length; ++j) {
  48886. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  48887. if (andj !== "true" && andj !== "false") {
  48888. if (andj[0] === "!") {
  48889. result = !evaluateCallback(andj.substring(1));
  48890. }
  48891. else {
  48892. result = evaluateCallback(andj);
  48893. }
  48894. }
  48895. else {
  48896. result = andj === "true" ? true : false;
  48897. }
  48898. if (!result) {
  48899. ori = "false";
  48900. break;
  48901. }
  48902. }
  48903. }
  48904. if (result || ori === "true") {
  48905. result = true;
  48906. break;
  48907. }
  48908. // result equals false (or undefined)
  48909. if (ori !== "true" && ori !== "false") {
  48910. if (ori[0] === "!") {
  48911. result = !evaluateCallback(ori.substring(1));
  48912. }
  48913. else {
  48914. result = evaluateCallback(ori);
  48915. }
  48916. }
  48917. else {
  48918. result = ori === "true" ? true : false;
  48919. }
  48920. }
  48921. }
  48922. // the whole parenthesis scope is replaced by 'true' or 'false'
  48923. return result ? "true" : "false";
  48924. };
  48925. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  48926. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  48927. // remove whitespaces
  48928. r = r.replace(/[\s]/g, function () { return ""; });
  48929. return r.length % 2 ? "!" : "";
  48930. });
  48931. booleanString = booleanString.trim();
  48932. if (booleanString === "!true") {
  48933. booleanString = "false";
  48934. }
  48935. else if (booleanString === "!false") {
  48936. booleanString = "true";
  48937. }
  48938. return booleanString;
  48939. };
  48940. return AndOrNotEvaluator;
  48941. }());
  48942. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  48943. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48944. })(BABYLON || (BABYLON = {}));
  48945. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  48946. var BABYLON;
  48947. (function (BABYLON) {
  48948. var Database = (function () {
  48949. function Database(urlToScene, callbackManifestChecked) {
  48950. // Handling various flavors of prefixed version of IndexedDB
  48951. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  48952. this.callbackManifestChecked = callbackManifestChecked;
  48953. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  48954. this.db = null;
  48955. this.enableSceneOffline = false;
  48956. this.enableTexturesOffline = false;
  48957. this.manifestVersionFound = 0;
  48958. this.mustUpdateRessources = false;
  48959. this.hasReachedQuota = false;
  48960. if (!Database.IDBStorageEnabled) {
  48961. this.callbackManifestChecked(true);
  48962. }
  48963. else {
  48964. this.checkManifestFile();
  48965. }
  48966. }
  48967. Database.prototype.checkManifestFile = function () {
  48968. var _this = this;
  48969. function noManifestFile() {
  48970. that.enableSceneOffline = false;
  48971. that.enableTexturesOffline = false;
  48972. that.callbackManifestChecked(false);
  48973. }
  48974. var that = this;
  48975. var timeStampUsed = false;
  48976. var manifestURL = this.currentSceneUrl + ".manifest";
  48977. var xhr = new XMLHttpRequest();
  48978. if (navigator.onLine) {
  48979. // Adding a timestamp to by-pass browsers' cache
  48980. timeStampUsed = true;
  48981. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  48982. }
  48983. xhr.open("GET", manifestURL, true);
  48984. xhr.addEventListener("load", function () {
  48985. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  48986. try {
  48987. var manifestFile = JSON.parse(xhr.response);
  48988. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  48989. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  48990. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  48991. _this.manifestVersionFound = manifestFile.version;
  48992. }
  48993. if (_this.callbackManifestChecked) {
  48994. _this.callbackManifestChecked(true);
  48995. }
  48996. }
  48997. catch (ex) {
  48998. noManifestFile();
  48999. }
  49000. }
  49001. else {
  49002. noManifestFile();
  49003. }
  49004. }, false);
  49005. xhr.addEventListener("error", function (event) {
  49006. if (timeStampUsed) {
  49007. timeStampUsed = false;
  49008. // Let's retry without the timeStamp
  49009. // It could fail when coupled with HTML5 Offline API
  49010. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  49011. xhr.open("GET", retryManifestURL, true);
  49012. xhr.send();
  49013. }
  49014. else {
  49015. noManifestFile();
  49016. }
  49017. }, false);
  49018. try {
  49019. xhr.send();
  49020. }
  49021. catch (ex) {
  49022. BABYLON.Tools.Error("Error on XHR send request.");
  49023. that.callbackManifestChecked(false);
  49024. }
  49025. };
  49026. Database.prototype.openAsync = function (successCallback, errorCallback) {
  49027. var _this = this;
  49028. function handleError() {
  49029. that.isSupported = false;
  49030. if (errorCallback)
  49031. errorCallback();
  49032. }
  49033. var that = this;
  49034. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  49035. // Your browser doesn't support IndexedDB
  49036. this.isSupported = false;
  49037. if (errorCallback)
  49038. errorCallback();
  49039. }
  49040. else {
  49041. // If the DB hasn't been opened or created yet
  49042. if (!this.db) {
  49043. this.hasReachedQuota = false;
  49044. this.isSupported = true;
  49045. var request = this.idbFactory.open("babylonjs", 1);
  49046. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  49047. request.onerror = function (event) {
  49048. handleError();
  49049. };
  49050. // executes when a version change transaction cannot complete due to other active transactions
  49051. request.onblocked = function (event) {
  49052. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  49053. handleError();
  49054. };
  49055. // DB has been opened successfully
  49056. request.onsuccess = function (event) {
  49057. _this.db = request.result;
  49058. successCallback();
  49059. };
  49060. // Initialization of the DB. Creating Scenes & Textures stores
  49061. request.onupgradeneeded = function (event) {
  49062. _this.db = (event.target).result;
  49063. try {
  49064. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  49065. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  49066. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  49067. }
  49068. catch (ex) {
  49069. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  49070. handleError();
  49071. }
  49072. };
  49073. }
  49074. else {
  49075. if (successCallback)
  49076. successCallback();
  49077. }
  49078. }
  49079. };
  49080. Database.prototype.loadImageFromDB = function (url, image) {
  49081. var _this = this;
  49082. var completeURL = Database.ReturnFullUrlLocation(url);
  49083. var saveAndLoadImage = function () {
  49084. if (!_this.hasReachedQuota && _this.db !== null) {
  49085. // the texture is not yet in the DB, let's try to save it
  49086. _this._saveImageIntoDBAsync(completeURL, image);
  49087. }
  49088. else {
  49089. image.src = url;
  49090. }
  49091. };
  49092. if (!this.mustUpdateRessources) {
  49093. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  49094. }
  49095. else {
  49096. saveAndLoadImage();
  49097. }
  49098. };
  49099. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  49100. if (this.isSupported && this.db !== null) {
  49101. var texture;
  49102. var transaction = this.db.transaction(["textures"]);
  49103. transaction.onabort = function (event) {
  49104. image.src = url;
  49105. };
  49106. transaction.oncomplete = function (event) {
  49107. var blobTextureURL;
  49108. if (texture) {
  49109. var URL = window.URL || window.webkitURL;
  49110. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  49111. image.onerror = function () {
  49112. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  49113. image.src = url;
  49114. };
  49115. image.src = blobTextureURL;
  49116. }
  49117. else {
  49118. notInDBCallback();
  49119. }
  49120. };
  49121. var getRequest = transaction.objectStore("textures").get(url);
  49122. getRequest.onsuccess = function (event) {
  49123. texture = (event.target).result;
  49124. };
  49125. getRequest.onerror = function (event) {
  49126. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  49127. image.src = url;
  49128. };
  49129. }
  49130. else {
  49131. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49132. image.src = url;
  49133. }
  49134. };
  49135. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  49136. var _this = this;
  49137. if (this.isSupported) {
  49138. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  49139. var generateBlobUrl = function () {
  49140. var blobTextureURL;
  49141. if (blob) {
  49142. var URL = window.URL || window.webkitURL;
  49143. try {
  49144. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  49145. }
  49146. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  49147. catch (ex) {
  49148. blobTextureURL = URL.createObjectURL(blob);
  49149. }
  49150. }
  49151. image.src = blobTextureURL;
  49152. };
  49153. if (Database.IsUASupportingBlobStorage) {
  49154. var xhr = new XMLHttpRequest(), blob;
  49155. xhr.open("GET", url, true);
  49156. xhr.responseType = "blob";
  49157. xhr.addEventListener("load", function () {
  49158. if (xhr.status === 200) {
  49159. // Blob as response (XHR2)
  49160. blob = xhr.response;
  49161. var transaction = _this.db.transaction(["textures"], "readwrite");
  49162. // the transaction could abort because of a QuotaExceededError error
  49163. transaction.onabort = function (event) {
  49164. try {
  49165. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49166. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49167. _this.hasReachedQuota = true;
  49168. }
  49169. }
  49170. catch (ex) { }
  49171. generateBlobUrl();
  49172. };
  49173. transaction.oncomplete = function (event) {
  49174. generateBlobUrl();
  49175. };
  49176. var newTexture = { textureUrl: url, data: blob };
  49177. try {
  49178. // Put the blob into the dabase
  49179. var addRequest = transaction.objectStore("textures").put(newTexture);
  49180. addRequest.onsuccess = function (event) {
  49181. };
  49182. addRequest.onerror = function (event) {
  49183. generateBlobUrl();
  49184. };
  49185. }
  49186. catch (ex) {
  49187. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  49188. if (ex.code === 25) {
  49189. Database.IsUASupportingBlobStorage = false;
  49190. }
  49191. image.src = url;
  49192. }
  49193. }
  49194. else {
  49195. image.src = url;
  49196. }
  49197. }, false);
  49198. xhr.addEventListener("error", function (event) {
  49199. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  49200. image.src = url;
  49201. }, false);
  49202. xhr.send();
  49203. }
  49204. else {
  49205. image.src = url;
  49206. }
  49207. }
  49208. else {
  49209. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49210. image.src = url;
  49211. }
  49212. };
  49213. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  49214. var _this = this;
  49215. var updateVersion = function (event) {
  49216. // the version is not yet in the DB or we need to update it
  49217. _this._saveVersionIntoDBAsync(url, versionLoaded);
  49218. };
  49219. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  49220. };
  49221. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  49222. var _this = this;
  49223. if (this.isSupported) {
  49224. var version;
  49225. try {
  49226. var transaction = this.db.transaction(["versions"]);
  49227. transaction.oncomplete = function (event) {
  49228. if (version) {
  49229. // If the version in the JSON file is > than the version in DB
  49230. if (_this.manifestVersionFound > version.data) {
  49231. _this.mustUpdateRessources = true;
  49232. updateInDBCallback();
  49233. }
  49234. else {
  49235. callback(version.data);
  49236. }
  49237. }
  49238. else {
  49239. _this.mustUpdateRessources = true;
  49240. updateInDBCallback();
  49241. }
  49242. };
  49243. transaction.onabort = function (event) {
  49244. callback(-1);
  49245. };
  49246. var getRequest = transaction.objectStore("versions").get(url);
  49247. getRequest.onsuccess = function (event) {
  49248. version = (event.target).result;
  49249. };
  49250. getRequest.onerror = function (event) {
  49251. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  49252. callback(-1);
  49253. };
  49254. }
  49255. catch (ex) {
  49256. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  49257. callback(-1);
  49258. }
  49259. }
  49260. else {
  49261. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49262. callback(-1);
  49263. }
  49264. };
  49265. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  49266. var _this = this;
  49267. if (this.isSupported && !this.hasReachedQuota) {
  49268. try {
  49269. // Open a transaction to the database
  49270. var transaction = this.db.transaction(["versions"], "readwrite");
  49271. // the transaction could abort because of a QuotaExceededError error
  49272. transaction.onabort = function (event) {
  49273. try {
  49274. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49275. _this.hasReachedQuota = true;
  49276. }
  49277. }
  49278. catch (ex) { }
  49279. callback(-1);
  49280. };
  49281. transaction.oncomplete = function (event) {
  49282. callback(_this.manifestVersionFound);
  49283. };
  49284. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  49285. // Put the scene into the database
  49286. var addRequest = transaction.objectStore("versions").put(newVersion);
  49287. addRequest.onsuccess = function (event) {
  49288. };
  49289. addRequest.onerror = function (event) {
  49290. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  49291. };
  49292. }
  49293. catch (ex) {
  49294. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  49295. callback(-1);
  49296. }
  49297. }
  49298. else {
  49299. callback(-1);
  49300. }
  49301. };
  49302. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  49303. var _this = this;
  49304. var completeUrl = Database.ReturnFullUrlLocation(url);
  49305. var saveAndLoadFile = function (event) {
  49306. // the scene is not yet in the DB, let's try to save it
  49307. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  49308. };
  49309. this._checkVersionFromDB(completeUrl, function (version) {
  49310. if (version !== -1) {
  49311. if (!_this.mustUpdateRessources) {
  49312. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  49313. }
  49314. else {
  49315. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  49316. }
  49317. }
  49318. else {
  49319. errorCallback();
  49320. }
  49321. });
  49322. };
  49323. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  49324. if (this.isSupported) {
  49325. var targetStore;
  49326. if (url.indexOf(".babylon") !== -1) {
  49327. targetStore = "scenes";
  49328. }
  49329. else {
  49330. targetStore = "textures";
  49331. }
  49332. var file;
  49333. var transaction = this.db.transaction([targetStore]);
  49334. transaction.oncomplete = function (event) {
  49335. if (file) {
  49336. callback(file.data);
  49337. }
  49338. else {
  49339. notInDBCallback();
  49340. }
  49341. };
  49342. transaction.onabort = function (event) {
  49343. notInDBCallback();
  49344. };
  49345. var getRequest = transaction.objectStore(targetStore).get(url);
  49346. getRequest.onsuccess = function (event) {
  49347. file = (event.target).result;
  49348. };
  49349. getRequest.onerror = function (event) {
  49350. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  49351. notInDBCallback();
  49352. };
  49353. }
  49354. else {
  49355. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49356. callback();
  49357. }
  49358. };
  49359. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  49360. var _this = this;
  49361. if (this.isSupported) {
  49362. var targetStore;
  49363. if (url.indexOf(".babylon") !== -1) {
  49364. targetStore = "scenes";
  49365. }
  49366. else {
  49367. targetStore = "textures";
  49368. }
  49369. // Create XHR
  49370. var xhr = new XMLHttpRequest(), fileData;
  49371. xhr.open("GET", url, true);
  49372. if (useArrayBuffer) {
  49373. xhr.responseType = "arraybuffer";
  49374. }
  49375. xhr.onprogress = progressCallback;
  49376. xhr.addEventListener("load", function () {
  49377. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  49378. // Blob as response (XHR2)
  49379. //fileData = xhr.responseText;
  49380. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  49381. if (!_this.hasReachedQuota) {
  49382. // Open a transaction to the database
  49383. var transaction = _this.db.transaction([targetStore], "readwrite");
  49384. // the transaction could abort because of a QuotaExceededError error
  49385. transaction.onabort = function (event) {
  49386. try {
  49387. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49388. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49389. _this.hasReachedQuota = true;
  49390. }
  49391. }
  49392. catch (ex) { }
  49393. callback(fileData);
  49394. };
  49395. transaction.oncomplete = function (event) {
  49396. callback(fileData);
  49397. };
  49398. var newFile;
  49399. if (targetStore === "scenes") {
  49400. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  49401. }
  49402. else {
  49403. newFile = { textureUrl: url, data: fileData };
  49404. }
  49405. try {
  49406. // Put the scene into the database
  49407. var addRequest = transaction.objectStore(targetStore).put(newFile);
  49408. addRequest.onsuccess = function (event) {
  49409. };
  49410. addRequest.onerror = function (event) {
  49411. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  49412. };
  49413. }
  49414. catch (ex) {
  49415. callback(fileData);
  49416. }
  49417. }
  49418. else {
  49419. callback(fileData);
  49420. }
  49421. }
  49422. else {
  49423. callback();
  49424. }
  49425. }, false);
  49426. xhr.addEventListener("error", function (event) {
  49427. BABYLON.Tools.Error("error on XHR request.");
  49428. callback();
  49429. }, false);
  49430. xhr.send();
  49431. }
  49432. else {
  49433. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49434. callback();
  49435. }
  49436. };
  49437. Database.IsUASupportingBlobStorage = true;
  49438. Database.IDBStorageEnabled = true;
  49439. Database.parseURL = function (url) {
  49440. var a = document.createElement('a');
  49441. a.href = url;
  49442. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  49443. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  49444. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  49445. return absLocation;
  49446. };
  49447. Database.ReturnFullUrlLocation = function (url) {
  49448. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  49449. return (Database.parseURL(window.location.href) + url);
  49450. }
  49451. else {
  49452. return url;
  49453. }
  49454. };
  49455. return Database;
  49456. }());
  49457. BABYLON.Database = Database;
  49458. })(BABYLON || (BABYLON = {}));
  49459. //# sourceMappingURL=babylon.database.js.map
  49460. var BABYLON;
  49461. (function (BABYLON) {
  49462. var FresnelParameters = (function () {
  49463. function FresnelParameters() {
  49464. this._isEnabled = true;
  49465. this.leftColor = BABYLON.Color3.White();
  49466. this.rightColor = BABYLON.Color3.Black();
  49467. this.bias = 0;
  49468. this.power = 1;
  49469. }
  49470. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  49471. get: function () {
  49472. return this._isEnabled;
  49473. },
  49474. set: function (value) {
  49475. if (this._isEnabled === value) {
  49476. return;
  49477. }
  49478. this._isEnabled = value;
  49479. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  49480. },
  49481. enumerable: true,
  49482. configurable: true
  49483. });
  49484. FresnelParameters.prototype.clone = function () {
  49485. var newFresnelParameters = new FresnelParameters();
  49486. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  49487. return newFresnelParameters;
  49488. };
  49489. FresnelParameters.prototype.serialize = function () {
  49490. var serializationObject = {};
  49491. serializationObject.isEnabled = this.isEnabled;
  49492. serializationObject.leftColor = this.leftColor;
  49493. serializationObject.rightColor = this.rightColor;
  49494. serializationObject.bias = this.bias;
  49495. serializationObject.power = this.power;
  49496. return serializationObject;
  49497. };
  49498. FresnelParameters.Parse = function (parsedFresnelParameters) {
  49499. var fresnelParameters = new FresnelParameters();
  49500. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  49501. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  49502. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  49503. fresnelParameters.bias = parsedFresnelParameters.bias;
  49504. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  49505. return fresnelParameters;
  49506. };
  49507. return FresnelParameters;
  49508. }());
  49509. BABYLON.FresnelParameters = FresnelParameters;
  49510. })(BABYLON || (BABYLON = {}));
  49511. //# sourceMappingURL=babylon.fresnelParameters.js.map
  49512. var BABYLON;
  49513. (function (BABYLON) {
  49514. var MultiMaterial = (function (_super) {
  49515. __extends(MultiMaterial, _super);
  49516. function MultiMaterial(name, scene) {
  49517. var _this = _super.call(this, name, scene, true) || this;
  49518. scene.multiMaterials.push(_this);
  49519. _this.subMaterials = new Array();
  49520. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  49521. return _this;
  49522. }
  49523. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  49524. get: function () {
  49525. return this._subMaterials;
  49526. },
  49527. set: function (value) {
  49528. this._subMaterials = value;
  49529. this._hookArray(value);
  49530. },
  49531. enumerable: true,
  49532. configurable: true
  49533. });
  49534. MultiMaterial.prototype._hookArray = function (array) {
  49535. var _this = this;
  49536. var oldPush = array.push;
  49537. array.push = function () {
  49538. var items = [];
  49539. for (var _i = 0; _i < arguments.length; _i++) {
  49540. items[_i] = arguments[_i];
  49541. }
  49542. var result = oldPush.apply(array, items);
  49543. _this._markAllSubMeshesAsTexturesDirty();
  49544. return result;
  49545. };
  49546. var oldSplice = array.splice;
  49547. array.splice = function (index, deleteCount) {
  49548. var deleted = oldSplice.apply(array, [index, deleteCount]);
  49549. _this._markAllSubMeshesAsTexturesDirty();
  49550. return deleted;
  49551. };
  49552. };
  49553. // Properties
  49554. MultiMaterial.prototype.getSubMaterial = function (index) {
  49555. if (index < 0 || index >= this.subMaterials.length) {
  49556. return this.getScene().defaultMaterial;
  49557. }
  49558. return this.subMaterials[index];
  49559. };
  49560. MultiMaterial.prototype.getActiveTextures = function () {
  49561. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  49562. var _a;
  49563. };
  49564. // Methods
  49565. MultiMaterial.prototype.getClassName = function () {
  49566. return "MultiMaterial";
  49567. };
  49568. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  49569. for (var index = 0; index < this.subMaterials.length; index++) {
  49570. var subMaterial = this.subMaterials[index];
  49571. if (subMaterial) {
  49572. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  49573. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  49574. return false;
  49575. }
  49576. continue;
  49577. }
  49578. if (!this.subMaterials[index].isReady(mesh)) {
  49579. return false;
  49580. }
  49581. }
  49582. }
  49583. return true;
  49584. };
  49585. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  49586. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  49587. for (var index = 0; index < this.subMaterials.length; index++) {
  49588. var subMaterial = null;
  49589. if (cloneChildren) {
  49590. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  49591. }
  49592. else {
  49593. subMaterial = this.subMaterials[index];
  49594. }
  49595. newMultiMaterial.subMaterials.push(subMaterial);
  49596. }
  49597. return newMultiMaterial;
  49598. };
  49599. MultiMaterial.prototype.serialize = function () {
  49600. var serializationObject = {};
  49601. serializationObject.name = this.name;
  49602. serializationObject.id = this.id;
  49603. serializationObject.tags = BABYLON.Tags.GetTags(this);
  49604. serializationObject.materials = [];
  49605. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  49606. var subMat = this.subMaterials[matIndex];
  49607. if (subMat) {
  49608. serializationObject.materials.push(subMat.id);
  49609. }
  49610. else {
  49611. serializationObject.materials.push(null);
  49612. }
  49613. }
  49614. return serializationObject;
  49615. };
  49616. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49617. var scene = this.getScene();
  49618. if (!scene) {
  49619. return;
  49620. }
  49621. var index = scene.multiMaterials.indexOf(this);
  49622. if (index >= 0) {
  49623. scene.multiMaterials.splice(index, 1);
  49624. }
  49625. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49626. };
  49627. return MultiMaterial;
  49628. }(BABYLON.Material));
  49629. BABYLON.MultiMaterial = MultiMaterial;
  49630. })(BABYLON || (BABYLON = {}));
  49631. //# sourceMappingURL=babylon.multiMaterial.js.map
  49632. var BABYLON;
  49633. (function (BABYLON) {
  49634. var FreeCameraTouchInput = (function () {
  49635. function FreeCameraTouchInput() {
  49636. this._offsetX = null;
  49637. this._offsetY = null;
  49638. this._pointerCount = 0;
  49639. this._pointerPressed = [];
  49640. this.touchAngularSensibility = 200000.0;
  49641. this.touchMoveSensibility = 250.0;
  49642. }
  49643. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  49644. var _this = this;
  49645. var previousPosition;
  49646. if (this._pointerInput === undefined) {
  49647. this._onLostFocus = function (evt) {
  49648. _this._offsetX = null;
  49649. _this._offsetY = null;
  49650. };
  49651. this._pointerInput = function (p, s) {
  49652. var evt = p.event;
  49653. if (evt.pointerType === "mouse") {
  49654. return;
  49655. }
  49656. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  49657. if (!noPreventDefault) {
  49658. evt.preventDefault();
  49659. }
  49660. _this._pointerPressed.push(evt.pointerId);
  49661. if (_this._pointerPressed.length !== 1) {
  49662. return;
  49663. }
  49664. previousPosition = {
  49665. x: evt.clientX,
  49666. y: evt.clientY
  49667. };
  49668. }
  49669. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  49670. if (!noPreventDefault) {
  49671. evt.preventDefault();
  49672. }
  49673. var index = _this._pointerPressed.indexOf(evt.pointerId);
  49674. if (index === -1) {
  49675. return;
  49676. }
  49677. _this._pointerPressed.splice(index, 1);
  49678. if (index != 0) {
  49679. return;
  49680. }
  49681. previousPosition = null;
  49682. _this._offsetX = null;
  49683. _this._offsetY = null;
  49684. }
  49685. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49686. if (!noPreventDefault) {
  49687. evt.preventDefault();
  49688. }
  49689. if (!previousPosition) {
  49690. return;
  49691. }
  49692. var index = _this._pointerPressed.indexOf(evt.pointerId);
  49693. if (index != 0) {
  49694. return;
  49695. }
  49696. _this._offsetX = evt.clientX - previousPosition.x;
  49697. _this._offsetY = -(evt.clientY - previousPosition.y);
  49698. }
  49699. };
  49700. }
  49701. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49702. element.addEventListener("blur", this._onLostFocus);
  49703. };
  49704. FreeCameraTouchInput.prototype.detachControl = function (element) {
  49705. if (this._pointerInput && element) {
  49706. this.camera.getScene().onPointerObservable.remove(this._observer);
  49707. this._observer = null;
  49708. element.removeEventListener("blur", this._onLostFocus);
  49709. this._onLostFocus = null;
  49710. this._pointerPressed = [];
  49711. this._offsetX = null;
  49712. this._offsetY = null;
  49713. this._pointerCount = 0;
  49714. }
  49715. };
  49716. FreeCameraTouchInput.prototype.checkInputs = function () {
  49717. if (this._offsetX) {
  49718. var camera = this.camera;
  49719. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  49720. if (this._pointerPressed.length > 1) {
  49721. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  49722. }
  49723. else {
  49724. var speed = camera._computeLocalCameraSpeed();
  49725. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  49726. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  49727. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  49728. }
  49729. }
  49730. };
  49731. FreeCameraTouchInput.prototype.getClassName = function () {
  49732. return "FreeCameraTouchInput";
  49733. };
  49734. FreeCameraTouchInput.prototype.getSimpleName = function () {
  49735. return "touch";
  49736. };
  49737. __decorate([
  49738. BABYLON.serialize()
  49739. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  49740. __decorate([
  49741. BABYLON.serialize()
  49742. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  49743. return FreeCameraTouchInput;
  49744. }());
  49745. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  49746. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  49747. })(BABYLON || (BABYLON = {}));
  49748. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  49749. /// <reference path="babylon.freeCamera.ts" />
  49750. var BABYLON;
  49751. (function (BABYLON) {
  49752. // We're mainly based on the logic defined into the FreeCamera code
  49753. var TouchCamera = (function (_super) {
  49754. __extends(TouchCamera, _super);
  49755. //-- end properties for backward compatibility for inputs
  49756. function TouchCamera(name, position, scene) {
  49757. var _this = _super.call(this, name, position, scene) || this;
  49758. _this.inputs.addTouch();
  49759. _this._setupInputs();
  49760. return _this;
  49761. }
  49762. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  49763. //-- Begin properties for backward compatibility for inputs
  49764. get: function () {
  49765. var touch = this.inputs.attached["touch"];
  49766. if (touch)
  49767. return touch.touchAngularSensibility;
  49768. },
  49769. set: function (value) {
  49770. var touch = this.inputs.attached["touch"];
  49771. if (touch)
  49772. touch.touchAngularSensibility = value;
  49773. },
  49774. enumerable: true,
  49775. configurable: true
  49776. });
  49777. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  49778. get: function () {
  49779. var touch = this.inputs.attached["touch"];
  49780. if (touch)
  49781. return touch.touchMoveSensibility;
  49782. },
  49783. set: function (value) {
  49784. var touch = this.inputs.attached["touch"];
  49785. if (touch)
  49786. touch.touchMoveSensibility = value;
  49787. },
  49788. enumerable: true,
  49789. configurable: true
  49790. });
  49791. TouchCamera.prototype.getClassName = function () {
  49792. return "TouchCamera";
  49793. };
  49794. TouchCamera.prototype._setupInputs = function () {
  49795. var mouse = this.inputs.attached["mouse"];
  49796. if (mouse) {
  49797. mouse.touchEnabled = false;
  49798. }
  49799. };
  49800. return TouchCamera;
  49801. }(BABYLON.FreeCamera));
  49802. BABYLON.TouchCamera = TouchCamera;
  49803. })(BABYLON || (BABYLON = {}));
  49804. //# sourceMappingURL=babylon.touchCamera.js.map
  49805. var BABYLON;
  49806. (function (BABYLON) {
  49807. var ProceduralTexture = (function (_super) {
  49808. __extends(ProceduralTexture, _super);
  49809. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  49810. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49811. if (isCube === void 0) { isCube = false; }
  49812. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49813. _this.isCube = isCube;
  49814. _this.isEnabled = true;
  49815. _this._currentRefreshId = -1;
  49816. _this._refreshRate = 1;
  49817. _this._vertexBuffers = {};
  49818. _this._uniforms = new Array();
  49819. _this._samplers = new Array();
  49820. _this._textures = new Array();
  49821. _this._floats = new Array();
  49822. _this._floatsArrays = {};
  49823. _this._colors3 = new Array();
  49824. _this._colors4 = new Array();
  49825. _this._vectors2 = new Array();
  49826. _this._vectors3 = new Array();
  49827. _this._matrices = new Array();
  49828. _this._fallbackTextureUsed = false;
  49829. scene._proceduralTextures.push(_this);
  49830. _this.name = name;
  49831. _this.isRenderTarget = true;
  49832. _this._size = size;
  49833. _this._generateMipMaps = generateMipMaps;
  49834. _this.setFragment(fragment);
  49835. _this._fallbackTexture = fallbackTexture;
  49836. var engine = scene.getEngine();
  49837. if (isCube) {
  49838. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  49839. _this.setFloat("face", 0);
  49840. }
  49841. else {
  49842. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  49843. }
  49844. // VBO
  49845. var vertices = [];
  49846. vertices.push(1, 1);
  49847. vertices.push(-1, 1);
  49848. vertices.push(-1, -1);
  49849. vertices.push(1, -1);
  49850. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49851. // Indices
  49852. var indices = [];
  49853. indices.push(0);
  49854. indices.push(1);
  49855. indices.push(2);
  49856. indices.push(0);
  49857. indices.push(2);
  49858. indices.push(3);
  49859. _this._indexBuffer = engine.createIndexBuffer(indices);
  49860. return _this;
  49861. }
  49862. ProceduralTexture.prototype.reset = function () {
  49863. if (this._effect === undefined) {
  49864. return;
  49865. }
  49866. var engine = this.getScene().getEngine();
  49867. engine._releaseEffect(this._effect);
  49868. };
  49869. ProceduralTexture.prototype.isReady = function () {
  49870. var _this = this;
  49871. var engine = this.getScene().getEngine();
  49872. var shaders;
  49873. if (!this._fragment) {
  49874. return false;
  49875. }
  49876. if (this._fallbackTextureUsed) {
  49877. return true;
  49878. }
  49879. if (this._fragment.fragmentElement !== undefined) {
  49880. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  49881. }
  49882. else {
  49883. shaders = { vertex: "procedural", fragment: this._fragment };
  49884. }
  49885. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  49886. _this.releaseInternalTexture();
  49887. if (_this._fallbackTexture) {
  49888. _this._texture = _this._fallbackTexture._texture;
  49889. _this._texture.incrementReferences();
  49890. }
  49891. _this._fallbackTextureUsed = true;
  49892. });
  49893. return this._effect.isReady();
  49894. };
  49895. ProceduralTexture.prototype.resetRefreshCounter = function () {
  49896. this._currentRefreshId = -1;
  49897. };
  49898. ProceduralTexture.prototype.setFragment = function (fragment) {
  49899. this._fragment = fragment;
  49900. };
  49901. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  49902. get: function () {
  49903. return this._refreshRate;
  49904. },
  49905. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49906. set: function (value) {
  49907. this._refreshRate = value;
  49908. this.resetRefreshCounter();
  49909. },
  49910. enumerable: true,
  49911. configurable: true
  49912. });
  49913. ProceduralTexture.prototype._shouldRender = function () {
  49914. if (!this.isEnabled || !this.isReady() || !this._texture) {
  49915. return false;
  49916. }
  49917. if (this._fallbackTextureUsed) {
  49918. return false;
  49919. }
  49920. if (this._currentRefreshId === -1) {
  49921. this._currentRefreshId = 1;
  49922. return true;
  49923. }
  49924. if (this.refreshRate === this._currentRefreshId) {
  49925. this._currentRefreshId = 1;
  49926. return true;
  49927. }
  49928. this._currentRefreshId++;
  49929. return false;
  49930. };
  49931. ProceduralTexture.prototype.getRenderSize = function () {
  49932. return this._size;
  49933. };
  49934. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  49935. if (this._fallbackTextureUsed) {
  49936. return;
  49937. }
  49938. this.releaseInternalTexture();
  49939. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  49940. };
  49941. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  49942. if (this._uniforms.indexOf(uniformName) === -1) {
  49943. this._uniforms.push(uniformName);
  49944. }
  49945. };
  49946. ProceduralTexture.prototype.setTexture = function (name, texture) {
  49947. if (this._samplers.indexOf(name) === -1) {
  49948. this._samplers.push(name);
  49949. }
  49950. this._textures[name] = texture;
  49951. return this;
  49952. };
  49953. ProceduralTexture.prototype.setFloat = function (name, value) {
  49954. this._checkUniform(name);
  49955. this._floats[name] = value;
  49956. return this;
  49957. };
  49958. ProceduralTexture.prototype.setFloats = function (name, value) {
  49959. this._checkUniform(name);
  49960. this._floatsArrays[name] = value;
  49961. return this;
  49962. };
  49963. ProceduralTexture.prototype.setColor3 = function (name, value) {
  49964. this._checkUniform(name);
  49965. this._colors3[name] = value;
  49966. return this;
  49967. };
  49968. ProceduralTexture.prototype.setColor4 = function (name, value) {
  49969. this._checkUniform(name);
  49970. this._colors4[name] = value;
  49971. return this;
  49972. };
  49973. ProceduralTexture.prototype.setVector2 = function (name, value) {
  49974. this._checkUniform(name);
  49975. this._vectors2[name] = value;
  49976. return this;
  49977. };
  49978. ProceduralTexture.prototype.setVector3 = function (name, value) {
  49979. this._checkUniform(name);
  49980. this._vectors3[name] = value;
  49981. return this;
  49982. };
  49983. ProceduralTexture.prototype.setMatrix = function (name, value) {
  49984. this._checkUniform(name);
  49985. this._matrices[name] = value;
  49986. return this;
  49987. };
  49988. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  49989. var scene = this.getScene();
  49990. var engine = scene.getEngine();
  49991. // Render
  49992. engine.enableEffect(this._effect);
  49993. engine.setState(false);
  49994. // Texture
  49995. for (var name in this._textures) {
  49996. this._effect.setTexture(name, this._textures[name]);
  49997. }
  49998. // Float
  49999. for (name in this._floats) {
  50000. this._effect.setFloat(name, this._floats[name]);
  50001. }
  50002. // Floats
  50003. for (name in this._floatsArrays) {
  50004. this._effect.setArray(name, this._floatsArrays[name]);
  50005. }
  50006. // Color3
  50007. for (name in this._colors3) {
  50008. this._effect.setColor3(name, this._colors3[name]);
  50009. }
  50010. // Color4
  50011. for (name in this._colors4) {
  50012. var color = this._colors4[name];
  50013. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50014. }
  50015. // Vector2
  50016. for (name in this._vectors2) {
  50017. this._effect.setVector2(name, this._vectors2[name]);
  50018. }
  50019. // Vector3
  50020. for (name in this._vectors3) {
  50021. this._effect.setVector3(name, this._vectors3[name]);
  50022. }
  50023. // Matrix
  50024. for (name in this._matrices) {
  50025. this._effect.setMatrix(name, this._matrices[name]);
  50026. }
  50027. if (this.isCube) {
  50028. for (var face = 0; face < 6; face++) {
  50029. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  50030. // VBOs
  50031. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50032. this._effect.setFloat("face", face);
  50033. // Clear
  50034. engine.clear(scene.clearColor, true, true, true);
  50035. // Draw order
  50036. engine.draw(true, 0, 6);
  50037. // Mipmaps
  50038. if (face === 5) {
  50039. engine.generateMipMapsForCubemap(this._texture);
  50040. }
  50041. }
  50042. }
  50043. else {
  50044. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  50045. // VBOs
  50046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50047. // Clear
  50048. engine.clear(scene.clearColor, true, true, true);
  50049. // Draw order
  50050. engine.draw(true, 0, 6);
  50051. }
  50052. // Unbind
  50053. engine.unBindFramebuffer(this._texture, this.isCube);
  50054. if (this.onGenerated) {
  50055. this.onGenerated();
  50056. }
  50057. };
  50058. ProceduralTexture.prototype.clone = function () {
  50059. var textureSize = this.getSize();
  50060. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  50061. // Base texture
  50062. newTexture.hasAlpha = this.hasAlpha;
  50063. newTexture.level = this.level;
  50064. // RenderTarget Texture
  50065. newTexture.coordinatesMode = this.coordinatesMode;
  50066. return newTexture;
  50067. };
  50068. ProceduralTexture.prototype.dispose = function () {
  50069. var index = this.getScene()._proceduralTextures.indexOf(this);
  50070. if (index >= 0) {
  50071. this.getScene()._proceduralTextures.splice(index, 1);
  50072. }
  50073. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50074. if (vertexBuffer) {
  50075. vertexBuffer.dispose();
  50076. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50077. }
  50078. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  50079. this._indexBuffer = null;
  50080. }
  50081. _super.prototype.dispose.call(this);
  50082. };
  50083. return ProceduralTexture;
  50084. }(BABYLON.Texture));
  50085. BABYLON.ProceduralTexture = ProceduralTexture;
  50086. })(BABYLON || (BABYLON = {}));
  50087. //# sourceMappingURL=babylon.proceduralTexture.js.map
  50088. /// <reference path="babylon.proceduralTexture.ts" />
  50089. var BABYLON;
  50090. (function (BABYLON) {
  50091. var CustomProceduralTexture = (function (_super) {
  50092. __extends(CustomProceduralTexture, _super);
  50093. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  50094. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  50095. _this._animate = true;
  50096. _this._time = 0;
  50097. _this._texturePath = texturePath;
  50098. //Try to load json
  50099. _this.loadJson(texturePath);
  50100. _this.refreshRate = 1;
  50101. return _this;
  50102. }
  50103. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  50104. var _this = this;
  50105. var that = this;
  50106. function noConfigFile() {
  50107. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  50108. try {
  50109. that.setFragment(that._texturePath);
  50110. }
  50111. catch (ex) {
  50112. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  50113. }
  50114. }
  50115. var configFileUrl = jsonUrl + "/config.json";
  50116. var xhr = new XMLHttpRequest();
  50117. xhr.open("GET", configFileUrl, true);
  50118. xhr.addEventListener("load", function () {
  50119. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50120. try {
  50121. _this._config = JSON.parse(xhr.response);
  50122. _this.updateShaderUniforms();
  50123. _this.updateTextures();
  50124. _this.setFragment(_this._texturePath + "/custom");
  50125. _this._animate = _this._config.animate;
  50126. _this.refreshRate = _this._config.refreshrate;
  50127. }
  50128. catch (ex) {
  50129. noConfigFile();
  50130. }
  50131. }
  50132. else {
  50133. noConfigFile();
  50134. }
  50135. }, false);
  50136. xhr.addEventListener("error", function () {
  50137. noConfigFile();
  50138. }, false);
  50139. try {
  50140. xhr.send();
  50141. }
  50142. catch (ex) {
  50143. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  50144. }
  50145. };
  50146. CustomProceduralTexture.prototype.isReady = function () {
  50147. if (!_super.prototype.isReady.call(this)) {
  50148. return false;
  50149. }
  50150. for (var name in this._textures) {
  50151. var texture = this._textures[name];
  50152. if (!texture.isReady()) {
  50153. return false;
  50154. }
  50155. }
  50156. return true;
  50157. };
  50158. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50159. if (this._animate) {
  50160. this._time += this.getScene().getAnimationRatio() * 0.03;
  50161. this.updateShaderUniforms();
  50162. }
  50163. _super.prototype.render.call(this, useCameraPostProcess);
  50164. };
  50165. CustomProceduralTexture.prototype.updateTextures = function () {
  50166. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  50167. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  50168. }
  50169. };
  50170. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  50171. if (this._config) {
  50172. for (var j = 0; j < this._config.uniforms.length; j++) {
  50173. var uniform = this._config.uniforms[j];
  50174. switch (uniform.type) {
  50175. case "float":
  50176. this.setFloat(uniform.name, uniform.value);
  50177. break;
  50178. case "color3":
  50179. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  50180. break;
  50181. case "color4":
  50182. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  50183. break;
  50184. case "vector2":
  50185. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  50186. break;
  50187. case "vector3":
  50188. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  50189. break;
  50190. }
  50191. }
  50192. }
  50193. this.setFloat("time", this._time);
  50194. };
  50195. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  50196. get: function () {
  50197. return this._animate;
  50198. },
  50199. set: function (value) {
  50200. this._animate = value;
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. return CustomProceduralTexture;
  50206. }(BABYLON.ProceduralTexture));
  50207. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  50208. })(BABYLON || (BABYLON = {}));
  50209. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  50210. var BABYLON;
  50211. (function (BABYLON) {
  50212. var FreeCameraGamepadInput = (function () {
  50213. function FreeCameraGamepadInput() {
  50214. this.gamepadAngularSensibility = 200;
  50215. this.gamepadMoveSensibility = 40;
  50216. // private members
  50217. this._cameraTransform = BABYLON.Matrix.Identity();
  50218. this._deltaTransform = BABYLON.Vector3.Zero();
  50219. this._vector3 = BABYLON.Vector3.Zero();
  50220. this._vector2 = BABYLON.Vector2.Zero();
  50221. }
  50222. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50223. var _this = this;
  50224. var manager = this.camera.getScene().gamepadManager;
  50225. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50226. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50227. // prioritize XBOX gamepads.
  50228. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50229. _this.gamepad = gamepad;
  50230. }
  50231. }
  50232. });
  50233. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50234. if (_this.gamepad === gamepad) {
  50235. _this.gamepad = null;
  50236. }
  50237. });
  50238. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50239. };
  50240. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  50241. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50242. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50243. this.gamepad = null;
  50244. };
  50245. FreeCameraGamepadInput.prototype.checkInputs = function () {
  50246. if (this.gamepad && this.gamepad.leftStick) {
  50247. var camera = this.camera;
  50248. var LSValues = this.gamepad.leftStick;
  50249. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  50250. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50251. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  50252. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  50253. var RSValues = this.gamepad.rightStick;
  50254. if (RSValues) {
  50255. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  50256. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  50257. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  50258. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  50259. }
  50260. else {
  50261. RSValues = { x: 0, y: 0 };
  50262. }
  50263. if (!camera.rotationQuaternion) {
  50264. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  50265. }
  50266. else {
  50267. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  50268. }
  50269. var speed = camera._computeLocalCameraSpeed() * 50.0;
  50270. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  50271. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  50272. camera.cameraDirection.addInPlace(this._deltaTransform);
  50273. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  50274. camera.cameraRotation.addInPlace(this._vector2);
  50275. }
  50276. };
  50277. FreeCameraGamepadInput.prototype.getClassName = function () {
  50278. return "FreeCameraGamepadInput";
  50279. };
  50280. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  50281. return "gamepad";
  50282. };
  50283. __decorate([
  50284. BABYLON.serialize()
  50285. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  50286. __decorate([
  50287. BABYLON.serialize()
  50288. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50289. return FreeCameraGamepadInput;
  50290. }());
  50291. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  50292. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  50293. })(BABYLON || (BABYLON = {}));
  50294. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  50295. var BABYLON;
  50296. (function (BABYLON) {
  50297. var ArcRotateCameraGamepadInput = (function () {
  50298. function ArcRotateCameraGamepadInput() {
  50299. this.gamepadRotationSensibility = 80;
  50300. this.gamepadMoveSensibility = 40;
  50301. }
  50302. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50303. var _this = this;
  50304. var manager = this.camera.getScene().gamepadManager;
  50305. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50306. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50307. // prioritize XBOX gamepads.
  50308. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50309. _this.gamepad = gamepad;
  50310. }
  50311. }
  50312. });
  50313. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50314. if (_this.gamepad === gamepad) {
  50315. _this.gamepad = null;
  50316. }
  50317. });
  50318. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50319. };
  50320. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  50321. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50322. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50323. this.gamepad = null;
  50324. };
  50325. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  50326. if (this.gamepad) {
  50327. var camera = this.camera;
  50328. var RSValues = this.gamepad.rightStick;
  50329. if (RSValues) {
  50330. if (RSValues.x != 0) {
  50331. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  50332. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  50333. camera.inertialAlphaOffset += normalizedRX;
  50334. }
  50335. }
  50336. if (RSValues.y != 0) {
  50337. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  50338. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  50339. camera.inertialBetaOffset += normalizedRY;
  50340. }
  50341. }
  50342. }
  50343. var LSValues = this.gamepad.leftStick;
  50344. if (LSValues && LSValues.y != 0) {
  50345. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50346. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  50347. this.camera.inertialRadiusOffset -= normalizedLY;
  50348. }
  50349. }
  50350. }
  50351. };
  50352. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  50353. return "ArcRotateCameraGamepadInput";
  50354. };
  50355. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  50356. return "gamepad";
  50357. };
  50358. __decorate([
  50359. BABYLON.serialize()
  50360. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  50361. __decorate([
  50362. BABYLON.serialize()
  50363. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50364. return ArcRotateCameraGamepadInput;
  50365. }());
  50366. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  50367. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  50368. })(BABYLON || (BABYLON = {}));
  50369. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  50370. var BABYLON;
  50371. (function (BABYLON) {
  50372. var GamepadManager = (function () {
  50373. function GamepadManager() {
  50374. var _this = this;
  50375. this._babylonGamepads = [];
  50376. this._oneGamepadConnected = false;
  50377. this._isMonitoring = false;
  50378. this._gamepadEventSupported = 'GamepadEvent' in window;
  50379. this._gamepadSupport = (navigator.getGamepads ||
  50380. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50381. this.onGamepadConnectedObservable = new BABYLON.Observable();
  50382. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  50383. this._onGamepadConnectedEvent = function (evt) {
  50384. var gamepad = evt.gamepad;
  50385. // Protection code for Chrome which has a very buggy gamepad implementation...
  50386. // And raises a connected event on disconnection for instance
  50387. if (gamepad.index in _this._babylonGamepads) {
  50388. return;
  50389. }
  50390. var newGamepad = _this._addNewGamepad(gamepad);
  50391. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  50392. _this._startMonitoringGamepads();
  50393. };
  50394. this._onGamepadDisconnectedEvent = function (evt) {
  50395. var gamepad = evt.gamepad;
  50396. // Remove the gamepad from the list of gamepads to monitor.
  50397. for (var i in _this._babylonGamepads) {
  50398. if (_this._babylonGamepads[i].index === gamepad.index) {
  50399. var gamepadToRemove = _this._babylonGamepads[i];
  50400. _this._babylonGamepads[i] = null;
  50401. _this.onGamepadDisconnectedObservable.notifyObservers(gamepadToRemove);
  50402. gamepadToRemove.dispose();
  50403. break;
  50404. }
  50405. }
  50406. };
  50407. if (this._gamepadSupport) {
  50408. //first add already-connected gamepads
  50409. this._updateGamepadObjects();
  50410. if (this._babylonGamepads.length) {
  50411. this._startMonitoringGamepads();
  50412. }
  50413. // Checking if the gamepad connected event is supported (like in Firefox)
  50414. if (this._gamepadEventSupported) {
  50415. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50416. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  50417. }
  50418. else {
  50419. this._startMonitoringGamepads();
  50420. }
  50421. }
  50422. }
  50423. GamepadManager.prototype.getGamepadByType = function (type) {
  50424. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  50425. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  50426. var gamepad = _a[_i];
  50427. if (gamepad && gamepad.type === type) {
  50428. return gamepad;
  50429. }
  50430. }
  50431. return null;
  50432. };
  50433. GamepadManager.prototype.dispose = function () {
  50434. if (this._gamepadEventSupported) {
  50435. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  50436. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  50437. this._onGamepadConnectedEvent = null;
  50438. this._onGamepadDisconnectedEvent = null;
  50439. }
  50440. this._oneGamepadConnected = false;
  50441. this._stopMonitoringGamepads();
  50442. this._babylonGamepads = [];
  50443. };
  50444. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  50445. if (!this._oneGamepadConnected) {
  50446. this._oneGamepadConnected = true;
  50447. }
  50448. var newGamepad;
  50449. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50450. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50451. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50452. }
  50453. else if (gamepad.pose) {
  50454. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50455. }
  50456. else {
  50457. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  50458. }
  50459. this._babylonGamepads[newGamepad.index] = newGamepad;
  50460. return newGamepad;
  50461. };
  50462. GamepadManager.prototype._startMonitoringGamepads = function () {
  50463. if (!this._isMonitoring) {
  50464. this._isMonitoring = true;
  50465. this._checkGamepadsStatus();
  50466. }
  50467. };
  50468. GamepadManager.prototype._stopMonitoringGamepads = function () {
  50469. this._isMonitoring = false;
  50470. };
  50471. GamepadManager.prototype._checkGamepadsStatus = function () {
  50472. var _this = this;
  50473. // Hack to be compatible Chrome
  50474. this._updateGamepadObjects();
  50475. for (var i in this._babylonGamepads) {
  50476. var gamepad = this._babylonGamepads[i];
  50477. if (!gamepad) {
  50478. continue;
  50479. }
  50480. gamepad.update();
  50481. }
  50482. if (this._isMonitoring) {
  50483. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  50484. }
  50485. };
  50486. // This function is called only on Chrome, which does not properly support
  50487. // connection/disconnection events and forces you to recopy again the gamepad object
  50488. GamepadManager.prototype._updateGamepadObjects = function () {
  50489. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50490. for (var i = 0; i < gamepads.length; i++) {
  50491. if (gamepads[i]) {
  50492. if (!this._babylonGamepads[gamepads[i].index]) {
  50493. var newGamepad = this._addNewGamepad(gamepads[i]);
  50494. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  50495. }
  50496. else {
  50497. // Forced to copy again this object for Chrome for unknown reason
  50498. this._babylonGamepads[i].browserGamepad = gamepads[i];
  50499. }
  50500. }
  50501. }
  50502. };
  50503. return GamepadManager;
  50504. }());
  50505. BABYLON.GamepadManager = GamepadManager;
  50506. })(BABYLON || (BABYLON = {}));
  50507. //# sourceMappingURL=babylon.gamepadManager.js.map
  50508. var BABYLON;
  50509. (function (BABYLON) {
  50510. var StickValues = (function () {
  50511. function StickValues(x, y) {
  50512. this.x = x;
  50513. this.y = y;
  50514. }
  50515. return StickValues;
  50516. }());
  50517. BABYLON.StickValues = StickValues;
  50518. var Gamepad = (function () {
  50519. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  50520. if (leftStickX === void 0) { leftStickX = 0; }
  50521. if (leftStickY === void 0) { leftStickY = 1; }
  50522. if (rightStickX === void 0) { rightStickX = 2; }
  50523. if (rightStickY === void 0) { rightStickY = 3; }
  50524. this.id = id;
  50525. this.index = index;
  50526. this.browserGamepad = browserGamepad;
  50527. this.type = Gamepad.GAMEPAD;
  50528. this._leftStickAxisX = leftStickX;
  50529. this._leftStickAxisY = leftStickY;
  50530. this._rightStickAxisX = rightStickX;
  50531. this._rightStickAxisY = rightStickY;
  50532. if (this.browserGamepad.axes.length >= 2) {
  50533. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50534. }
  50535. if (this.browserGamepad.axes.length >= 4) {
  50536. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50537. }
  50538. }
  50539. Gamepad.prototype.onleftstickchanged = function (callback) {
  50540. this._onleftstickchanged = callback;
  50541. };
  50542. Gamepad.prototype.onrightstickchanged = function (callback) {
  50543. this._onrightstickchanged = callback;
  50544. };
  50545. Object.defineProperty(Gamepad.prototype, "leftStick", {
  50546. get: function () {
  50547. return this._leftStick;
  50548. },
  50549. set: function (newValues) {
  50550. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  50551. this._onleftstickchanged(newValues);
  50552. }
  50553. this._leftStick = newValues;
  50554. },
  50555. enumerable: true,
  50556. configurable: true
  50557. });
  50558. Object.defineProperty(Gamepad.prototype, "rightStick", {
  50559. get: function () {
  50560. return this._rightStick;
  50561. },
  50562. set: function (newValues) {
  50563. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  50564. this._onrightstickchanged(newValues);
  50565. }
  50566. this._rightStick = newValues;
  50567. },
  50568. enumerable: true,
  50569. configurable: true
  50570. });
  50571. Gamepad.prototype.update = function () {
  50572. if (this._leftStick) {
  50573. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50574. }
  50575. if (this._rightStick) {
  50576. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50577. }
  50578. };
  50579. Gamepad.prototype.dispose = function () {
  50580. };
  50581. Gamepad.GAMEPAD = 0;
  50582. Gamepad.GENERIC = 1;
  50583. Gamepad.XBOX = 2;
  50584. Gamepad.POSE_ENABLED = 3;
  50585. return Gamepad;
  50586. }());
  50587. BABYLON.Gamepad = Gamepad;
  50588. var GenericPad = (function (_super) {
  50589. __extends(GenericPad, _super);
  50590. function GenericPad(id, index, browserGamepad) {
  50591. var _this = _super.call(this, id, index, browserGamepad) || this;
  50592. _this.type = Gamepad.GENERIC;
  50593. _this._buttons = new Array(browserGamepad.buttons.length);
  50594. return _this;
  50595. }
  50596. GenericPad.prototype.onbuttondown = function (callback) {
  50597. this._onbuttondown = callback;
  50598. };
  50599. GenericPad.prototype.onbuttonup = function (callback) {
  50600. this._onbuttonup = callback;
  50601. };
  50602. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  50603. if (newValue !== currentValue) {
  50604. if (this._onbuttondown && newValue === 1) {
  50605. this._onbuttondown(buttonIndex);
  50606. }
  50607. if (this._onbuttonup && newValue === 0) {
  50608. this._onbuttonup(buttonIndex);
  50609. }
  50610. }
  50611. return newValue;
  50612. };
  50613. GenericPad.prototype.update = function () {
  50614. _super.prototype.update.call(this);
  50615. for (var index = 0; index < this._buttons.length; index++) {
  50616. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  50617. }
  50618. };
  50619. return GenericPad;
  50620. }(Gamepad));
  50621. BABYLON.GenericPad = GenericPad;
  50622. })(BABYLON || (BABYLON = {}));
  50623. //# sourceMappingURL=babylon.gamepad.js.map
  50624. var BABYLON;
  50625. (function (BABYLON) {
  50626. var Xbox360Button;
  50627. (function (Xbox360Button) {
  50628. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  50629. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  50630. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  50631. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  50632. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  50633. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  50634. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  50635. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  50636. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  50637. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  50638. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  50639. var Xbox360Dpad;
  50640. (function (Xbox360Dpad) {
  50641. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  50642. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  50643. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  50644. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  50645. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  50646. var Xbox360Pad = (function (_super) {
  50647. __extends(Xbox360Pad, _super);
  50648. function Xbox360Pad(id, index, gamepad, xboxOne) {
  50649. if (xboxOne === void 0) { xboxOne = false; }
  50650. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  50651. _this._leftTrigger = 0;
  50652. _this._rightTrigger = 0;
  50653. _this._buttonA = 0;
  50654. _this._buttonB = 0;
  50655. _this._buttonX = 0;
  50656. _this._buttonY = 0;
  50657. _this._buttonBack = 0;
  50658. _this._buttonStart = 0;
  50659. _this._buttonLB = 0;
  50660. _this._buttonRB = 0;
  50661. _this._buttonLeftStick = 0;
  50662. _this._buttonRightStick = 0;
  50663. _this._dPadUp = 0;
  50664. _this._dPadDown = 0;
  50665. _this._dPadLeft = 0;
  50666. _this._dPadRight = 0;
  50667. _this._isXboxOnePad = false;
  50668. _this.type = BABYLON.Gamepad.XBOX;
  50669. _this._isXboxOnePad = xboxOne;
  50670. return _this;
  50671. }
  50672. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  50673. this._onlefttriggerchanged = callback;
  50674. };
  50675. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  50676. this._onrighttriggerchanged = callback;
  50677. };
  50678. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  50679. get: function () {
  50680. return this._leftTrigger;
  50681. },
  50682. set: function (newValue) {
  50683. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  50684. this._onlefttriggerchanged(newValue);
  50685. }
  50686. this._leftTrigger = newValue;
  50687. },
  50688. enumerable: true,
  50689. configurable: true
  50690. });
  50691. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  50692. get: function () {
  50693. return this._rightTrigger;
  50694. },
  50695. set: function (newValue) {
  50696. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  50697. this._onrighttriggerchanged(newValue);
  50698. }
  50699. this._rightTrigger = newValue;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. Xbox360Pad.prototype.onbuttondown = function (callback) {
  50705. this._onbuttondown = callback;
  50706. };
  50707. Xbox360Pad.prototype.onbuttonup = function (callback) {
  50708. this._onbuttonup = callback;
  50709. };
  50710. Xbox360Pad.prototype.ondpaddown = function (callback) {
  50711. this._ondpaddown = callback;
  50712. };
  50713. Xbox360Pad.prototype.ondpadup = function (callback) {
  50714. this._ondpadup = callback;
  50715. };
  50716. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  50717. if (newValue !== currentValue) {
  50718. if (this._onbuttondown && newValue === 1) {
  50719. this._onbuttondown(buttonType);
  50720. }
  50721. if (this._onbuttonup && newValue === 0) {
  50722. this._onbuttonup(buttonType);
  50723. }
  50724. }
  50725. return newValue;
  50726. };
  50727. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  50728. if (newValue !== currentValue) {
  50729. if (this._ondpaddown && newValue === 1) {
  50730. this._ondpaddown(buttonType);
  50731. }
  50732. if (this._ondpadup && newValue === 0) {
  50733. this._ondpadup(buttonType);
  50734. }
  50735. }
  50736. return newValue;
  50737. };
  50738. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  50739. get: function () {
  50740. return this._buttonA;
  50741. },
  50742. set: function (value) {
  50743. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  50744. },
  50745. enumerable: true,
  50746. configurable: true
  50747. });
  50748. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  50749. get: function () {
  50750. return this._buttonB;
  50751. },
  50752. set: function (value) {
  50753. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  50754. },
  50755. enumerable: true,
  50756. configurable: true
  50757. });
  50758. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  50759. get: function () {
  50760. return this._buttonX;
  50761. },
  50762. set: function (value) {
  50763. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  50764. },
  50765. enumerable: true,
  50766. configurable: true
  50767. });
  50768. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  50769. get: function () {
  50770. return this._buttonY;
  50771. },
  50772. set: function (value) {
  50773. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  50774. },
  50775. enumerable: true,
  50776. configurable: true
  50777. });
  50778. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  50779. get: function () {
  50780. return this._buttonStart;
  50781. },
  50782. set: function (value) {
  50783. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  50784. },
  50785. enumerable: true,
  50786. configurable: true
  50787. });
  50788. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  50789. get: function () {
  50790. return this._buttonBack;
  50791. },
  50792. set: function (value) {
  50793. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  50794. },
  50795. enumerable: true,
  50796. configurable: true
  50797. });
  50798. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  50799. get: function () {
  50800. return this._buttonLB;
  50801. },
  50802. set: function (value) {
  50803. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  50804. },
  50805. enumerable: true,
  50806. configurable: true
  50807. });
  50808. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  50809. get: function () {
  50810. return this._buttonRB;
  50811. },
  50812. set: function (value) {
  50813. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  50814. },
  50815. enumerable: true,
  50816. configurable: true
  50817. });
  50818. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  50819. get: function () {
  50820. return this._buttonLeftStick;
  50821. },
  50822. set: function (value) {
  50823. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  50824. },
  50825. enumerable: true,
  50826. configurable: true
  50827. });
  50828. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  50829. get: function () {
  50830. return this._buttonRightStick;
  50831. },
  50832. set: function (value) {
  50833. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  50834. },
  50835. enumerable: true,
  50836. configurable: true
  50837. });
  50838. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  50839. get: function () {
  50840. return this._dPadUp;
  50841. },
  50842. set: function (value) {
  50843. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  50844. },
  50845. enumerable: true,
  50846. configurable: true
  50847. });
  50848. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  50849. get: function () {
  50850. return this._dPadDown;
  50851. },
  50852. set: function (value) {
  50853. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  50854. },
  50855. enumerable: true,
  50856. configurable: true
  50857. });
  50858. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  50859. get: function () {
  50860. return this._dPadLeft;
  50861. },
  50862. set: function (value) {
  50863. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  50864. },
  50865. enumerable: true,
  50866. configurable: true
  50867. });
  50868. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  50869. get: function () {
  50870. return this._dPadRight;
  50871. },
  50872. set: function (value) {
  50873. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  50874. },
  50875. enumerable: true,
  50876. configurable: true
  50877. });
  50878. Xbox360Pad.prototype.update = function () {
  50879. _super.prototype.update.call(this);
  50880. if (this._isXboxOnePad) {
  50881. this.buttonA = this.browserGamepad.buttons[0].value;
  50882. this.buttonB = this.browserGamepad.buttons[1].value;
  50883. this.buttonX = this.browserGamepad.buttons[2].value;
  50884. this.buttonY = this.browserGamepad.buttons[3].value;
  50885. this.buttonLB = this.browserGamepad.buttons[4].value;
  50886. this.buttonRB = this.browserGamepad.buttons[5].value;
  50887. this.leftTrigger = this.browserGamepad.axes[2];
  50888. this.rightTrigger = this.browserGamepad.axes[5];
  50889. this.buttonBack = this.browserGamepad.buttons[9].value;
  50890. this.buttonStart = this.browserGamepad.buttons[8].value;
  50891. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  50892. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  50893. this.dPadUp = this.browserGamepad.buttons[11].value;
  50894. this.dPadDown = this.browserGamepad.buttons[12].value;
  50895. this.dPadLeft = this.browserGamepad.buttons[13].value;
  50896. this.dPadRight = this.browserGamepad.buttons[14].value;
  50897. }
  50898. else {
  50899. this.buttonA = this.browserGamepad.buttons[0].value;
  50900. this.buttonB = this.browserGamepad.buttons[1].value;
  50901. this.buttonX = this.browserGamepad.buttons[2].value;
  50902. this.buttonY = this.browserGamepad.buttons[3].value;
  50903. this.buttonLB = this.browserGamepad.buttons[4].value;
  50904. this.buttonRB = this.browserGamepad.buttons[5].value;
  50905. this.leftTrigger = this.browserGamepad.buttons[6].value;
  50906. this.rightTrigger = this.browserGamepad.buttons[7].value;
  50907. this.buttonBack = this.browserGamepad.buttons[8].value;
  50908. this.buttonStart = this.browserGamepad.buttons[9].value;
  50909. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  50910. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  50911. this.dPadUp = this.browserGamepad.buttons[12].value;
  50912. this.dPadDown = this.browserGamepad.buttons[13].value;
  50913. this.dPadLeft = this.browserGamepad.buttons[14].value;
  50914. this.dPadRight = this.browserGamepad.buttons[15].value;
  50915. }
  50916. };
  50917. return Xbox360Pad;
  50918. }(BABYLON.Gamepad));
  50919. BABYLON.Xbox360Pad = Xbox360Pad;
  50920. })(BABYLON || (BABYLON = {}));
  50921. //# sourceMappingURL=babylon.xboxGamepad.js.map
  50922. var BABYLON;
  50923. (function (BABYLON) {
  50924. var PoseEnabledControllerType;
  50925. (function (PoseEnabledControllerType) {
  50926. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  50927. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  50928. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  50929. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  50930. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  50931. var PoseEnabledControllerHelper = (function () {
  50932. function PoseEnabledControllerHelper() {
  50933. }
  50934. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  50935. // Oculus Touch
  50936. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  50937. return new BABYLON.OculusTouchController(vrGamepad);
  50938. }
  50939. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  50940. return new BABYLON.ViveController(vrGamepad);
  50941. }
  50942. else {
  50943. return new BABYLON.GenericController(vrGamepad);
  50944. }
  50945. };
  50946. return PoseEnabledControllerHelper;
  50947. }());
  50948. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  50949. var PoseEnabledController = (function (_super) {
  50950. __extends(PoseEnabledController, _super);
  50951. function PoseEnabledController(vrGamepad) {
  50952. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  50953. _this.vrGamepad = vrGamepad;
  50954. _this.deviceScaleFactor = 1;
  50955. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  50956. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  50957. _this.controllerType = PoseEnabledControllerType.GENERIC;
  50958. _this.position = BABYLON.Vector3.Zero();
  50959. _this.rotationQuaternion = new BABYLON.Quaternion();
  50960. _this.devicePosition = BABYLON.Vector3.Zero();
  50961. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50962. _this._calculatedPosition = BABYLON.Vector3.Zero();
  50963. _this._calculatedRotation = new BABYLON.Quaternion();
  50964. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  50965. return _this;
  50966. }
  50967. PoseEnabledController.prototype.update = function () {
  50968. _super.prototype.update.call(this);
  50969. var pose = this.vrGamepad.pose;
  50970. this.updateFromDevice(pose);
  50971. if (this._mesh) {
  50972. this._mesh.position.copyFrom(this._calculatedPosition);
  50973. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  50974. }
  50975. };
  50976. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  50977. if (poseData) {
  50978. this.rawPose = poseData;
  50979. if (poseData.position) {
  50980. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  50981. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  50982. this.devicePosition.z *= -1;
  50983. }
  50984. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  50985. this._calculatedPosition.addInPlace(this.position);
  50986. }
  50987. if (poseData.orientation) {
  50988. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50989. if (this._mesh) {
  50990. if (this._mesh.getScene().useRightHandedSystem) {
  50991. this.deviceRotationQuaternion.z *= -1;
  50992. this.deviceRotationQuaternion.w *= -1;
  50993. }
  50994. else {
  50995. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  50996. }
  50997. }
  50998. // if the camera is set, rotate to the camera's rotation
  50999. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51000. }
  51001. }
  51002. };
  51003. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51004. if (this._mesh) {
  51005. this._mesh.parent = undefined;
  51006. }
  51007. this._mesh = mesh;
  51008. if (this._poseControlledCamera) {
  51009. this._mesh.parent = this._poseControlledCamera;
  51010. }
  51011. if (!this._mesh.rotationQuaternion) {
  51012. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51013. }
  51014. };
  51015. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51016. this._poseControlledCamera = camera;
  51017. if (this._mesh) {
  51018. this._mesh.parent = this._poseControlledCamera;
  51019. }
  51020. };
  51021. PoseEnabledController.prototype.dispose = function () {
  51022. if (this._mesh) {
  51023. this._mesh.dispose();
  51024. }
  51025. this._mesh = undefined;
  51026. _super.prototype.dispose.call(this);
  51027. };
  51028. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  51029. get: function () {
  51030. return this._mesh;
  51031. },
  51032. enumerable: true,
  51033. configurable: true
  51034. });
  51035. PoseEnabledController.prototype.getForwardRay = function (length) {
  51036. if (length === void 0) { length = 100; }
  51037. if (!this.mesh) {
  51038. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  51039. }
  51040. var m = this.mesh.getWorldMatrix();
  51041. var origin = m.getTranslation();
  51042. var forward = new BABYLON.Vector3(0, 0, -1);
  51043. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  51044. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  51045. return new BABYLON.Ray(origin, direction, length);
  51046. };
  51047. return PoseEnabledController;
  51048. }(BABYLON.Gamepad));
  51049. BABYLON.PoseEnabledController = PoseEnabledController;
  51050. })(BABYLON || (BABYLON = {}));
  51051. //# sourceMappingURL=babylon.poseEnabledController.js.map
  51052. var BABYLON;
  51053. (function (BABYLON) {
  51054. var WebVRController = (function (_super) {
  51055. __extends(WebVRController, _super);
  51056. function WebVRController(vrGamepad) {
  51057. var _this = _super.call(this, vrGamepad) || this;
  51058. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51059. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51060. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51061. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51062. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51063. _this.pad = { x: 0, y: 0 };
  51064. // avoid GC, store state in a tmp object
  51065. _this._changes = {
  51066. pressChanged: false,
  51067. touchChanged: false,
  51068. valueChanged: false,
  51069. changed: false
  51070. };
  51071. _this._buttons = new Array(vrGamepad.buttons.length);
  51072. _this.hand = vrGamepad.hand;
  51073. return _this;
  51074. }
  51075. WebVRController.prototype.onButtonStateChange = function (callback) {
  51076. this._onButtonStateChange = callback;
  51077. };
  51078. WebVRController.prototype.update = function () {
  51079. _super.prototype.update.call(this);
  51080. for (var index = 0; index < this._buttons.length; index++) {
  51081. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51082. }
  51083. ;
  51084. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51085. this.pad.x = this.leftStick.x;
  51086. this.pad.y = this.leftStick.y;
  51087. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51088. }
  51089. };
  51090. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51091. if (!newState) {
  51092. newState = {
  51093. pressed: false,
  51094. touched: false,
  51095. value: 0
  51096. };
  51097. }
  51098. if (!currentState) {
  51099. this._buttons[buttonIndex] = {
  51100. pressed: newState.pressed,
  51101. touched: newState.touched,
  51102. value: newState.value
  51103. };
  51104. return;
  51105. }
  51106. this._checkChanges(newState, currentState);
  51107. if (this._changes.changed) {
  51108. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51109. this.handleButtonChange(buttonIndex, newState, this._changes);
  51110. }
  51111. this._buttons[buttonIndex].pressed = newState.pressed;
  51112. this._buttons[buttonIndex].touched = newState.touched;
  51113. // oculus triggers are never 0, thou not touched.
  51114. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51115. };
  51116. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51117. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51118. this._changes.touchChanged = newState.touched !== currentState.touched;
  51119. this._changes.valueChanged = newState.value !== currentState.value;
  51120. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51121. return this._changes;
  51122. };
  51123. return WebVRController;
  51124. }(BABYLON.PoseEnabledController));
  51125. BABYLON.WebVRController = WebVRController;
  51126. })(BABYLON || (BABYLON = {}));
  51127. //# sourceMappingURL=babylon.webVRController.js.map
  51128. var BABYLON;
  51129. (function (BABYLON) {
  51130. var OculusTouchController = (function (_super) {
  51131. __extends(OculusTouchController, _super);
  51132. function OculusTouchController(vrGamepad) {
  51133. var _this = _super.call(this, vrGamepad) || this;
  51134. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51135. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51136. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  51137. return _this;
  51138. }
  51139. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51140. var _this = this;
  51141. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51142. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51143. /*
  51144. Parent Mesh name: oculus_touch_left
  51145. - body
  51146. - trigger
  51147. - thumbstick
  51148. - grip
  51149. - button_y
  51150. - button_x
  51151. - button_enter
  51152. */
  51153. _this._defaultModel = newMeshes[1];
  51154. if (meshLoaded) {
  51155. meshLoaded(_this._defaultModel);
  51156. }
  51157. _this.attachToMesh(_this._defaultModel);
  51158. });
  51159. };
  51160. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51161. // helper getters for left and right hand.
  51162. get: function () {
  51163. if (this.hand === 'right') {
  51164. return this.onMainButtonStateChangedObservable;
  51165. }
  51166. else {
  51167. throw new Error('No A button on left hand');
  51168. }
  51169. },
  51170. enumerable: true,
  51171. configurable: true
  51172. });
  51173. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51174. get: function () {
  51175. if (this.hand === 'right') {
  51176. return this.onSecondaryButtonStateChangedObservable;
  51177. }
  51178. else {
  51179. throw new Error('No B button on left hand');
  51180. }
  51181. },
  51182. enumerable: true,
  51183. configurable: true
  51184. });
  51185. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51186. get: function () {
  51187. if (this.hand === 'left') {
  51188. return this.onMainButtonStateChangedObservable;
  51189. }
  51190. else {
  51191. throw new Error('No X button on right hand');
  51192. }
  51193. },
  51194. enumerable: true,
  51195. configurable: true
  51196. });
  51197. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51198. get: function () {
  51199. if (this.hand === 'left') {
  51200. return this.onSecondaryButtonStateChangedObservable;
  51201. }
  51202. else {
  51203. throw new Error('No Y button on right hand');
  51204. }
  51205. },
  51206. enumerable: true,
  51207. configurable: true
  51208. });
  51209. /*
  51210. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51211. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51212. 2) secondary trigger (same)
  51213. 3) A (right) X (left), touch, pressed = value
  51214. 4) B / Y
  51215. 5) thumb rest
  51216. */
  51217. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51218. var notifyObject = state; //{ state: state, changes: changes };
  51219. var triggerDirection = this.hand === 'right' ? -1 : 1;
  51220. switch (buttonIdx) {
  51221. case 0:
  51222. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51223. return;
  51224. case 1:// index trigger
  51225. if (this._defaultModel) {
  51226. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51227. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51228. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51229. }
  51230. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51231. return;
  51232. case 2:// secondary trigger
  51233. if (this._defaultModel) {
  51234. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  51235. }
  51236. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51237. return;
  51238. case 3:
  51239. if (this._defaultModel) {
  51240. if (notifyObject.pressed) {
  51241. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51242. }
  51243. else {
  51244. (this._defaultModel.getChildren()[1]).position.y = 0;
  51245. }
  51246. }
  51247. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51248. return;
  51249. case 4:
  51250. if (this._defaultModel) {
  51251. if (notifyObject.pressed) {
  51252. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51253. }
  51254. else {
  51255. (this._defaultModel.getChildren()[2]).position.y = 0;
  51256. }
  51257. }
  51258. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51259. return;
  51260. case 5:
  51261. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51262. return;
  51263. }
  51264. };
  51265. return OculusTouchController;
  51266. }(BABYLON.WebVRController));
  51267. BABYLON.OculusTouchController = OculusTouchController;
  51268. })(BABYLON || (BABYLON = {}));
  51269. //# sourceMappingURL=babylon.oculusTouchController.js.map
  51270. var BABYLON;
  51271. (function (BABYLON) {
  51272. var ViveController = (function (_super) {
  51273. __extends(ViveController, _super);
  51274. function ViveController(vrGamepad) {
  51275. var _this = _super.call(this, vrGamepad) || this;
  51276. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  51277. return _this;
  51278. }
  51279. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51280. var _this = this;
  51281. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51282. /*
  51283. Parent Mesh name: ViveWand
  51284. - body
  51285. - r_gripper
  51286. - l_gripper
  51287. - menu_button
  51288. - system_button
  51289. - trackpad
  51290. - trigger
  51291. - LED
  51292. */
  51293. _this._defaultModel = newMeshes[1];
  51294. if (meshLoaded) {
  51295. meshLoaded(_this._defaultModel);
  51296. }
  51297. _this.attachToMesh(_this._defaultModel);
  51298. });
  51299. };
  51300. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51301. get: function () {
  51302. return this.onMainButtonStateChangedObservable;
  51303. },
  51304. enumerable: true,
  51305. configurable: true
  51306. });
  51307. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51308. get: function () {
  51309. return this.onMainButtonStateChangedObservable;
  51310. },
  51311. enumerable: true,
  51312. configurable: true
  51313. });
  51314. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51315. get: function () {
  51316. return this.onSecondaryButtonStateChangedObservable;
  51317. },
  51318. enumerable: true,
  51319. configurable: true
  51320. });
  51321. /**
  51322. * Vive mapping:
  51323. * 0: touchpad
  51324. * 1: trigger
  51325. * 2: left AND right buttons
  51326. * 3: menu button
  51327. */
  51328. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51329. var notifyObject = state; //{ state: state, changes: changes };
  51330. switch (buttonIdx) {
  51331. case 0:
  51332. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51333. return;
  51334. case 1:// index trigger
  51335. if (this._defaultModel) {
  51336. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51337. }
  51338. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51339. return;
  51340. case 2:// left AND right button
  51341. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51342. return;
  51343. case 3:
  51344. if (this._defaultModel) {
  51345. if (notifyObject.pressed) {
  51346. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51347. }
  51348. else {
  51349. (this._defaultModel.getChildren()[2]).position.y = 0;
  51350. }
  51351. }
  51352. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51353. return;
  51354. }
  51355. };
  51356. return ViveController;
  51357. }(BABYLON.WebVRController));
  51358. BABYLON.ViveController = ViveController;
  51359. })(BABYLON || (BABYLON = {}));
  51360. //# sourceMappingURL=babylon.viveController.js.map
  51361. var BABYLON;
  51362. (function (BABYLON) {
  51363. var GenericController = (function (_super) {
  51364. __extends(GenericController, _super);
  51365. function GenericController(vrGamepad) {
  51366. return _super.call(this, vrGamepad) || this;
  51367. }
  51368. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51369. var _this = this;
  51370. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "genericvrcontroller.babylon", scene, function (newMeshes) {
  51371. _this._defaultModel = newMeshes[1];
  51372. if (meshLoaded) {
  51373. meshLoaded(_this._defaultModel);
  51374. }
  51375. _this.attachToMesh(_this._defaultModel);
  51376. });
  51377. };
  51378. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51379. console.log("Button id: " + buttonIdx + "state: ");
  51380. console.dir(state);
  51381. };
  51382. return GenericController;
  51383. }(BABYLON.WebVRController));
  51384. BABYLON.GenericController = GenericController;
  51385. })(BABYLON || (BABYLON = {}));
  51386. //# sourceMappingURL=babylon.genericController.js.map
  51387. /// <reference path="babylon.targetCamera.ts" />
  51388. var BABYLON;
  51389. (function (BABYLON) {
  51390. var FollowCamera = (function (_super) {
  51391. __extends(FollowCamera, _super);
  51392. function FollowCamera(name, position, scene, lockedTarget) {
  51393. var _this = _super.call(this, name, position, scene) || this;
  51394. _this.radius = 12;
  51395. _this.rotationOffset = 0;
  51396. _this.heightOffset = 4;
  51397. _this.cameraAcceleration = 0.05;
  51398. _this.maxCameraSpeed = 20;
  51399. _this.lockedTarget = lockedTarget;
  51400. return _this;
  51401. }
  51402. FollowCamera.prototype.getRadians = function (degrees) {
  51403. return degrees * Math.PI / 180;
  51404. };
  51405. FollowCamera.prototype.follow = function (cameraTarget) {
  51406. if (!cameraTarget)
  51407. return;
  51408. var yRotation;
  51409. if (cameraTarget.rotationQuaternion) {
  51410. var rotMatrix = new BABYLON.Matrix();
  51411. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  51412. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  51413. }
  51414. else {
  51415. yRotation = cameraTarget.rotation.y;
  51416. }
  51417. var radians = this.getRadians(this.rotationOffset) + yRotation;
  51418. var targetPosition = cameraTarget.getAbsolutePosition();
  51419. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  51420. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  51421. var dx = targetX - this.position.x;
  51422. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  51423. var dz = (targetZ) - this.position.z;
  51424. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  51425. var vy = dy * this.cameraAcceleration;
  51426. var vz = dz * this.cameraAcceleration * 2;
  51427. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  51428. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51429. }
  51430. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  51431. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51432. }
  51433. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  51434. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51435. }
  51436. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  51437. this.setTarget(targetPosition);
  51438. };
  51439. FollowCamera.prototype._checkInputs = function () {
  51440. _super.prototype._checkInputs.call(this);
  51441. this.follow(this.lockedTarget);
  51442. };
  51443. FollowCamera.prototype.getClassName = function () {
  51444. return "FollowCamera";
  51445. };
  51446. __decorate([
  51447. BABYLON.serialize()
  51448. ], FollowCamera.prototype, "radius", void 0);
  51449. __decorate([
  51450. BABYLON.serialize()
  51451. ], FollowCamera.prototype, "rotationOffset", void 0);
  51452. __decorate([
  51453. BABYLON.serialize()
  51454. ], FollowCamera.prototype, "heightOffset", void 0);
  51455. __decorate([
  51456. BABYLON.serialize()
  51457. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  51458. __decorate([
  51459. BABYLON.serialize()
  51460. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  51461. __decorate([
  51462. BABYLON.serializeAsMeshReference("lockedTargetId")
  51463. ], FollowCamera.prototype, "lockedTarget", void 0);
  51464. return FollowCamera;
  51465. }(BABYLON.TargetCamera));
  51466. BABYLON.FollowCamera = FollowCamera;
  51467. var ArcFollowCamera = (function (_super) {
  51468. __extends(ArcFollowCamera, _super);
  51469. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  51470. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  51471. _this.alpha = alpha;
  51472. _this.beta = beta;
  51473. _this.radius = radius;
  51474. _this.target = target;
  51475. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  51476. _this.follow();
  51477. return _this;
  51478. }
  51479. ArcFollowCamera.prototype.follow = function () {
  51480. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  51481. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  51482. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  51483. var targetPosition = this.target.getAbsolutePosition();
  51484. this.position = targetPosition.add(this._cartesianCoordinates);
  51485. this.setTarget(targetPosition);
  51486. };
  51487. ArcFollowCamera.prototype._checkInputs = function () {
  51488. _super.prototype._checkInputs.call(this);
  51489. this.follow();
  51490. };
  51491. ArcFollowCamera.prototype.getClassName = function () {
  51492. return "ArcFollowCamera";
  51493. };
  51494. return ArcFollowCamera;
  51495. }(BABYLON.TargetCamera));
  51496. BABYLON.ArcFollowCamera = ArcFollowCamera;
  51497. })(BABYLON || (BABYLON = {}));
  51498. //# sourceMappingURL=babylon.followCamera.js.map
  51499. /// <reference path="babylon.touchCamera.ts" />
  51500. var BABYLON;
  51501. (function (BABYLON) {
  51502. // We're mainly based on the logic defined into the FreeCamera code
  51503. var UniversalCamera = (function (_super) {
  51504. __extends(UniversalCamera, _super);
  51505. //-- end properties for backward compatibility for inputs
  51506. function UniversalCamera(name, position, scene) {
  51507. var _this = _super.call(this, name, position, scene) || this;
  51508. _this.inputs.addGamepad();
  51509. return _this;
  51510. }
  51511. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  51512. //-- Begin properties for backward compatibility for inputs
  51513. get: function () {
  51514. var gamepad = this.inputs.attached["gamepad"];
  51515. if (gamepad)
  51516. return gamepad.gamepadAngularSensibility;
  51517. },
  51518. set: function (value) {
  51519. var gamepad = this.inputs.attached["gamepad"];
  51520. if (gamepad)
  51521. gamepad.gamepadAngularSensibility = value;
  51522. },
  51523. enumerable: true,
  51524. configurable: true
  51525. });
  51526. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  51527. get: function () {
  51528. var gamepad = this.inputs.attached["gamepad"];
  51529. if (gamepad)
  51530. return gamepad.gamepadMoveSensibility;
  51531. },
  51532. set: function (value) {
  51533. var gamepad = this.inputs.attached["gamepad"];
  51534. if (gamepad)
  51535. gamepad.gamepadMoveSensibility = value;
  51536. },
  51537. enumerable: true,
  51538. configurable: true
  51539. });
  51540. UniversalCamera.prototype.getClassName = function () {
  51541. return "UniversalCamera";
  51542. };
  51543. return UniversalCamera;
  51544. }(BABYLON.TouchCamera));
  51545. BABYLON.UniversalCamera = UniversalCamera;
  51546. })(BABYLON || (BABYLON = {}));
  51547. //# sourceMappingURL=babylon.universalCamera.js.map
  51548. /// <reference path="babylon.universalCamera.ts" />
  51549. var BABYLON;
  51550. (function (BABYLON) {
  51551. // We're mainly based on the logic defined into the FreeCamera code
  51552. var GamepadCamera = (function (_super) {
  51553. __extends(GamepadCamera, _super);
  51554. //-- end properties for backward compatibility for inputs
  51555. function GamepadCamera(name, position, scene) {
  51556. return _super.call(this, name, position, scene) || this;
  51557. }
  51558. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51559. //-- Begin properties for backward compatibility for inputs
  51560. get: function () {
  51561. var gamepad = this.inputs.attached["gamepad"];
  51562. if (gamepad)
  51563. return gamepad.gamepadAngularSensibility;
  51564. },
  51565. set: function (value) {
  51566. var gamepad = this.inputs.attached["gamepad"];
  51567. if (gamepad)
  51568. gamepad.gamepadAngularSensibility = value;
  51569. },
  51570. enumerable: true,
  51571. configurable: true
  51572. });
  51573. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51574. get: function () {
  51575. var gamepad = this.inputs.attached["gamepad"];
  51576. if (gamepad)
  51577. return gamepad.gamepadMoveSensibility;
  51578. },
  51579. set: function (value) {
  51580. var gamepad = this.inputs.attached["gamepad"];
  51581. if (gamepad)
  51582. gamepad.gamepadMoveSensibility = value;
  51583. },
  51584. enumerable: true,
  51585. configurable: true
  51586. });
  51587. GamepadCamera.prototype.getClassName = function () {
  51588. return "GamepadCamera";
  51589. };
  51590. return GamepadCamera;
  51591. }(BABYLON.UniversalCamera));
  51592. BABYLON.GamepadCamera = GamepadCamera;
  51593. })(BABYLON || (BABYLON = {}));
  51594. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51595. var BABYLON;
  51596. (function (BABYLON) {
  51597. var PostProcessRenderPipelineManager = (function () {
  51598. function PostProcessRenderPipelineManager() {
  51599. this._renderPipelines = {};
  51600. }
  51601. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  51602. this._renderPipelines[renderPipeline._name] = renderPipeline;
  51603. };
  51604. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  51605. var renderPipeline = this._renderPipelines[renderPipelineName];
  51606. if (!renderPipeline) {
  51607. return;
  51608. }
  51609. renderPipeline._attachCameras(cameras, unique);
  51610. };
  51611. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  51612. var renderPipeline = this._renderPipelines[renderPipelineName];
  51613. if (!renderPipeline) {
  51614. return;
  51615. }
  51616. renderPipeline._detachCameras(cameras);
  51617. };
  51618. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  51619. var renderPipeline = this._renderPipelines[renderPipelineName];
  51620. if (!renderPipeline) {
  51621. return;
  51622. }
  51623. renderPipeline._enableEffect(renderEffectName, cameras);
  51624. };
  51625. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  51626. var renderPipeline = this._renderPipelines[renderPipelineName];
  51627. if (!renderPipeline) {
  51628. return;
  51629. }
  51630. renderPipeline._disableEffect(renderEffectName, cameras);
  51631. };
  51632. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  51633. var renderPipeline = this._renderPipelines[renderPipelineName];
  51634. if (!renderPipeline) {
  51635. return;
  51636. }
  51637. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  51638. };
  51639. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  51640. var renderPipeline = this._renderPipelines[renderPipelineName];
  51641. if (!renderPipeline) {
  51642. return;
  51643. }
  51644. renderPipeline._disableDisplayOnlyPass(cameras);
  51645. };
  51646. PostProcessRenderPipelineManager.prototype.update = function () {
  51647. for (var renderPipelineName in this._renderPipelines) {
  51648. var pipeline = this._renderPipelines[renderPipelineName];
  51649. if (!pipeline.isSupported) {
  51650. pipeline.dispose();
  51651. delete this._renderPipelines[renderPipelineName];
  51652. }
  51653. else {
  51654. pipeline._update();
  51655. }
  51656. }
  51657. };
  51658. return PostProcessRenderPipelineManager;
  51659. }());
  51660. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  51661. })(BABYLON || (BABYLON = {}));
  51662. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  51663. var BABYLON;
  51664. (function (BABYLON) {
  51665. var PostProcessRenderPass = (function () {
  51666. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  51667. this._enabled = true;
  51668. this._refCount = 0;
  51669. this._name = name;
  51670. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  51671. this.setRenderList(renderList);
  51672. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  51673. this._renderTexture.onAfterRenderObservable.add(afterRender);
  51674. this._scene = scene;
  51675. this._renderList = renderList;
  51676. }
  51677. // private
  51678. PostProcessRenderPass.prototype._incRefCount = function () {
  51679. if (this._refCount === 0) {
  51680. this._scene.customRenderTargets.push(this._renderTexture);
  51681. }
  51682. return ++this._refCount;
  51683. };
  51684. PostProcessRenderPass.prototype._decRefCount = function () {
  51685. this._refCount--;
  51686. if (this._refCount <= 0) {
  51687. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  51688. }
  51689. return this._refCount;
  51690. };
  51691. PostProcessRenderPass.prototype._update = function () {
  51692. this.setRenderList(this._renderList);
  51693. };
  51694. // public
  51695. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  51696. this._renderTexture.renderList = renderList;
  51697. };
  51698. PostProcessRenderPass.prototype.getRenderTexture = function () {
  51699. return this._renderTexture;
  51700. };
  51701. return PostProcessRenderPass;
  51702. }());
  51703. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  51704. })(BABYLON || (BABYLON = {}));
  51705. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  51706. var BABYLON;
  51707. (function (BABYLON) {
  51708. var PostProcessRenderEffect = (function () {
  51709. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  51710. this._engine = engine;
  51711. this._name = name;
  51712. this._singleInstance = singleInstance || true;
  51713. this._getPostProcess = getPostProcess;
  51714. this._cameras = [];
  51715. this._indicesForCamera = [];
  51716. this._postProcesses = {};
  51717. this._renderPasses = {};
  51718. this._renderEffectAsPasses = {};
  51719. }
  51720. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  51721. get: function () {
  51722. for (var index in this._postProcesses) {
  51723. if (!this._postProcesses[index].isSupported) {
  51724. return false;
  51725. }
  51726. }
  51727. return true;
  51728. },
  51729. enumerable: true,
  51730. configurable: true
  51731. });
  51732. PostProcessRenderEffect.prototype._update = function () {
  51733. for (var renderPassName in this._renderPasses) {
  51734. this._renderPasses[renderPassName]._update();
  51735. }
  51736. };
  51737. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  51738. this._renderPasses[renderPass._name] = renderPass;
  51739. this._linkParameters();
  51740. };
  51741. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  51742. delete this._renderPasses[renderPass._name];
  51743. this._linkParameters();
  51744. };
  51745. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  51746. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  51747. this._linkParameters();
  51748. };
  51749. PostProcessRenderEffect.prototype.getPass = function (passName) {
  51750. for (var renderPassName in this._renderPasses) {
  51751. if (renderPassName === passName) {
  51752. return this._renderPasses[passName];
  51753. }
  51754. }
  51755. };
  51756. PostProcessRenderEffect.prototype.emptyPasses = function () {
  51757. this._renderPasses = {};
  51758. this._linkParameters();
  51759. };
  51760. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  51761. var cameraKey;
  51762. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51763. for (var i = 0; i < _cam.length; i++) {
  51764. var camera = _cam[i];
  51765. var cameraName = camera.name;
  51766. if (this._singleInstance) {
  51767. cameraKey = 0;
  51768. }
  51769. else {
  51770. cameraKey = cameraName;
  51771. }
  51772. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  51773. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  51774. if (!this._indicesForCamera[cameraName]) {
  51775. this._indicesForCamera[cameraName] = [];
  51776. }
  51777. this._indicesForCamera[cameraName].push(index);
  51778. if (this._cameras.indexOf(camera) === -1) {
  51779. this._cameras[cameraName] = camera;
  51780. }
  51781. for (var passName in this._renderPasses) {
  51782. this._renderPasses[passName]._incRefCount();
  51783. }
  51784. }
  51785. this._linkParameters();
  51786. };
  51787. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  51788. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51789. for (var i = 0; i < _cam.length; i++) {
  51790. var camera = _cam[i];
  51791. var cameraName = camera.name;
  51792. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51793. var index = this._cameras.indexOf(cameraName);
  51794. this._indicesForCamera.splice(index, 1);
  51795. this._cameras.splice(index, 1);
  51796. for (var passName in this._renderPasses) {
  51797. this._renderPasses[passName]._decRefCount();
  51798. }
  51799. }
  51800. };
  51801. PostProcessRenderEffect.prototype._enable = function (cameras) {
  51802. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51803. for (var i = 0; i < _cam.length; i++) {
  51804. var camera = _cam[i];
  51805. var cameraName = camera.name;
  51806. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  51807. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  51808. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  51809. }
  51810. }
  51811. for (var passName in this._renderPasses) {
  51812. this._renderPasses[passName]._incRefCount();
  51813. }
  51814. }
  51815. };
  51816. PostProcessRenderEffect.prototype._disable = function (cameras) {
  51817. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51818. for (var i = 0; i < _cam.length; i++) {
  51819. var camera = _cam[i];
  51820. var cameraName = camera.Name;
  51821. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51822. for (var passName in this._renderPasses) {
  51823. this._renderPasses[passName]._decRefCount();
  51824. }
  51825. }
  51826. };
  51827. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  51828. if (this._singleInstance) {
  51829. return this._postProcesses[0];
  51830. }
  51831. else {
  51832. return this._postProcesses[camera.name];
  51833. }
  51834. };
  51835. PostProcessRenderEffect.prototype._linkParameters = function () {
  51836. var _this = this;
  51837. for (var index in this._postProcesses) {
  51838. if (this.applyParameters) {
  51839. this.applyParameters(this._postProcesses[index]);
  51840. }
  51841. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  51842. _this._linkTextures(effect);
  51843. });
  51844. }
  51845. };
  51846. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  51847. for (var renderPassName in this._renderPasses) {
  51848. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  51849. }
  51850. for (var renderEffectName in this._renderEffectAsPasses) {
  51851. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  51852. }
  51853. };
  51854. return PostProcessRenderEffect;
  51855. }());
  51856. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  51857. })(BABYLON || (BABYLON = {}));
  51858. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  51859. var BABYLON;
  51860. (function (BABYLON) {
  51861. var PostProcessRenderPipeline = (function () {
  51862. function PostProcessRenderPipeline(engine, name) {
  51863. this._engine = engine;
  51864. this._name = name;
  51865. this._renderEffects = new Array();
  51866. this._renderEffectsForIsolatedPass = new Array();
  51867. this._cameras = [];
  51868. }
  51869. PostProcessRenderPipeline.prototype.getClassName = function () {
  51870. return "PostProcessRenderPipeline";
  51871. };
  51872. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  51873. get: function () {
  51874. for (var renderEffectName in this._renderEffects) {
  51875. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  51876. if (!this._renderEffects[renderEffectName].isSupported) {
  51877. return false;
  51878. }
  51879. }
  51880. }
  51881. return true;
  51882. },
  51883. enumerable: true,
  51884. configurable: true
  51885. });
  51886. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  51887. this._renderEffects[renderEffect._name] = renderEffect;
  51888. };
  51889. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  51890. var renderEffects = this._renderEffects[renderEffectName];
  51891. if (!renderEffects) {
  51892. return;
  51893. }
  51894. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  51895. };
  51896. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  51897. var renderEffects = this._renderEffects[renderEffectName];
  51898. if (!renderEffects) {
  51899. return;
  51900. }
  51901. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  51902. };
  51903. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  51904. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51905. var indicesToDelete = [];
  51906. var i;
  51907. for (i = 0; i < _cam.length; i++) {
  51908. var camera = _cam[i];
  51909. var cameraName = camera.name;
  51910. if (this._cameras.indexOf(camera) === -1) {
  51911. this._cameras[cameraName] = camera;
  51912. }
  51913. else if (unique) {
  51914. indicesToDelete.push(i);
  51915. }
  51916. }
  51917. for (i = 0; i < indicesToDelete.length; i++) {
  51918. cameras.splice(indicesToDelete[i], 1);
  51919. }
  51920. for (var renderEffectName in this._renderEffects) {
  51921. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  51922. this._renderEffects[renderEffectName]._attachCameras(_cam);
  51923. }
  51924. }
  51925. };
  51926. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  51927. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51928. for (var renderEffectName in this._renderEffects) {
  51929. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  51930. this._renderEffects[renderEffectName]._detachCameras(_cam);
  51931. }
  51932. }
  51933. for (var i = 0; i < _cam.length; i++) {
  51934. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  51935. }
  51936. };
  51937. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  51938. var _this = this;
  51939. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51940. var pass = null;
  51941. var renderEffectName;
  51942. for (renderEffectName in this._renderEffects) {
  51943. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  51944. pass = this._renderEffects[renderEffectName].getPass(passName);
  51945. if (pass != null) {
  51946. break;
  51947. }
  51948. }
  51949. }
  51950. if (pass === null) {
  51951. return;
  51952. }
  51953. for (renderEffectName in this._renderEffects) {
  51954. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  51955. this._renderEffects[renderEffectName]._disable(_cam);
  51956. }
  51957. }
  51958. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  51959. for (var i = 0; i < _cam.length; i++) {
  51960. var camera = _cam[i];
  51961. var cameraName = camera.name;
  51962. 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); });
  51963. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  51964. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  51965. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  51966. }
  51967. };
  51968. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  51969. var _this = this;
  51970. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51971. for (var i = 0; i < _cam.length; i++) {
  51972. var camera = _cam[i];
  51973. var cameraName = camera.name;
  51974. 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); });
  51975. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  51976. }
  51977. for (var renderEffectName in this._renderEffects) {
  51978. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  51979. this._renderEffects[renderEffectName]._enable(_cam);
  51980. }
  51981. }
  51982. };
  51983. PostProcessRenderPipeline.prototype._update = function () {
  51984. for (var renderEffectName in this._renderEffects) {
  51985. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  51986. this._renderEffects[renderEffectName]._update();
  51987. }
  51988. }
  51989. for (var i = 0; i < this._cameras.length; i++) {
  51990. var cameraName = this._cameras[i].name;
  51991. if (this._renderEffectsForIsolatedPass[cameraName]) {
  51992. this._renderEffectsForIsolatedPass[cameraName]._update();
  51993. }
  51994. }
  51995. };
  51996. PostProcessRenderPipeline.prototype._reset = function () {
  51997. this._renderEffects = new Array();
  51998. this._renderEffectsForIsolatedPass = new Array();
  51999. };
  52000. PostProcessRenderPipeline.prototype.dispose = function () {
  52001. // Must be implemented by children
  52002. };
  52003. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  52004. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  52005. __decorate([
  52006. BABYLON.serialize()
  52007. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  52008. return PostProcessRenderPipeline;
  52009. }());
  52010. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  52011. })(BABYLON || (BABYLON = {}));
  52012. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  52013. var BABYLON;
  52014. (function (BABYLON) {
  52015. var DepthRenderer = (function () {
  52016. function DepthRenderer(scene, type) {
  52017. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  52018. var _this = this;
  52019. this._viewMatrix = BABYLON.Matrix.Zero();
  52020. this._projectionMatrix = BABYLON.Matrix.Zero();
  52021. this._transformMatrix = BABYLON.Matrix.Zero();
  52022. this._worldViewProjection = BABYLON.Matrix.Zero();
  52023. this._scene = scene;
  52024. var engine = scene.getEngine();
  52025. // Render target
  52026. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  52027. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52028. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52029. this._depthMap.refreshRate = 1;
  52030. this._depthMap.renderParticles = false;
  52031. this._depthMap.renderList = null;
  52032. // set default depth value to 1.0 (far away)
  52033. this._depthMap.onClearObservable.add(function (engine) {
  52034. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52035. });
  52036. // Custom render function
  52037. var renderSubMesh = function (subMesh) {
  52038. var mesh = subMesh.getRenderingMesh();
  52039. var scene = _this._scene;
  52040. var engine = scene.getEngine();
  52041. // Culling
  52042. engine.setState(subMesh.getMaterial().backFaceCulling);
  52043. // Managing instances
  52044. var batch = mesh._getInstancesRenderList(subMesh._id);
  52045. if (batch.mustReturn) {
  52046. return;
  52047. }
  52048. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52049. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52050. engine.enableEffect(_this._effect);
  52051. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52052. var material = subMesh.getMaterial();
  52053. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52054. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  52055. // Alpha test
  52056. if (material && material.needAlphaTesting()) {
  52057. var alphaTexture = material.getAlphaTestTexture();
  52058. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52059. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52060. }
  52061. // Bones
  52062. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52063. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52064. }
  52065. // Draw
  52066. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52067. }
  52068. };
  52069. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  52070. var index;
  52071. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52072. renderSubMesh(opaqueSubMeshes.data[index]);
  52073. }
  52074. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52075. renderSubMesh(alphaTestSubMeshes.data[index]);
  52076. }
  52077. };
  52078. }
  52079. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52080. var material = subMesh.getMaterial();
  52081. if (material.disableDepthWrite) {
  52082. return false;
  52083. }
  52084. var defines = [];
  52085. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52086. var mesh = subMesh.getMesh();
  52087. var scene = mesh.getScene();
  52088. // Alpha test
  52089. if (material && material.needAlphaTesting()) {
  52090. defines.push("#define ALPHATEST");
  52091. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52092. attribs.push(BABYLON.VertexBuffer.UVKind);
  52093. defines.push("#define UV1");
  52094. }
  52095. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52096. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52097. defines.push("#define UV2");
  52098. }
  52099. }
  52100. // Bones
  52101. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52102. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52103. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52104. if (mesh.numBoneInfluencers > 4) {
  52105. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52106. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52107. }
  52108. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52109. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52110. }
  52111. else {
  52112. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52113. }
  52114. // Instances
  52115. if (useInstances) {
  52116. defines.push("#define INSTANCES");
  52117. attribs.push("world0");
  52118. attribs.push("world1");
  52119. attribs.push("world2");
  52120. attribs.push("world3");
  52121. }
  52122. // Get correct effect
  52123. var join = defines.join("\n");
  52124. if (this._cachedDefines !== join) {
  52125. this._cachedDefines = join;
  52126. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  52127. }
  52128. return this._effect.isReady();
  52129. };
  52130. DepthRenderer.prototype.getDepthMap = function () {
  52131. return this._depthMap;
  52132. };
  52133. // Methods
  52134. DepthRenderer.prototype.dispose = function () {
  52135. this._depthMap.dispose();
  52136. };
  52137. return DepthRenderer;
  52138. }());
  52139. BABYLON.DepthRenderer = DepthRenderer;
  52140. })(BABYLON || (BABYLON = {}));
  52141. //# sourceMappingURL=babylon.depthRenderer.js.map
  52142. var BABYLON;
  52143. (function (BABYLON) {
  52144. var SSAORenderingPipeline = (function (_super) {
  52145. __extends(SSAORenderingPipeline, _super);
  52146. /**
  52147. * @constructor
  52148. * @param {string} name - The rendering pipeline name
  52149. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52150. * @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 }
  52151. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52152. */
  52153. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52154. var _this = _super.call(this, scene.getEngine(), name) || this;
  52155. // Members
  52156. /**
  52157. * The PassPostProcess id in the pipeline that contains the original scene color
  52158. * @type {string}
  52159. */
  52160. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52161. /**
  52162. * The SSAO PostProcess id in the pipeline
  52163. * @type {string}
  52164. */
  52165. _this.SSAORenderEffect = "SSAORenderEffect";
  52166. /**
  52167. * The horizontal blur PostProcess id in the pipeline
  52168. * @type {string}
  52169. */
  52170. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52171. /**
  52172. * The vertical blur PostProcess id in the pipeline
  52173. * @type {string}
  52174. */
  52175. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52176. /**
  52177. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52178. * @type {string}
  52179. */
  52180. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52181. /**
  52182. * The output strength of the SSAO post-process. Default value is 1.0.
  52183. * @type {number}
  52184. */
  52185. _this.totalStrength = 1.0;
  52186. /**
  52187. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52188. * @type {number}
  52189. */
  52190. _this.radius = 0.0001;
  52191. /**
  52192. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52193. * Must not be equal to fallOff and superior to fallOff.
  52194. * Default value is 0.975
  52195. * @type {number}
  52196. */
  52197. _this.area = 0.0075;
  52198. /**
  52199. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52200. * Must not be equal to area and inferior to area.
  52201. * Default value is 0.0
  52202. * @type {number}
  52203. */
  52204. _this.fallOff = 0.000001;
  52205. /**
  52206. * The base color of the SSAO post-process
  52207. * The final result is "base + ssao" between [0, 1]
  52208. * @type {number}
  52209. */
  52210. _this.base = 0.5;
  52211. _this._firstUpdate = true;
  52212. _this._scene = scene;
  52213. // Set up assets
  52214. _this._createRandomTexture();
  52215. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52216. var ssaoRatio = ratio.ssaoRatio || ratio;
  52217. var combineRatio = ratio.combineRatio || ratio;
  52218. _this._ratio = {
  52219. ssaoRatio: ssaoRatio,
  52220. combineRatio: combineRatio
  52221. };
  52222. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52223. _this._createSSAOPostProcess(ssaoRatio);
  52224. _this._createBlurPostProcess(ssaoRatio);
  52225. _this._createSSAOCombinePostProcess(combineRatio);
  52226. // Set up pipeline
  52227. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52228. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52229. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52230. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52231. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52232. // Finish
  52233. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52234. if (cameras)
  52235. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52236. return _this;
  52237. }
  52238. // Public Methods
  52239. /**
  52240. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52241. */
  52242. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52243. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52244. for (var i = 0; i < this._scene.cameras.length; i++) {
  52245. var camera = this._scene.cameras[i];
  52246. this._originalColorPostProcess.dispose(camera);
  52247. this._ssaoPostProcess.dispose(camera);
  52248. this._blurHPostProcess.dispose(camera);
  52249. this._blurVPostProcess.dispose(camera);
  52250. this._ssaoCombinePostProcess.dispose(camera);
  52251. }
  52252. this._randomTexture.dispose();
  52253. if (disableDepthRender)
  52254. this._scene.disableDepthRenderer();
  52255. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52256. _super.prototype.dispose.call(this);
  52257. };
  52258. // Private Methods
  52259. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52260. var _this = this;
  52261. /*
  52262. var samplerOffsets = [
  52263. -8.0, -6.0, -4.0, -2.0,
  52264. 0.0,
  52265. 2.0, 4.0, 6.0, 8.0
  52266. ];
  52267. */
  52268. var samples = 16;
  52269. var samplerOffsets = [];
  52270. for (var i = -8; i < 8; i++) {
  52271. samplerOffsets.push(i * 2);
  52272. }
  52273. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  52274. this._blurHPostProcess.onApply = function (effect) {
  52275. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52276. effect.setTexture("depthSampler", _this._depthTexture);
  52277. if (_this._firstUpdate) {
  52278. effect.setArray("samplerOffsets", samplerOffsets);
  52279. }
  52280. };
  52281. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  52282. this._blurVPostProcess.onApply = function (effect) {
  52283. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52284. effect.setTexture("depthSampler", _this._depthTexture);
  52285. if (_this._firstUpdate) {
  52286. effect.setArray("samplerOffsets", samplerOffsets);
  52287. _this._firstUpdate = false;
  52288. }
  52289. };
  52290. };
  52291. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52292. var _this = this;
  52293. var numSamples = 16;
  52294. var sampleSphere = [
  52295. 0.5381, 0.1856, -0.4319,
  52296. 0.1379, 0.2486, 0.4430,
  52297. 0.3371, 0.5679, -0.0057,
  52298. -0.6999, -0.0451, -0.0019,
  52299. 0.0689, -0.1598, -0.8547,
  52300. 0.0560, 0.0069, -0.1843,
  52301. -0.0146, 0.1402, 0.0762,
  52302. 0.0100, -0.1924, -0.0344,
  52303. -0.3577, -0.5301, -0.4358,
  52304. -0.3169, 0.1063, 0.0158,
  52305. 0.0103, -0.5869, 0.0046,
  52306. -0.0897, -0.4940, 0.3287,
  52307. 0.7119, -0.0154, -0.0918,
  52308. -0.0533, 0.0596, -0.5411,
  52309. 0.0352, -0.0631, 0.5460,
  52310. -0.4776, 0.2847, -0.0271
  52311. ];
  52312. var samplesFactor = 1.0 / numSamples;
  52313. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52314. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52315. "area", "fallOff", "base", "range", "viewport"
  52316. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52317. var viewport = new BABYLON.Vector2(0, 0);
  52318. this._ssaoPostProcess.onApply = function (effect) {
  52319. if (_this._firstUpdate) {
  52320. effect.setArray3("sampleSphere", sampleSphere);
  52321. effect.setFloat("samplesFactor", samplesFactor);
  52322. effect.setFloat("randTextureTiles", 4.0);
  52323. }
  52324. effect.setFloat("totalStrength", _this.totalStrength);
  52325. effect.setFloat("radius", _this.radius);
  52326. effect.setFloat("area", _this.area);
  52327. effect.setFloat("fallOff", _this.fallOff);
  52328. effect.setFloat("base", _this.base);
  52329. effect.setTexture("textureSampler", _this._depthTexture);
  52330. effect.setTexture("randomSampler", _this._randomTexture);
  52331. };
  52332. };
  52333. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52334. var _this = this;
  52335. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52336. this._ssaoCombinePostProcess.onApply = function (effect) {
  52337. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52338. };
  52339. };
  52340. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52341. var size = 512;
  52342. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52343. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52344. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52345. var context = this._randomTexture.getContext();
  52346. var rand = function (min, max) {
  52347. return Math.random() * (max - min) + min;
  52348. };
  52349. var randVector = BABYLON.Vector3.Zero();
  52350. for (var x = 0; x < size; x++) {
  52351. for (var y = 0; y < size; y++) {
  52352. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52353. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52354. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52355. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52356. context.fillRect(x, y, 1, 1);
  52357. }
  52358. }
  52359. this._randomTexture.update(false);
  52360. };
  52361. __decorate([
  52362. BABYLON.serialize()
  52363. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52364. __decorate([
  52365. BABYLON.serialize()
  52366. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52367. __decorate([
  52368. BABYLON.serialize()
  52369. ], SSAORenderingPipeline.prototype, "area", void 0);
  52370. __decorate([
  52371. BABYLON.serialize()
  52372. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52373. __decorate([
  52374. BABYLON.serialize()
  52375. ], SSAORenderingPipeline.prototype, "base", void 0);
  52376. __decorate([
  52377. BABYLON.serialize()
  52378. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52379. return SSAORenderingPipeline;
  52380. }(BABYLON.PostProcessRenderPipeline));
  52381. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52382. })(BABYLON || (BABYLON = {}));
  52383. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52384. var BABYLON;
  52385. (function (BABYLON) {
  52386. var SSAO2RenderingPipeline = (function (_super) {
  52387. __extends(SSAO2RenderingPipeline, _super);
  52388. /**
  52389. * @constructor
  52390. * @param {string} name - The rendering pipeline name
  52391. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52392. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  52393. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52394. */
  52395. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  52396. var _this = _super.call(this, scene.getEngine(), name) || this;
  52397. // Members
  52398. /**
  52399. * The PassPostProcess id in the pipeline that contains the original scene color
  52400. * @type {string}
  52401. */
  52402. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52403. /**
  52404. * The SSAO PostProcess id in the pipeline
  52405. * @type {string}
  52406. */
  52407. _this.SSAORenderEffect = "SSAORenderEffect";
  52408. /**
  52409. * The horizontal blur PostProcess id in the pipeline
  52410. * @type {string}
  52411. */
  52412. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52413. /**
  52414. * The vertical blur PostProcess id in the pipeline
  52415. * @type {string}
  52416. */
  52417. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52418. /**
  52419. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52420. * @type {string}
  52421. */
  52422. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52423. /**
  52424. * The output strength of the SSAO post-process. Default value is 1.0.
  52425. * @type {number}
  52426. */
  52427. _this.totalStrength = 1.0;
  52428. /**
  52429. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  52430. * @type {number}
  52431. */
  52432. _this.maxZ = 100.0;
  52433. /**
  52434. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  52435. * @type {number}
  52436. */
  52437. _this.minZAspect = 0.2;
  52438. /**
  52439. * Number of samples used for the SSAO calculations. Default value is 8
  52440. * @type {number}
  52441. */
  52442. _this._samples = 8;
  52443. /**
  52444. * Are we using bilateral blur ?
  52445. * @type {boolean}
  52446. */
  52447. _this._expensiveBlur = true;
  52448. /**
  52449. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  52450. * @type {number}
  52451. */
  52452. _this.radius = 2.0;
  52453. /**
  52454. * The base color of the SSAO post-process
  52455. * The final result is "base + ssao" between [0, 1]
  52456. * @type {number}
  52457. */
  52458. _this.base = 0.1;
  52459. _this._firstUpdate = true;
  52460. _this._scene = scene;
  52461. if (!_this.isSupported) {
  52462. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  52463. return _this;
  52464. }
  52465. var ssaoRatio = ratio.ssaoRatio || ratio;
  52466. var blurRatio = ratio.blurRatio || ratio;
  52467. _this._ratio = {
  52468. ssaoRatio: ssaoRatio,
  52469. blurRatio: blurRatio
  52470. };
  52471. // Set up assets
  52472. _this._createRandomTexture();
  52473. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  52474. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  52475. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52476. _this._createSSAOPostProcess(1.0);
  52477. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  52478. _this._createSSAOCombinePostProcess(blurRatio);
  52479. // Set up pipeline
  52480. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52481. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52482. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52483. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52484. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52485. // Finish
  52486. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52487. if (cameras)
  52488. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52489. return _this;
  52490. }
  52491. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  52492. get: function () {
  52493. return this._samples;
  52494. },
  52495. set: function (n) {
  52496. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  52497. this._samples = n;
  52498. this._sampleSphere = this._generateHemisphere();
  52499. this._firstUpdate = true;
  52500. },
  52501. enumerable: true,
  52502. configurable: true
  52503. });
  52504. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  52505. get: function () {
  52506. return this._expensiveBlur;
  52507. },
  52508. set: function (b) {
  52509. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  52510. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  52511. this._expensiveBlur = b;
  52512. this._firstUpdate = true;
  52513. },
  52514. enumerable: true,
  52515. configurable: true
  52516. });
  52517. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  52518. /**
  52519. * Support test.
  52520. * @type {boolean}
  52521. */
  52522. get: function () {
  52523. var engine = BABYLON.Engine.LastCreatedEngine;
  52524. return engine.webGLVersion > 1;
  52525. },
  52526. enumerable: true,
  52527. configurable: true
  52528. });
  52529. // Public Methods
  52530. /**
  52531. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52532. */
  52533. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  52534. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  52535. for (var i = 0; i < this._scene.cameras.length; i++) {
  52536. var camera = this._scene.cameras[i];
  52537. this._originalColorPostProcess.dispose(camera);
  52538. this._ssaoPostProcess.dispose(camera);
  52539. this._blurHPostProcess.dispose(camera);
  52540. this._blurVPostProcess.dispose(camera);
  52541. this._ssaoCombinePostProcess.dispose(camera);
  52542. }
  52543. this._randomTexture.dispose();
  52544. if (disableGeometryBufferRenderer)
  52545. this._scene.disableGeometryBufferRenderer();
  52546. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52547. _super.prototype.dispose.call(this);
  52548. };
  52549. // Private Methods
  52550. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  52551. var _this = this;
  52552. var samples = 16;
  52553. this._samplerOffsets = [];
  52554. var expensive = this.expensiveBlur;
  52555. for (var i = -8; i < 8; i++) {
  52556. this._samplerOffsets.push(i * 2 + 0.5);
  52557. }
  52558. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  52559. this._blurHPostProcess.onApply = function (effect) {
  52560. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52561. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52562. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52563. effect.setFloat("radius", _this.radius);
  52564. effect.setTexture("depthSampler", _this._depthTexture);
  52565. if (_this._firstUpdate) {
  52566. effect.setArray("samplerOffsets", _this._samplerOffsets);
  52567. }
  52568. };
  52569. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  52570. this._blurVPostProcess.onApply = function (effect) {
  52571. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52572. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52573. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52574. effect.setFloat("radius", _this.radius);
  52575. effect.setTexture("depthSampler", _this._depthTexture);
  52576. if (_this._firstUpdate) {
  52577. effect.setArray("samplerOffsets", _this._samplerOffsets);
  52578. _this._firstUpdate = false;
  52579. }
  52580. };
  52581. };
  52582. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  52583. var numSamples = this.samples;
  52584. var result = [];
  52585. var vector, scale;
  52586. var rand = function (min, max) {
  52587. return Math.random() * (max - min) + min;
  52588. };
  52589. var lerp = function (start, end, percent) {
  52590. return (start + percent * (end - start));
  52591. };
  52592. var i = 0;
  52593. var normal = new BABYLON.Vector3(0, 0, 1);
  52594. while (i < numSamples) {
  52595. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  52596. vector.normalize();
  52597. scale = i / numSamples;
  52598. scale = lerp(0.1, 1.0, scale * scale);
  52599. vector.scaleInPlace(scale);
  52600. result.push(vector.x, vector.y, vector.z);
  52601. i++;
  52602. }
  52603. return result;
  52604. };
  52605. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52606. var _this = this;
  52607. var numSamples = this.samples;
  52608. this._sampleSphere = this._generateHemisphere();
  52609. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  52610. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52611. "base", "range", "projection", "near", "far", "texelSize",
  52612. "xViewport", "yViewport", "maxZ", "minZAspect"
  52613. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52614. this._ssaoPostProcess.onApply = function (effect) {
  52615. if (_this._firstUpdate) {
  52616. effect.setArray3("sampleSphere", _this._sampleSphere);
  52617. effect.setFloat("randTextureTiles", 4.0);
  52618. }
  52619. effect.setFloat("samplesFactor", 1 / _this.samples);
  52620. effect.setFloat("totalStrength", _this.totalStrength);
  52621. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  52622. effect.setFloat("radius", _this.radius);
  52623. effect.setFloat("maxZ", _this.maxZ);
  52624. effect.setFloat("minZAspect", _this.minZAspect);
  52625. effect.setFloat("base", _this.base);
  52626. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52627. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52628. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  52629. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  52630. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  52631. effect.setTexture("textureSampler", _this._depthTexture);
  52632. effect.setTexture("normalSampler", _this._normalTexture);
  52633. effect.setTexture("randomSampler", _this._randomTexture);
  52634. };
  52635. };
  52636. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52637. var _this = this;
  52638. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52639. this._ssaoCombinePostProcess.onApply = function (effect) {
  52640. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52641. };
  52642. };
  52643. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  52644. var size = 512;
  52645. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52646. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52647. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52648. var context = this._randomTexture.getContext();
  52649. var rand = function (min, max) {
  52650. return Math.random() * (max - min) + min;
  52651. };
  52652. var randVector = BABYLON.Vector3.Zero();
  52653. for (var x = 0; x < size; x++) {
  52654. for (var y = 0; y < size; y++) {
  52655. randVector.x = rand(0.0, 1.0);
  52656. randVector.y = rand(0.0, 1.0);
  52657. randVector.z = 0.0;
  52658. randVector.normalize();
  52659. randVector.scaleInPlace(255);
  52660. randVector.x = Math.floor(randVector.x);
  52661. randVector.y = Math.floor(randVector.y);
  52662. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52663. context.fillRect(x, y, 1, 1);
  52664. }
  52665. }
  52666. this._randomTexture.update(false);
  52667. };
  52668. __decorate([
  52669. BABYLON.serialize()
  52670. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  52671. __decorate([
  52672. BABYLON.serialize()
  52673. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  52674. __decorate([
  52675. BABYLON.serialize()
  52676. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  52677. __decorate([
  52678. BABYLON.serialize("samples")
  52679. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  52680. __decorate([
  52681. BABYLON.serialize("expensiveBlur")
  52682. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  52683. __decorate([
  52684. BABYLON.serialize()
  52685. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  52686. __decorate([
  52687. BABYLON.serialize()
  52688. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  52689. __decorate([
  52690. BABYLON.serialize()
  52691. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  52692. return SSAO2RenderingPipeline;
  52693. }(BABYLON.PostProcessRenderPipeline));
  52694. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  52695. })(BABYLON || (BABYLON = {}));
  52696. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  52697. // BABYLON.JS Chromatic Aberration GLSL Shader
  52698. // Author: Olivier Guyot
  52699. // Separates very slightly R, G and B colors on the edges of the screen
  52700. // Inspired by Francois Tarlier & Martins Upitis
  52701. var BABYLON;
  52702. (function (BABYLON) {
  52703. var LensRenderingPipeline = (function (_super) {
  52704. __extends(LensRenderingPipeline, _super);
  52705. /**
  52706. * @constructor
  52707. *
  52708. * Effect parameters are as follow:
  52709. * {
  52710. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52711. * edge_blur: number; // from 0 to x (1 for realism)
  52712. * distortion: number; // from 0 to x (1 for realism)
  52713. * grain_amount: number; // from 0 to 1
  52714. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52715. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52716. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52717. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52718. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52719. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52720. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52721. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52722. * }
  52723. * Note: if an effect parameter is unset, effect is disabled
  52724. *
  52725. * @param {string} name - The rendering pipeline name
  52726. * @param {object} parameters - An object containing all parameters (see above)
  52727. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52728. * @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)
  52729. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52730. */
  52731. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52732. if (ratio === void 0) { ratio = 1.0; }
  52733. var _this = _super.call(this, scene.getEngine(), name) || this;
  52734. // Lens effects can be of the following:
  52735. // - chromatic aberration (slight shift of RGB colors)
  52736. // - blur on the edge of the lens
  52737. // - lens distortion
  52738. // - depth-of-field blur & highlights enhancing
  52739. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52740. // - grain effect (noise or custom texture)
  52741. // Two additional texture samplers are needed:
  52742. // - depth map (for depth-of-field)
  52743. // - grain texture
  52744. /**
  52745. * The chromatic aberration PostProcess id in the pipeline
  52746. * @type {string}
  52747. */
  52748. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52749. /**
  52750. * The highlights enhancing PostProcess id in the pipeline
  52751. * @type {string}
  52752. */
  52753. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52754. /**
  52755. * The depth-of-field PostProcess id in the pipeline
  52756. * @type {string}
  52757. */
  52758. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52759. _this._scene = scene;
  52760. // Fetch texture samplers
  52761. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52762. if (parameters.grain_texture) {
  52763. _this._grainTexture = parameters.grain_texture;
  52764. }
  52765. else {
  52766. _this._createGrainTexture();
  52767. }
  52768. // save parameters
  52769. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52770. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52771. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52772. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52773. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52774. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52775. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52776. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52777. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52778. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52779. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52780. // Create effects
  52781. _this._createChromaticAberrationPostProcess(ratio);
  52782. _this._createHighlightsPostProcess(ratio);
  52783. _this._createDepthOfFieldPostProcess(ratio / 4);
  52784. // Set up pipeline
  52785. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52786. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52787. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52788. if (_this._highlightsGain === -1) {
  52789. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52790. }
  52791. // Finish
  52792. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52793. if (cameras) {
  52794. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52795. }
  52796. return _this;
  52797. }
  52798. // public methods (self explanatory)
  52799. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52800. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52801. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52802. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52803. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52804. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52805. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52806. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52807. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52808. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52809. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52810. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52811. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52812. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52813. };
  52814. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52815. this._highlightsPostProcess.updateEffect();
  52816. };
  52817. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52818. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52819. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52820. this._highlightsGain = amount;
  52821. };
  52822. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52823. if (this._highlightsGain === -1) {
  52824. this._highlightsGain = 1.0;
  52825. }
  52826. this._highlightsThreshold = amount;
  52827. };
  52828. LensRenderingPipeline.prototype.disableHighlights = function () {
  52829. this._highlightsGain = -1;
  52830. };
  52831. /**
  52832. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52833. */
  52834. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52835. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52836. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52837. this._chromaticAberrationPostProcess = undefined;
  52838. this._highlightsPostProcess = undefined;
  52839. this._depthOfFieldPostProcess = undefined;
  52840. this._grainTexture.dispose();
  52841. if (disableDepthRender)
  52842. this._scene.disableDepthRenderer();
  52843. };
  52844. // colors shifting and distortion
  52845. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52846. var _this = this;
  52847. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52848. [], // samplers
  52849. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52850. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52851. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52852. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52853. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52854. };
  52855. };
  52856. // highlights enhancing
  52857. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52858. var _this = this;
  52859. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52860. [], // samplers
  52861. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52862. this._highlightsPostProcess.onApply = function (effect) {
  52863. effect.setFloat('gain', _this._highlightsGain);
  52864. effect.setFloat('threshold', _this._highlightsThreshold);
  52865. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52866. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52867. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52868. };
  52869. };
  52870. // colors shifting and distortion
  52871. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52872. var _this = this;
  52873. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52874. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52875. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52876. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52877. this._depthOfFieldPostProcess.onApply = function (effect) {
  52878. effect.setTexture("depthSampler", _this._depthTexture);
  52879. effect.setTexture("grainSampler", _this._grainTexture);
  52880. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52881. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52882. effect.setFloat('grain_amount', _this._grainAmount);
  52883. effect.setBool('blur_noise', _this._blurNoise);
  52884. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52885. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52886. effect.setFloat('distortion', _this._distortion);
  52887. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52888. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52889. effect.setFloat('aperture', _this._dofAperture);
  52890. effect.setFloat('darken', _this._dofDarken);
  52891. effect.setFloat('edge_blur', _this._edgeBlur);
  52892. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52893. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52894. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52895. };
  52896. };
  52897. // creates a black and white random noise texture, 512x512
  52898. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52899. var size = 512;
  52900. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52901. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52902. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52903. var context = this._grainTexture.getContext();
  52904. var rand = function (min, max) {
  52905. return Math.random() * (max - min) + min;
  52906. };
  52907. var value;
  52908. for (var x = 0; x < size; x++) {
  52909. for (var y = 0; y < size; y++) {
  52910. value = Math.floor(rand(0.42, 0.58) * 255);
  52911. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52912. context.fillRect(x, y, 1, 1);
  52913. }
  52914. }
  52915. this._grainTexture.update(false);
  52916. };
  52917. return LensRenderingPipeline;
  52918. }(BABYLON.PostProcessRenderPipeline));
  52919. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52920. })(BABYLON || (BABYLON = {}));
  52921. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  52922. var BABYLON;
  52923. (function (BABYLON) {
  52924. var StandardRenderingPipeline = (function (_super) {
  52925. __extends(StandardRenderingPipeline, _super);
  52926. /**
  52927. * @constructor
  52928. * @param {string} name - The rendering pipeline name
  52929. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52930. * @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)
  52931. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  52932. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52933. */
  52934. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  52935. if (originalPostProcess === void 0) { originalPostProcess = null; }
  52936. var _this = _super.call(this, scene.getEngine(), name) || this;
  52937. _this.downSampleX4PostProcess = null;
  52938. _this.brightPassPostProcess = null;
  52939. _this.blurHPostProcesses = [];
  52940. _this.blurVPostProcesses = [];
  52941. _this.textureAdderPostProcess = null;
  52942. _this.volumetricLightPostProcess = null;
  52943. _this.volumetricLightSmoothXPostProcess = null;
  52944. _this.volumetricLightSmoothYPostProcess = null;
  52945. _this.volumetricLightMergePostProces = null;
  52946. _this.volumetricLightFinalPostProcess = null;
  52947. _this.luminancePostProcess = null;
  52948. _this.luminanceDownSamplePostProcesses = [];
  52949. _this.hdrPostProcess = null;
  52950. _this.textureAdderFinalPostProcess = null;
  52951. _this.lensFlareFinalPostProcess = null;
  52952. _this.hdrFinalPostProcess = null;
  52953. _this.lensFlarePostProcess = null;
  52954. _this.lensFlareComposePostProcess = null;
  52955. _this.motionBlurPostProcess = null;
  52956. _this.depthOfFieldPostProcess = null;
  52957. // Values
  52958. _this.brightThreshold = 1.0;
  52959. _this.blurWidth = 512.0;
  52960. _this.horizontalBlur = false;
  52961. _this.exposure = 1.0;
  52962. _this.lensTexture = null;
  52963. _this.volumetricLightCoefficient = 0.2;
  52964. _this.volumetricLightPower = 4.0;
  52965. _this.volumetricLightBlurScale = 64.0;
  52966. _this.sourceLight = null;
  52967. _this.hdrMinimumLuminance = 1.0;
  52968. _this.hdrDecreaseRate = 0.5;
  52969. _this.hdrIncreaseRate = 0.5;
  52970. _this.lensColorTexture = null;
  52971. _this.lensFlareStrength = 20.0;
  52972. _this.lensFlareGhostDispersal = 1.4;
  52973. _this.lensFlareHaloWidth = 0.7;
  52974. _this.lensFlareDistortionStrength = 16.0;
  52975. _this.lensStarTexture = null;
  52976. _this.lensFlareDirtTexture = null;
  52977. _this.depthOfFieldDistance = 10.0;
  52978. _this.depthOfFieldBlurWidth = 64.0;
  52979. _this.motionStrength = 1.0;
  52980. // IAnimatable
  52981. _this.animations = [];
  52982. _this._currentDepthOfFieldSource = null;
  52983. _this._hdrCurrentLuminance = 1.0;
  52984. // Getters and setters
  52985. _this._bloomEnabled = true;
  52986. _this._depthOfFieldEnabled = false;
  52987. _this._vlsEnabled = false;
  52988. _this._lensFlareEnabled = false;
  52989. _this._hdrEnabled = false;
  52990. _this._motionBlurEnabled = false;
  52991. _this._motionBlurSamples = 64.0;
  52992. _this._volumetricLightStepsCount = 50.0;
  52993. _this._cameras = cameras || [];
  52994. // Initialize
  52995. _this._scene = scene;
  52996. _this._basePostProcess = originalPostProcess;
  52997. _this._ratio = ratio;
  52998. // Misc
  52999. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53000. // Finish
  53001. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53002. _this._buildPipeline();
  53003. return _this;
  53004. }
  53005. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  53006. get: function () {
  53007. return this._bloomEnabled;
  53008. },
  53009. set: function (enabled) {
  53010. if (this._bloomEnabled === enabled) {
  53011. return;
  53012. }
  53013. this._bloomEnabled = enabled;
  53014. this._buildPipeline();
  53015. },
  53016. enumerable: true,
  53017. configurable: true
  53018. });
  53019. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  53020. get: function () {
  53021. return this._depthOfFieldEnabled;
  53022. },
  53023. set: function (enabled) {
  53024. if (this._depthOfFieldEnabled === enabled) {
  53025. return;
  53026. }
  53027. this._depthOfFieldEnabled = enabled;
  53028. this._buildPipeline();
  53029. },
  53030. enumerable: true,
  53031. configurable: true
  53032. });
  53033. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53034. get: function () {
  53035. return this._lensFlareEnabled;
  53036. },
  53037. set: function (enabled) {
  53038. if (this._lensFlareEnabled === enabled) {
  53039. return;
  53040. }
  53041. this._lensFlareEnabled = enabled;
  53042. this._buildPipeline();
  53043. },
  53044. enumerable: true,
  53045. configurable: true
  53046. });
  53047. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  53048. get: function () {
  53049. return this._hdrEnabled;
  53050. },
  53051. set: function (enabled) {
  53052. if (this._hdrEnabled === enabled) {
  53053. return;
  53054. }
  53055. this._hdrEnabled = enabled;
  53056. this._buildPipeline();
  53057. },
  53058. enumerable: true,
  53059. configurable: true
  53060. });
  53061. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  53062. get: function () {
  53063. return this._vlsEnabled;
  53064. },
  53065. set: function (enabled) {
  53066. if (this._vlsEnabled === enabled) {
  53067. return;
  53068. }
  53069. if (enabled) {
  53070. var geometry = this._scene.enableGeometryBufferRenderer();
  53071. if (!geometry) {
  53072. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  53073. return;
  53074. }
  53075. }
  53076. this._vlsEnabled = enabled;
  53077. this._buildPipeline();
  53078. },
  53079. enumerable: true,
  53080. configurable: true
  53081. });
  53082. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  53083. get: function () {
  53084. return this._motionBlurEnabled;
  53085. },
  53086. set: function (enabled) {
  53087. if (this._motionBlurEnabled === enabled) {
  53088. return;
  53089. }
  53090. this._motionBlurEnabled = enabled;
  53091. this._buildPipeline();
  53092. },
  53093. enumerable: true,
  53094. configurable: true
  53095. });
  53096. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  53097. get: function () {
  53098. return this._volumetricLightStepsCount;
  53099. },
  53100. set: function (count) {
  53101. if (this.volumetricLightPostProcess) {
  53102. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  53103. }
  53104. this._volumetricLightStepsCount = count;
  53105. },
  53106. enumerable: true,
  53107. configurable: true
  53108. });
  53109. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  53110. get: function () {
  53111. return this._motionBlurSamples;
  53112. },
  53113. set: function (samples) {
  53114. if (this.motionBlurPostProcess) {
  53115. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  53116. }
  53117. this._motionBlurSamples = samples;
  53118. },
  53119. enumerable: true,
  53120. configurable: true
  53121. });
  53122. StandardRenderingPipeline.prototype._buildPipeline = function () {
  53123. var _this = this;
  53124. var ratio = this._ratio;
  53125. var scene = this._scene;
  53126. this._disposePostProcesses();
  53127. this._reset();
  53128. // Create pass post-process
  53129. if (!this._basePostProcess) {
  53130. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  53131. this.originalPostProcess.onApply = function (effect) {
  53132. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  53133. };
  53134. }
  53135. else {
  53136. this.originalPostProcess = this._basePostProcess;
  53137. }
  53138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53139. this._currentDepthOfFieldSource = this.originalPostProcess;
  53140. if (this._vlsEnabled) {
  53141. // Create volumetric light
  53142. this._createVolumetricLightPostProcess(scene, ratio);
  53143. // Create volumetric light final post-process
  53144. this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  53146. }
  53147. if (this._bloomEnabled) {
  53148. // Create down sample X4 post-process
  53149. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53150. // Create bright pass post-process
  53151. this._createBrightPassPostProcess(scene, ratio / 2);
  53152. // Create gaussian blur post-processes (down sampling blurs)
  53153. this._createBlurPostProcesses(scene, ratio / 4, 1);
  53154. // Create texture adder post-process
  53155. this._createTextureAdderPostProcess(scene, ratio);
  53156. // Create depth-of-field source post-process
  53157. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53158. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53159. }
  53160. if (this._lensFlareEnabled) {
  53161. // Create lens flare post-process
  53162. this._createLensFlarePostProcess(scene, ratio);
  53163. // Create depth-of-field source post-process post lens-flare and disable it now
  53164. this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53165. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  53166. }
  53167. if (this._hdrEnabled) {
  53168. // Create luminance
  53169. this._createLuminancePostProcesses(scene, this._floatTextureType);
  53170. // Create HDR
  53171. this._createHdrPostProcess(scene, ratio);
  53172. // Create depth-of-field source post-process post hdr and disable it now
  53173. this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  53175. }
  53176. if (this._depthOfFieldEnabled) {
  53177. // Create gaussian blur used by depth-of-field
  53178. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  53179. // Create depth-of-field post-process
  53180. this._createDepthOfFieldPostProcess(scene, ratio);
  53181. }
  53182. if (this._motionBlurEnabled) {
  53183. // Create motion blur post-process
  53184. this._createMotionBlurPostProcess(scene, ratio);
  53185. }
  53186. if (this._cameras !== null) {
  53187. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53188. }
  53189. };
  53190. // Down Sample X4 Post-Processs
  53191. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53192. var _this = this;
  53193. var downSampleX4Offsets = new Array(32);
  53194. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53195. this.downSampleX4PostProcess.onApply = function (effect) {
  53196. var id = 0;
  53197. for (var i = -2; i < 2; i++) {
  53198. for (var j = -2; j < 2; j++) {
  53199. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53200. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53201. id += 2;
  53202. }
  53203. }
  53204. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53205. };
  53206. // Add to pipeline
  53207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53208. };
  53209. // Brightpass Post-Process
  53210. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53211. var _this = this;
  53212. var brightOffsets = new Array(8);
  53213. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53214. this.brightPassPostProcess.onApply = function (effect) {
  53215. var sU = (1.0 / _this.brightPassPostProcess.width);
  53216. var sV = (1.0 / _this.brightPassPostProcess.height);
  53217. brightOffsets[0] = -0.5 * sU;
  53218. brightOffsets[1] = 0.5 * sV;
  53219. brightOffsets[2] = 0.5 * sU;
  53220. brightOffsets[3] = 0.5 * sV;
  53221. brightOffsets[4] = -0.5 * sU;
  53222. brightOffsets[5] = -0.5 * sV;
  53223. brightOffsets[6] = 0.5 * sU;
  53224. brightOffsets[7] = -0.5 * sV;
  53225. effect.setArray2("dsOffsets", brightOffsets);
  53226. effect.setFloat("brightThreshold", _this.brightThreshold);
  53227. };
  53228. // Add to pipeline
  53229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53230. };
  53231. // Create blur H&V post-processes
  53232. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  53233. var _this = this;
  53234. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  53235. var engine = scene.getEngine();
  53236. var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53237. var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53238. blurX.onActivateObservable.add(function () {
  53239. var dw = blurX.width / engine.getRenderingCanvas().width;
  53240. blurX.kernel = _this[blurWidthKey] * dw;
  53241. });
  53242. blurY.onActivateObservable.add(function () {
  53243. var dw = blurY.height / engine.getRenderingCanvas().height;
  53244. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  53245. });
  53246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  53247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  53248. this.blurHPostProcesses.push(blurX);
  53249. this.blurVPostProcesses.push(blurY);
  53250. };
  53251. // Create texture adder post-process
  53252. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53253. var _this = this;
  53254. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53255. this.textureAdderPostProcess.onApply = function (effect) {
  53256. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  53257. effect.setTexture("lensSampler", _this.lensTexture);
  53258. effect.setFloat("exposure", _this.exposure);
  53259. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  53260. };
  53261. // Add to pipeline
  53262. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  53263. };
  53264. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  53265. var _this = this;
  53266. var geometryRenderer = scene.enableGeometryBufferRenderer();
  53267. geometryRenderer.enablePosition = true;
  53268. var geometry = geometryRenderer.getGBuffer();
  53269. // Base post-process
  53270. this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
  53271. var depthValues = BABYLON.Vector2.Zero();
  53272. this.volumetricLightPostProcess.onApply = function (effect) {
  53273. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  53274. var generator = _this.sourceLight.getShadowGenerator();
  53275. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  53276. effect.setTexture("positionSampler", geometry.textures[2]);
  53277. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  53278. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  53279. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  53280. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  53281. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  53282. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  53283. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  53284. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  53285. effect.setVector2("depthValues", depthValues);
  53286. }
  53287. };
  53288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  53289. // Smooth
  53290. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  53291. // Merge
  53292. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  53293. this.volumetricLightMergePostProces.onApply = function (effect) {
  53294. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  53295. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  53296. };
  53297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  53298. };
  53299. // Create luminance
  53300. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  53301. var _this = this;
  53302. // Create luminance
  53303. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  53304. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  53305. var offsets = [];
  53306. this.luminancePostProcess.onApply = function (effect) {
  53307. var sU = (1.0 / _this.luminancePostProcess.width);
  53308. var sV = (1.0 / _this.luminancePostProcess.height);
  53309. offsets[0] = -0.5 * sU;
  53310. offsets[1] = 0.5 * sV;
  53311. offsets[2] = 0.5 * sU;
  53312. offsets[3] = 0.5 * sV;
  53313. offsets[4] = -0.5 * sU;
  53314. offsets[5] = -0.5 * sV;
  53315. offsets[6] = 0.5 * sU;
  53316. offsets[7] = -0.5 * sV;
  53317. effect.setArray2("lumOffsets", offsets);
  53318. };
  53319. // Add to pipeline
  53320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  53321. // Create down sample luminance
  53322. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  53323. var size = Math.pow(3, i);
  53324. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  53325. if (i === 0) {
  53326. defines += "#define FINAL_DOWN_SAMPLER";
  53327. }
  53328. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  53329. this.luminanceDownSamplePostProcesses.push(postProcess);
  53330. }
  53331. // Create callbacks and add effects
  53332. var lastLuminance = this.luminancePostProcess;
  53333. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  53334. var downSampleOffsets = new Array(18);
  53335. pp.onApply = function (effect) {
  53336. var id = 0;
  53337. for (var x = -1; x < 2; x++) {
  53338. for (var y = -1; y < 2; y++) {
  53339. downSampleOffsets[id] = x / lastLuminance.width;
  53340. downSampleOffsets[id + 1] = y / lastLuminance.height;
  53341. id += 2;
  53342. }
  53343. }
  53344. effect.setArray2("dsOffsets", downSampleOffsets);
  53345. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  53346. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  53347. lastLuminance = _this.luminancePostProcess;
  53348. }
  53349. else {
  53350. lastLuminance = pp;
  53351. }
  53352. };
  53353. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  53354. pp.onAfterRender = function (effect) {
  53355. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53356. 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);
  53357. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53358. };
  53359. }
  53360. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  53361. });
  53362. };
  53363. // Create HDR post-process
  53364. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  53365. var _this = this;
  53366. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53367. var outputLiminance = 1;
  53368. var time = 0;
  53369. var lastTime = 0;
  53370. this.hdrPostProcess.onApply = function (effect) {
  53371. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  53372. time += scene.getEngine().getDeltaTime();
  53373. if (outputLiminance < 0) {
  53374. outputLiminance = _this._hdrCurrentLuminance;
  53375. }
  53376. else {
  53377. var dt = (lastTime - time) / 1000.0;
  53378. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  53379. outputLiminance += _this.hdrDecreaseRate * dt;
  53380. }
  53381. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  53382. outputLiminance -= _this.hdrIncreaseRate * dt;
  53383. }
  53384. else {
  53385. outputLiminance = _this._hdrCurrentLuminance;
  53386. }
  53387. }
  53388. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  53389. effect.setFloat("averageLuminance", outputLiminance);
  53390. lastTime = time;
  53391. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  53392. };
  53393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  53394. };
  53395. // Create lens flare post-process
  53396. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  53397. var _this = this;
  53398. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53399. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  53400. this._createBlurPostProcesses(scene, ratio / 4, 2);
  53401. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  53403. var resolution = new BABYLON.Vector2(0, 0);
  53404. // Lens flare
  53405. this.lensFlarePostProcess.onApply = function (effect) {
  53406. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  53407. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  53408. effect.setFloat("strength", _this.lensFlareStrength);
  53409. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  53410. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  53411. // Shift
  53412. resolution.x = _this.lensFlarePostProcess.width;
  53413. resolution.y = _this.lensFlarePostProcess.height;
  53414. effect.setVector2("resolution", resolution);
  53415. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  53416. };
  53417. // Compose
  53418. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  53419. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  53420. this.lensFlareComposePostProcess.onApply = function (effect) {
  53421. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  53422. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  53423. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  53424. // Lens start rotation matrix
  53425. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  53426. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  53427. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  53428. camRot *= 4.0;
  53429. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  53430. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  53431. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  53432. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  53433. };
  53434. };
  53435. // Create depth-of-field post-process
  53436. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  53437. var _this = this;
  53438. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53439. this.depthOfFieldPostProcess.onApply = function (effect) {
  53440. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  53441. effect.setTexture("depthSampler", _this._getDepthTexture());
  53442. effect.setFloat("distance", _this.depthOfFieldDistance);
  53443. };
  53444. // Add to pipeline
  53445. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  53446. };
  53447. // Create motion blur post-process
  53448. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  53449. var _this = this;
  53450. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53451. var motionScale = 0;
  53452. var prevViewProjection = BABYLON.Matrix.Identity();
  53453. var invViewProjection = BABYLON.Matrix.Identity();
  53454. var viewProjection = BABYLON.Matrix.Identity();
  53455. var screenSize = BABYLON.Vector2.Zero();
  53456. this.motionBlurPostProcess.onApply = function (effect) {
  53457. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  53458. viewProjection.invertToRef(invViewProjection);
  53459. effect.setMatrix("inverseViewProjection", invViewProjection);
  53460. effect.setMatrix("prevViewProjection", prevViewProjection);
  53461. prevViewProjection = viewProjection;
  53462. screenSize.x = _this.motionBlurPostProcess.width;
  53463. screenSize.y = _this.motionBlurPostProcess.height;
  53464. effect.setVector2("screenSize", screenSize);
  53465. motionScale = scene.getEngine().getFps() / 60.0;
  53466. effect.setFloat("motionScale", motionScale);
  53467. effect.setFloat("motionStrength", _this.motionStrength);
  53468. effect.setTexture("depthSampler", _this._getDepthTexture());
  53469. };
  53470. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  53471. };
  53472. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  53473. var geometry = this._scene.enableGeometryBufferRenderer();
  53474. if (geometry) {
  53475. return geometry.getGBuffer().textures[0];
  53476. }
  53477. return this._scene.enableDepthRenderer().getDepthMap();
  53478. };
  53479. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  53480. for (var i = 0; i < this._cameras.length; i++) {
  53481. var camera = this._cameras[i];
  53482. if (this.originalPostProcess) {
  53483. this.originalPostProcess.dispose(camera);
  53484. }
  53485. if (this.downSampleX4PostProcess) {
  53486. this.downSampleX4PostProcess.dispose(camera);
  53487. }
  53488. if (this.brightPassPostProcess) {
  53489. this.brightPassPostProcess.dispose(camera);
  53490. }
  53491. if (this.textureAdderPostProcess) {
  53492. this.textureAdderPostProcess.dispose(camera);
  53493. }
  53494. if (this.textureAdderFinalPostProcess) {
  53495. this.textureAdderFinalPostProcess.dispose(camera);
  53496. }
  53497. if (this.volumetricLightPostProcess) {
  53498. this.volumetricLightPostProcess.dispose(camera);
  53499. }
  53500. if (this.volumetricLightSmoothXPostProcess) {
  53501. this.volumetricLightSmoothXPostProcess.dispose(camera);
  53502. }
  53503. if (this.volumetricLightSmoothYPostProcess) {
  53504. this.volumetricLightSmoothYPostProcess.dispose(camera);
  53505. }
  53506. if (this.volumetricLightMergePostProces) {
  53507. this.volumetricLightMergePostProces.dispose(camera);
  53508. }
  53509. if (this.volumetricLightFinalPostProcess) {
  53510. this.volumetricLightFinalPostProcess.dispose(camera);
  53511. }
  53512. if (this.lensFlarePostProcess) {
  53513. this.lensFlarePostProcess.dispose(camera);
  53514. }
  53515. if (this.lensFlareComposePostProcess) {
  53516. this.lensFlareComposePostProcess.dispose(camera);
  53517. }
  53518. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  53519. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  53520. }
  53521. if (this.luminancePostProcess) {
  53522. this.luminancePostProcess.dispose(camera);
  53523. }
  53524. if (this.hdrPostProcess) {
  53525. this.hdrPostProcess.dispose(camera);
  53526. }
  53527. if (this.hdrFinalPostProcess) {
  53528. this.hdrFinalPostProcess.dispose(camera);
  53529. }
  53530. if (this.depthOfFieldPostProcess) {
  53531. this.depthOfFieldPostProcess.dispose(camera);
  53532. }
  53533. if (this.motionBlurPostProcess) {
  53534. this.motionBlurPostProcess.dispose(camera);
  53535. }
  53536. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  53537. this.blurHPostProcesses[j].dispose(camera);
  53538. }
  53539. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  53540. this.blurVPostProcesses[j].dispose(camera);
  53541. }
  53542. }
  53543. this.originalPostProcess = null;
  53544. this.downSampleX4PostProcess = null;
  53545. this.brightPassPostProcess = null;
  53546. this.textureAdderPostProcess = null;
  53547. this.textureAdderFinalPostProcess = null;
  53548. this.volumetricLightPostProcess = null;
  53549. this.volumetricLightSmoothXPostProcess = null;
  53550. this.volumetricLightSmoothYPostProcess = null;
  53551. this.volumetricLightMergePostProces = null;
  53552. this.volumetricLightFinalPostProcess = null;
  53553. this.lensFlarePostProcess = null;
  53554. this.lensFlareComposePostProcess = null;
  53555. this.luminancePostProcess = null;
  53556. this.hdrPostProcess = null;
  53557. this.hdrFinalPostProcess = null;
  53558. this.depthOfFieldPostProcess = null;
  53559. this.motionBlurPostProcess = null;
  53560. this.luminanceDownSamplePostProcesses = [];
  53561. this.blurHPostProcesses = [];
  53562. this.blurVPostProcesses = [];
  53563. };
  53564. // Dispose
  53565. StandardRenderingPipeline.prototype.dispose = function () {
  53566. this._disposePostProcesses();
  53567. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53568. _super.prototype.dispose.call(this);
  53569. };
  53570. // Serialize rendering pipeline
  53571. StandardRenderingPipeline.prototype.serialize = function () {
  53572. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53573. serializationObject.customType = "StandardRenderingPipeline";
  53574. return serializationObject;
  53575. };
  53576. /**
  53577. * Static members
  53578. */
  53579. // Parse serialized pipeline
  53580. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53581. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  53582. };
  53583. // Luminance steps
  53584. StandardRenderingPipeline.LuminanceSteps = 6;
  53585. __decorate([
  53586. BABYLON.serialize()
  53587. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  53588. __decorate([
  53589. BABYLON.serialize()
  53590. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  53591. __decorate([
  53592. BABYLON.serialize()
  53593. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  53594. __decorate([
  53595. BABYLON.serialize()
  53596. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  53597. __decorate([
  53598. BABYLON.serializeAsTexture("lensTexture")
  53599. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  53600. __decorate([
  53601. BABYLON.serialize()
  53602. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  53603. __decorate([
  53604. BABYLON.serialize()
  53605. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  53606. __decorate([
  53607. BABYLON.serialize()
  53608. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  53609. __decorate([
  53610. BABYLON.serialize()
  53611. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  53612. __decorate([
  53613. BABYLON.serialize()
  53614. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  53615. __decorate([
  53616. BABYLON.serialize()
  53617. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  53618. __decorate([
  53619. BABYLON.serializeAsTexture("lensColorTexture")
  53620. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  53621. __decorate([
  53622. BABYLON.serialize()
  53623. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  53624. __decorate([
  53625. BABYLON.serialize()
  53626. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  53627. __decorate([
  53628. BABYLON.serialize()
  53629. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  53630. __decorate([
  53631. BABYLON.serialize()
  53632. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  53633. __decorate([
  53634. BABYLON.serializeAsTexture("lensStarTexture")
  53635. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  53636. __decorate([
  53637. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  53638. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  53639. __decorate([
  53640. BABYLON.serialize()
  53641. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  53642. __decorate([
  53643. BABYLON.serialize()
  53644. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  53645. __decorate([
  53646. BABYLON.serialize()
  53647. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  53648. __decorate([
  53649. BABYLON.serialize()
  53650. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  53651. __decorate([
  53652. BABYLON.serialize()
  53653. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  53654. __decorate([
  53655. BABYLON.serialize()
  53656. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  53657. __decorate([
  53658. BABYLON.serialize()
  53659. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  53660. __decorate([
  53661. BABYLON.serialize()
  53662. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  53663. __decorate([
  53664. BABYLON.serialize()
  53665. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  53666. __decorate([
  53667. BABYLON.serialize()
  53668. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  53669. __decorate([
  53670. BABYLON.serialize()
  53671. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  53672. return StandardRenderingPipeline;
  53673. }(BABYLON.PostProcessRenderPipeline));
  53674. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  53675. })(BABYLON || (BABYLON = {}));
  53676. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  53677. var BABYLON;
  53678. (function (BABYLON) {
  53679. var FxaaPostProcess = (function (_super) {
  53680. __extends(FxaaPostProcess, _super);
  53681. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53682. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53683. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  53684. _this.onApplyObservable.add(function (effect) {
  53685. var texelSize = _this.texelSize;
  53686. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  53687. });
  53688. return _this;
  53689. }
  53690. return FxaaPostProcess;
  53691. }(BABYLON.PostProcess));
  53692. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53693. })(BABYLON || (BABYLON = {}));
  53694. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  53695. var BABYLON;
  53696. (function (BABYLON) {
  53697. var DefaultRenderingPipeline = (function (_super) {
  53698. __extends(DefaultRenderingPipeline, _super);
  53699. /**
  53700. * @constructor
  53701. * @param {string} name - The rendering pipeline name
  53702. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53703. * @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)
  53704. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53705. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  53706. */
  53707. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  53708. if (automaticBuild === void 0) { automaticBuild = true; }
  53709. var _this = _super.call(this, scene.getEngine(), name) || this;
  53710. _this.PassPostProcessId = "PassPostProcessEffect";
  53711. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  53712. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  53713. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  53714. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  53715. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  53716. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  53717. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  53718. // IAnimatable
  53719. _this.animations = [];
  53720. // Values
  53721. _this._bloomEnabled = false;
  53722. _this._fxaaEnabled = false;
  53723. _this._imageProcessingEnabled = true;
  53724. _this._bloomScale = 0.6;
  53725. _this._buildAllowed = true;
  53726. /**
  53727. * Specifies the size of the bloom blur kernel, relative to the final output size
  53728. */
  53729. _this.bloomKernel = 64;
  53730. /**
  53731. * Specifies the weight of the bloom in the final rendering
  53732. */
  53733. _this._bloomWeight = 0.15;
  53734. _this._cameras = cameras || [];
  53735. _this._buildAllowed = automaticBuild;
  53736. // Initialize
  53737. _this._scene = scene;
  53738. var caps = _this._scene.getEngine().getCaps();
  53739. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  53740. // Misc
  53741. if (_this._hdr) {
  53742. if (caps.textureHalfFloatRender) {
  53743. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53744. }
  53745. else if (caps.textureFloatRender) {
  53746. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53747. }
  53748. }
  53749. else {
  53750. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53751. }
  53752. // Attach
  53753. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53754. _this._buildPipeline();
  53755. return _this;
  53756. }
  53757. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  53758. get: function () {
  53759. return this._bloomWeight;
  53760. },
  53761. set: function (value) {
  53762. if (this._bloomWeight === value) {
  53763. return;
  53764. }
  53765. this._bloomWeight = value;
  53766. if (this._hdr && this.copyBack) {
  53767. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  53768. }
  53769. },
  53770. enumerable: true,
  53771. configurable: true
  53772. });
  53773. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  53774. get: function () {
  53775. return this._bloomScale;
  53776. },
  53777. set: function (value) {
  53778. if (this._bloomScale === value) {
  53779. return;
  53780. }
  53781. this._bloomScale = value;
  53782. this._buildPipeline();
  53783. },
  53784. enumerable: true,
  53785. configurable: true
  53786. });
  53787. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  53788. get: function () {
  53789. return this._bloomEnabled;
  53790. },
  53791. set: function (enabled) {
  53792. if (this._bloomEnabled === enabled) {
  53793. return;
  53794. }
  53795. this._bloomEnabled = enabled;
  53796. this._buildPipeline();
  53797. },
  53798. enumerable: true,
  53799. configurable: true
  53800. });
  53801. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  53802. get: function () {
  53803. return this._fxaaEnabled;
  53804. },
  53805. set: function (enabled) {
  53806. if (this._fxaaEnabled === enabled) {
  53807. return;
  53808. }
  53809. this._fxaaEnabled = enabled;
  53810. this._buildPipeline();
  53811. },
  53812. enumerable: true,
  53813. configurable: true
  53814. });
  53815. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  53816. get: function () {
  53817. return this._imageProcessingEnabled;
  53818. },
  53819. set: function (enabled) {
  53820. if (this._imageProcessingEnabled === enabled) {
  53821. return;
  53822. }
  53823. this._imageProcessingEnabled = enabled;
  53824. this._buildPipeline();
  53825. },
  53826. enumerable: true,
  53827. configurable: true
  53828. });
  53829. /**
  53830. * Force the compilation of the entire pipeline.
  53831. */
  53832. DefaultRenderingPipeline.prototype.prepare = function () {
  53833. var previousState = this._buildAllowed;
  53834. this._buildAllowed = true;
  53835. this._buildPipeline();
  53836. this._buildAllowed = previousState;
  53837. };
  53838. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  53839. var _this = this;
  53840. if (!this._buildAllowed) {
  53841. return;
  53842. }
  53843. var engine = this._scene.getEngine();
  53844. this._disposePostProcesses();
  53845. this._reset();
  53846. if (this.bloomEnabled) {
  53847. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53848. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  53849. if (!this._hdr) {
  53850. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53851. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  53852. this.highlights.autoClear = false;
  53853. this.highlights.alwaysForcePOT = true;
  53854. }
  53855. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53856. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  53857. this.blurX.alwaysForcePOT = true;
  53858. this.blurX.autoClear = false;
  53859. this.blurX.onActivateObservable.add(function () {
  53860. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  53861. _this.blurX.kernel = _this.bloomKernel * dw;
  53862. });
  53863. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53864. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  53865. this.blurY.alwaysForcePOT = true;
  53866. this.blurY.autoClear = false;
  53867. this.blurY.onActivateObservable.add(function () {
  53868. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  53869. _this.blurY.kernel = _this.bloomKernel * dh;
  53870. });
  53871. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53872. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  53873. this.copyBack.alwaysForcePOT = true;
  53874. if (this._hdr) {
  53875. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  53876. var w = this.bloomWeight;
  53877. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  53878. }
  53879. else {
  53880. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  53881. }
  53882. this.copyBack.autoClear = false;
  53883. }
  53884. if (this._imageProcessingEnabled) {
  53885. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53886. if (this._hdr) {
  53887. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  53888. }
  53889. }
  53890. if (this.fxaaEnabled) {
  53891. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53892. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  53893. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  53894. }
  53895. else {
  53896. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53897. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  53898. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  53899. }
  53900. if (this.bloomEnabled) {
  53901. if (this._hdr) {
  53902. this.copyBack.shareOutputWith(this.blurX);
  53903. if (this.imageProcessing) {
  53904. this.imageProcessing.shareOutputWith(this.pass);
  53905. this.imageProcessing.autoClear = false;
  53906. }
  53907. else if (this.fxaa) {
  53908. this.fxaa.shareOutputWith(this.pass);
  53909. }
  53910. else {
  53911. this.finalMerge.shareOutputWith(this.pass);
  53912. }
  53913. }
  53914. else {
  53915. if (this.fxaa) {
  53916. this.fxaa.shareOutputWith(this.pass);
  53917. }
  53918. else {
  53919. this.finalMerge.shareOutputWith(this.pass);
  53920. }
  53921. }
  53922. }
  53923. if (this._cameras !== null) {
  53924. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53925. }
  53926. };
  53927. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  53928. for (var i = 0; i < this._cameras.length; i++) {
  53929. var camera = this._cameras[i];
  53930. if (this.pass) {
  53931. this.pass.dispose(camera);
  53932. }
  53933. if (this.highlights) {
  53934. this.highlights.dispose(camera);
  53935. }
  53936. if (this.blurX) {
  53937. this.blurX.dispose(camera);
  53938. }
  53939. if (this.blurY) {
  53940. this.blurY.dispose(camera);
  53941. }
  53942. if (this.copyBack) {
  53943. this.copyBack.dispose(camera);
  53944. }
  53945. if (this.imageProcessing) {
  53946. this.imageProcessing.dispose(camera);
  53947. }
  53948. if (this.fxaa) {
  53949. this.fxaa.dispose(camera);
  53950. }
  53951. if (this.finalMerge) {
  53952. this.finalMerge.dispose(camera);
  53953. }
  53954. }
  53955. this.pass = null;
  53956. this.highlights = null;
  53957. this.blurX = null;
  53958. this.blurY = null;
  53959. this.copyBack = null;
  53960. this.imageProcessing = null;
  53961. this.fxaa = null;
  53962. this.finalMerge = null;
  53963. };
  53964. // Dispose
  53965. DefaultRenderingPipeline.prototype.dispose = function () {
  53966. this._disposePostProcesses();
  53967. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53968. _super.prototype.dispose.call(this);
  53969. };
  53970. // Serialize rendering pipeline
  53971. DefaultRenderingPipeline.prototype.serialize = function () {
  53972. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53973. serializationObject.customType = "DefaultRenderingPipeline";
  53974. return serializationObject;
  53975. };
  53976. // Parse serialized pipeline
  53977. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53978. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  53979. };
  53980. __decorate([
  53981. BABYLON.serialize()
  53982. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  53983. __decorate([
  53984. BABYLON.serialize()
  53985. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  53986. __decorate([
  53987. BABYLON.serialize()
  53988. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  53989. __decorate([
  53990. BABYLON.serialize()
  53991. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  53992. __decorate([
  53993. BABYLON.serialize()
  53994. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  53995. __decorate([
  53996. BABYLON.serialize()
  53997. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  53998. __decorate([
  53999. BABYLON.serialize()
  54000. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  54001. __decorate([
  54002. BABYLON.serialize()
  54003. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  54004. return DefaultRenderingPipeline;
  54005. }(BABYLON.PostProcessRenderPipeline));
  54006. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  54007. })(BABYLON || (BABYLON = {}));
  54008. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  54009. var BABYLON;
  54010. (function (BABYLON) {
  54011. var GeometryBufferRenderer = (function () {
  54012. function GeometryBufferRenderer(scene, ratio) {
  54013. if (ratio === void 0) { ratio = 1; }
  54014. this._viewMatrix = BABYLON.Matrix.Zero();
  54015. this._projectionMatrix = BABYLON.Matrix.Zero();
  54016. this._transformMatrix = BABYLON.Matrix.Zero();
  54017. this._worldViewProjection = BABYLON.Matrix.Zero();
  54018. this._enablePosition = false;
  54019. this._scene = scene;
  54020. this._ratio = ratio;
  54021. // Render target
  54022. this._createRenderTargets();
  54023. }
  54024. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  54025. set: function (meshes) {
  54026. this._multiRenderTarget.renderList = meshes;
  54027. },
  54028. enumerable: true,
  54029. configurable: true
  54030. });
  54031. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  54032. get: function () {
  54033. return this._multiRenderTarget.isSupported;
  54034. },
  54035. enumerable: true,
  54036. configurable: true
  54037. });
  54038. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  54039. get: function () {
  54040. return this._enablePosition;
  54041. },
  54042. set: function (enable) {
  54043. this._enablePosition = enable;
  54044. this.dispose();
  54045. this._createRenderTargets();
  54046. },
  54047. enumerable: true,
  54048. configurable: true
  54049. });
  54050. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  54051. var material = subMesh.getMaterial();
  54052. if (material && material.disableDepthWrite) {
  54053. return false;
  54054. }
  54055. var defines = [];
  54056. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  54057. var mesh = subMesh.getMesh();
  54058. var scene = mesh.getScene();
  54059. // Alpha test
  54060. if (material && material.needAlphaTesting()) {
  54061. defines.push("#define ALPHATEST");
  54062. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54063. attribs.push(BABYLON.VertexBuffer.UVKind);
  54064. defines.push("#define UV1");
  54065. }
  54066. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54067. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54068. defines.push("#define UV2");
  54069. }
  54070. }
  54071. // Buffers
  54072. if (this._enablePosition) {
  54073. defines.push("#define POSITION");
  54074. }
  54075. // Bones
  54076. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54077. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54078. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54079. if (mesh.numBoneInfluencers > 4) {
  54080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54082. }
  54083. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54084. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54085. }
  54086. else {
  54087. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54088. }
  54089. // Instances
  54090. if (useInstances) {
  54091. defines.push("#define INSTANCES");
  54092. attribs.push("world0");
  54093. attribs.push("world1");
  54094. attribs.push("world2");
  54095. attribs.push("world3");
  54096. }
  54097. // Get correct effect
  54098. var join = defines.join("\n");
  54099. if (this._cachedDefines !== join) {
  54100. this._cachedDefines = join;
  54101. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  54102. }
  54103. return this._effect.isReady();
  54104. };
  54105. GeometryBufferRenderer.prototype.getGBuffer = function () {
  54106. return this._multiRenderTarget;
  54107. };
  54108. // Methods
  54109. GeometryBufferRenderer.prototype.dispose = function () {
  54110. this.getGBuffer().dispose();
  54111. };
  54112. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  54113. var _this = this;
  54114. var engine = this._scene.getEngine();
  54115. var count = this._enablePosition ? 3 : 2;
  54116. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  54117. if (!this.isSupported) {
  54118. return null;
  54119. }
  54120. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54121. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54122. this._multiRenderTarget.refreshRate = 1;
  54123. this._multiRenderTarget.renderParticles = false;
  54124. this._multiRenderTarget.renderList = null;
  54125. // set default depth value to 1.0 (far away)
  54126. this._multiRenderTarget.onClearObservable.add(function (engine) {
  54127. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  54128. });
  54129. // Custom render function
  54130. var renderSubMesh = function (subMesh) {
  54131. var mesh = subMesh.getRenderingMesh();
  54132. var scene = _this._scene;
  54133. var engine = scene.getEngine();
  54134. // Culling
  54135. engine.setState(subMesh.getMaterial().backFaceCulling);
  54136. // Managing instances
  54137. var batch = mesh._getInstancesRenderList(subMesh._id);
  54138. if (batch.mustReturn) {
  54139. return;
  54140. }
  54141. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  54142. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54143. engine.enableEffect(_this._effect);
  54144. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54145. var material = subMesh.getMaterial();
  54146. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54147. _this._effect.setMatrix("view", scene.getViewMatrix());
  54148. // Alpha test
  54149. if (material && material.needAlphaTesting()) {
  54150. var alphaTexture = material.getAlphaTestTexture();
  54151. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54152. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54153. }
  54154. // Bones
  54155. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54156. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54157. }
  54158. // Draw
  54159. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54160. }
  54161. };
  54162. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  54163. var index;
  54164. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54165. renderSubMesh(opaqueSubMeshes.data[index]);
  54166. }
  54167. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54168. renderSubMesh(alphaTestSubMeshes.data[index]);
  54169. }
  54170. };
  54171. };
  54172. return GeometryBufferRenderer;
  54173. }());
  54174. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  54175. })(BABYLON || (BABYLON = {}));
  54176. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  54177. var BABYLON;
  54178. (function (BABYLON) {
  54179. var RefractionPostProcess = (function (_super) {
  54180. __extends(RefractionPostProcess, _super);
  54181. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54182. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  54183. _this.color = color;
  54184. _this.depth = depth;
  54185. _this.colorLevel = colorLevel;
  54186. _this.onActivateObservable.add(function (cam) {
  54187. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54188. });
  54189. _this.onApplyObservable.add(function (effect) {
  54190. effect.setColor3("baseColor", _this.color);
  54191. effect.setFloat("depth", _this.depth);
  54192. effect.setFloat("colorLevel", _this.colorLevel);
  54193. effect.setTexture("refractionSampler", _this._refRexture);
  54194. });
  54195. return _this;
  54196. }
  54197. // Methods
  54198. RefractionPostProcess.prototype.dispose = function (camera) {
  54199. if (this._refRexture) {
  54200. this._refRexture.dispose();
  54201. }
  54202. _super.prototype.dispose.call(this, camera);
  54203. };
  54204. return RefractionPostProcess;
  54205. }(BABYLON.PostProcess));
  54206. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54207. })(BABYLON || (BABYLON = {}));
  54208. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  54209. var BABYLON;
  54210. (function (BABYLON) {
  54211. var BlackAndWhitePostProcess = (function (_super) {
  54212. __extends(BlackAndWhitePostProcess, _super);
  54213. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54214. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  54215. _this.degree = 1;
  54216. _this.onApplyObservable.add(function (effect) {
  54217. effect.setFloat("degree", _this.degree);
  54218. });
  54219. return _this;
  54220. }
  54221. return BlackAndWhitePostProcess;
  54222. }(BABYLON.PostProcess));
  54223. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54224. })(BABYLON || (BABYLON = {}));
  54225. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  54226. var BABYLON;
  54227. (function (BABYLON) {
  54228. var ConvolutionPostProcess = (function (_super) {
  54229. __extends(ConvolutionPostProcess, _super);
  54230. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54231. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  54232. _this.kernel = kernel;
  54233. _this.onApply = function (effect) {
  54234. effect.setFloat2("screenSize", _this.width, _this.height);
  54235. effect.setArray("kernel", _this.kernel);
  54236. };
  54237. return _this;
  54238. }
  54239. // Statics
  54240. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  54241. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  54242. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  54243. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  54244. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  54245. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  54246. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  54247. return ConvolutionPostProcess;
  54248. }(BABYLON.PostProcess));
  54249. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  54250. })(BABYLON || (BABYLON = {}));
  54251. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  54252. var BABYLON;
  54253. (function (BABYLON) {
  54254. var FilterPostProcess = (function (_super) {
  54255. __extends(FilterPostProcess, _super);
  54256. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  54257. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  54258. _this.kernelMatrix = kernelMatrix;
  54259. _this.onApply = function (effect) {
  54260. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  54261. };
  54262. return _this;
  54263. }
  54264. return FilterPostProcess;
  54265. }(BABYLON.PostProcess));
  54266. BABYLON.FilterPostProcess = FilterPostProcess;
  54267. })(BABYLON || (BABYLON = {}));
  54268. //# sourceMappingURL=babylon.filterPostProcess.js.map
  54269. var BABYLON;
  54270. (function (BABYLON) {
  54271. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  54272. var VolumetricLightScatteringPostProcess = (function (_super) {
  54273. __extends(VolumetricLightScatteringPostProcess, _super);
  54274. /**
  54275. * @constructor
  54276. * @param {string} name - The post-process name
  54277. * @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)
  54278. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  54279. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  54280. * @param {number} samples - The post-process quality, default 100
  54281. * @param {number} samplingMode - The post-process filtering mode
  54282. * @param {BABYLON.Engine} engine - The babylon engine
  54283. * @param {boolean} reusable - If the post-process is reusable
  54284. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  54285. */
  54286. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  54287. if (samples === void 0) { samples = 100; }
  54288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54289. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  54290. _this._screenCoordinates = BABYLON.Vector2.Zero();
  54291. /**
  54292. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  54293. * @type {Vector3}
  54294. */
  54295. _this.customMeshPosition = BABYLON.Vector3.Zero();
  54296. /**
  54297. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  54298. * @type {boolean}
  54299. */
  54300. _this.useCustomMeshPosition = false;
  54301. /**
  54302. * If the post-process should inverse the light scattering direction
  54303. * @type {boolean}
  54304. */
  54305. _this.invert = true;
  54306. /**
  54307. * Array containing the excluded meshes not rendered in the internal pass
  54308. */
  54309. _this.excludedMeshes = new Array();
  54310. /**
  54311. * Controls the overall intensity of the post-process
  54312. * @type {number}
  54313. */
  54314. _this.exposure = 0.3;
  54315. /**
  54316. * Dissipates each sample's contribution in range [0, 1]
  54317. * @type {number}
  54318. */
  54319. _this.decay = 0.96815;
  54320. /**
  54321. * Controls the overall intensity of each sample
  54322. * @type {number}
  54323. */
  54324. _this.weight = 0.58767;
  54325. /**
  54326. * Controls the density of each sample
  54327. * @type {number}
  54328. */
  54329. _this.density = 0.926;
  54330. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  54331. var engine = scene.getEngine();
  54332. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  54333. // Configure mesh
  54334. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  54335. // Configure
  54336. _this._createPass(scene, ratio.passRatio || ratio);
  54337. _this.onActivate = function (camera) {
  54338. if (!_this.isSupported) {
  54339. _this.dispose(camera);
  54340. }
  54341. _this.onActivate = null;
  54342. };
  54343. _this.onApplyObservable.add(function (effect) {
  54344. _this._updateMeshScreenCoordinates(scene);
  54345. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  54346. effect.setFloat("exposure", _this.exposure);
  54347. effect.setFloat("decay", _this.decay);
  54348. effect.setFloat("weight", _this.weight);
  54349. effect.setFloat("density", _this.density);
  54350. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  54351. });
  54352. return _this;
  54353. }
  54354. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  54355. get: function () {
  54356. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54357. return false;
  54358. },
  54359. set: function (useDiffuseColor) {
  54360. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54361. },
  54362. enumerable: true,
  54363. configurable: true
  54364. });
  54365. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  54366. return "VolumetricLightScatteringPostProcess";
  54367. };
  54368. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  54369. var mesh = subMesh.getMesh();
  54370. // Render this.mesh as default
  54371. if (mesh === this.mesh) {
  54372. return mesh.material.isReady(mesh);
  54373. }
  54374. var defines = [];
  54375. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54376. var material = subMesh.getMaterial();
  54377. var needUV = false;
  54378. // Alpha test
  54379. if (material) {
  54380. if (material.needAlphaTesting()) {
  54381. defines.push("#define ALPHATEST");
  54382. }
  54383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54384. attribs.push(BABYLON.VertexBuffer.UVKind);
  54385. defines.push("#define UV1");
  54386. }
  54387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54388. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54389. defines.push("#define UV2");
  54390. }
  54391. }
  54392. // Bones
  54393. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54396. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54397. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54398. }
  54399. else {
  54400. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54401. }
  54402. // Instances
  54403. if (useInstances) {
  54404. defines.push("#define INSTANCES");
  54405. attribs.push("world0");
  54406. attribs.push("world1");
  54407. attribs.push("world2");
  54408. attribs.push("world3");
  54409. }
  54410. // Get correct effect
  54411. var join = defines.join("\n");
  54412. if (this._cachedDefines !== join) {
  54413. this._cachedDefines = join;
  54414. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  54415. }
  54416. return this._volumetricLightScatteringPass.isReady();
  54417. };
  54418. /**
  54419. * Sets the new light position for light scattering effect
  54420. * @param {BABYLON.Vector3} The new custom light position
  54421. */
  54422. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  54423. this.customMeshPosition = position;
  54424. };
  54425. /**
  54426. * Returns the light position for light scattering effect
  54427. * @return {BABYLON.Vector3} The custom light position
  54428. */
  54429. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  54430. return this.customMeshPosition;
  54431. };
  54432. /**
  54433. * Disposes the internal assets and detaches the post-process from the camera
  54434. */
  54435. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  54436. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  54437. if (rttIndex !== -1) {
  54438. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  54439. }
  54440. this._volumetricLightScatteringRTT.dispose();
  54441. _super.prototype.dispose.call(this, camera);
  54442. };
  54443. /**
  54444. * Returns the render target texture used by the post-process
  54445. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  54446. */
  54447. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  54448. return this._volumetricLightScatteringRTT;
  54449. };
  54450. // Private methods
  54451. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  54452. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  54453. return true;
  54454. }
  54455. return false;
  54456. };
  54457. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  54458. var _this = this;
  54459. var engine = scene.getEngine();
  54460. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54461. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54462. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54463. this._volumetricLightScatteringRTT.renderList = null;
  54464. this._volumetricLightScatteringRTT.renderParticles = false;
  54465. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  54466. // Custom render function for submeshes
  54467. var renderSubMesh = function (subMesh) {
  54468. var mesh = subMesh.getRenderingMesh();
  54469. if (_this._meshExcluded(mesh)) {
  54470. return;
  54471. }
  54472. var scene = mesh.getScene();
  54473. var engine = scene.getEngine();
  54474. // Culling
  54475. engine.setState(subMesh.getMaterial().backFaceCulling);
  54476. // Managing instances
  54477. var batch = mesh._getInstancesRenderList(subMesh._id);
  54478. if (batch.mustReturn) {
  54479. return;
  54480. }
  54481. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  54482. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54483. var effect = _this._volumetricLightScatteringPass;
  54484. if (mesh === _this.mesh) {
  54485. if (subMesh.effect) {
  54486. effect = subMesh.effect;
  54487. }
  54488. else {
  54489. effect = subMesh.getMaterial().getEffect();
  54490. }
  54491. }
  54492. engine.enableEffect(effect);
  54493. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  54494. if (mesh === _this.mesh) {
  54495. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  54496. }
  54497. else {
  54498. var material = subMesh.getMaterial();
  54499. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  54500. // Alpha test
  54501. if (material && material.needAlphaTesting()) {
  54502. var alphaTexture = material.getAlphaTestTexture();
  54503. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  54504. if (alphaTexture) {
  54505. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54506. }
  54507. }
  54508. // Bones
  54509. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54510. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54511. }
  54512. }
  54513. // Draw
  54514. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  54515. }
  54516. };
  54517. // Render target texture callbacks
  54518. var savedSceneClearColor;
  54519. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  54520. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  54521. savedSceneClearColor = scene.clearColor;
  54522. scene.clearColor = sceneClearColor;
  54523. });
  54524. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  54525. scene.clearColor = savedSceneClearColor;
  54526. });
  54527. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  54528. var engine = scene.getEngine();
  54529. var index;
  54530. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54531. renderSubMesh(opaqueSubMeshes.data[index]);
  54532. }
  54533. engine.setAlphaTesting(true);
  54534. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54535. renderSubMesh(alphaTestSubMeshes.data[index]);
  54536. }
  54537. engine.setAlphaTesting(false);
  54538. if (transparentSubMeshes.length) {
  54539. // Sort sub meshes
  54540. for (index = 0; index < transparentSubMeshes.length; index++) {
  54541. var submesh = transparentSubMeshes.data[index];
  54542. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  54543. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  54544. }
  54545. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  54546. sortedArray.sort(function (a, b) {
  54547. // Alpha index first
  54548. if (a._alphaIndex > b._alphaIndex) {
  54549. return 1;
  54550. }
  54551. if (a._alphaIndex < b._alphaIndex) {
  54552. return -1;
  54553. }
  54554. // Then distance to camera
  54555. if (a._distanceToCamera < b._distanceToCamera) {
  54556. return 1;
  54557. }
  54558. if (a._distanceToCamera > b._distanceToCamera) {
  54559. return -1;
  54560. }
  54561. return 0;
  54562. });
  54563. // Render sub meshes
  54564. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54565. for (index = 0; index < sortedArray.length; index++) {
  54566. renderSubMesh(sortedArray[index]);
  54567. }
  54568. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54569. }
  54570. };
  54571. };
  54572. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  54573. var transform = scene.getTransformMatrix();
  54574. var meshPosition;
  54575. if (this.useCustomMeshPosition) {
  54576. meshPosition = this.customMeshPosition;
  54577. }
  54578. else if (this.attachedNode) {
  54579. meshPosition = this.attachedNode.position;
  54580. }
  54581. else {
  54582. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  54583. }
  54584. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  54585. this._screenCoordinates.x = pos.x / this._viewPort.width;
  54586. this._screenCoordinates.y = pos.y / this._viewPort.height;
  54587. if (this.invert)
  54588. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  54589. };
  54590. // Static methods
  54591. /**
  54592. * Creates a default mesh for the Volumeric Light Scattering post-process
  54593. * @param {string} The mesh name
  54594. * @param {BABYLON.Scene} The scene where to create the mesh
  54595. * @return {BABYLON.Mesh} the default mesh
  54596. */
  54597. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  54598. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  54599. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54600. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  54601. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  54602. mesh.material = material;
  54603. return mesh;
  54604. };
  54605. __decorate([
  54606. BABYLON.serializeAsVector3()
  54607. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  54608. __decorate([
  54609. BABYLON.serialize()
  54610. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  54611. __decorate([
  54612. BABYLON.serialize()
  54613. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  54614. __decorate([
  54615. BABYLON.serializeAsMeshReference()
  54616. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  54617. __decorate([
  54618. BABYLON.serialize()
  54619. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  54620. __decorate([
  54621. BABYLON.serialize()
  54622. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  54623. __decorate([
  54624. BABYLON.serialize()
  54625. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  54626. __decorate([
  54627. BABYLON.serialize()
  54628. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  54629. __decorate([
  54630. BABYLON.serialize()
  54631. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  54632. return VolumetricLightScatteringPostProcess;
  54633. }(BABYLON.PostProcess));
  54634. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  54635. })(BABYLON || (BABYLON = {}));
  54636. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  54637. //
  54638. // This post-process allows the modification of rendered colors by using
  54639. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54640. //
  54641. // The object needs to be provided an url to a texture containing the color
  54642. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54643. // Use an image editing software to tweak the LUT to match your needs.
  54644. //
  54645. // For an example of a color LUT, see here:
  54646. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54647. // For explanations on color grading, see here:
  54648. // http://udn.epicgames.com/Three/ColorGrading.html
  54649. //
  54650. var BABYLON;
  54651. (function (BABYLON) {
  54652. var ColorCorrectionPostProcess = (function (_super) {
  54653. __extends(ColorCorrectionPostProcess, _super);
  54654. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54655. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  54656. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54657. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  54658. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54659. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54660. _this.onApply = function (effect) {
  54661. effect.setTexture("colorTable", _this._colorTableTexture);
  54662. };
  54663. return _this;
  54664. }
  54665. return ColorCorrectionPostProcess;
  54666. }(BABYLON.PostProcess));
  54667. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54668. })(BABYLON || (BABYLON = {}));
  54669. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  54670. var BABYLON;
  54671. (function (BABYLON) {
  54672. var TonemappingOperator;
  54673. (function (TonemappingOperator) {
  54674. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  54675. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  54676. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  54677. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  54678. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  54679. ;
  54680. var TonemapPostProcess = (function (_super) {
  54681. __extends(TonemapPostProcess, _super);
  54682. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  54683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54684. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54685. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  54686. _this._operator = _operator;
  54687. _this.exposureAdjustment = exposureAdjustment;
  54688. var defines = "#define ";
  54689. if (_this._operator === TonemappingOperator.Hable)
  54690. defines += "HABLE_TONEMAPPING";
  54691. else if (_this._operator === TonemappingOperator.Reinhard)
  54692. defines += "REINHARD_TONEMAPPING";
  54693. else if (_this._operator === TonemappingOperator.HejiDawson)
  54694. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  54695. else if (_this._operator === TonemappingOperator.Photographic)
  54696. defines += "PHOTOGRAPHIC_TONEMAPPING";
  54697. //sadly a second call to create the effect.
  54698. _this.updateEffect(defines);
  54699. _this.onApply = function (effect) {
  54700. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  54701. };
  54702. return _this;
  54703. }
  54704. return TonemapPostProcess;
  54705. }(BABYLON.PostProcess));
  54706. BABYLON.TonemapPostProcess = TonemapPostProcess;
  54707. })(BABYLON || (BABYLON = {}));
  54708. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  54709. var BABYLON;
  54710. (function (BABYLON) {
  54711. var DisplayPassPostProcess = (function (_super) {
  54712. __extends(DisplayPassPostProcess, _super);
  54713. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  54714. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  54715. }
  54716. return DisplayPassPostProcess;
  54717. }(BABYLON.PostProcess));
  54718. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  54719. })(BABYLON || (BABYLON = {}));
  54720. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  54721. var BABYLON;
  54722. (function (BABYLON) {
  54723. var HighlightsPostProcess = (function (_super) {
  54724. __extends(HighlightsPostProcess, _super);
  54725. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54726. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54727. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  54728. }
  54729. return HighlightsPostProcess;
  54730. }(BABYLON.PostProcess));
  54731. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  54732. })(BABYLON || (BABYLON = {}));
  54733. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  54734. var BABYLON;
  54735. (function (BABYLON) {
  54736. var ImageProcessingPostProcess = (function (_super) {
  54737. __extends(ImageProcessingPostProcess, _super);
  54738. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54739. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54740. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  54741. _this._fromLinearSpace = true;
  54742. /**
  54743. * Defines cache preventing GC.
  54744. */
  54745. _this._defines = {
  54746. IMAGEPROCESSING: false,
  54747. VIGNETTE: false,
  54748. VIGNETTEBLENDMODEMULTIPLY: false,
  54749. VIGNETTEBLENDMODEOPAQUE: false,
  54750. TONEMAPPING: false,
  54751. CONTRAST: false,
  54752. COLORCURVES: false,
  54753. COLORGRADING: false,
  54754. FROMLINEARSPACE: false,
  54755. SAMPLER3DGREENDEPTH: false,
  54756. SAMPLER3DBGRMAP: false,
  54757. IMAGEPROCESSINGPOSTPROCESS: false,
  54758. EXPOSURE: false,
  54759. };
  54760. // Setup the default processing configuration to the scene.
  54761. _this._attachImageProcessingConfiguration(null, true);
  54762. _this.imageProcessingConfiguration.applyByPostProcess = true;
  54763. _this.onApply = function (effect) {
  54764. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  54765. };
  54766. return _this;
  54767. }
  54768. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  54769. /**
  54770. * Gets the image processing configuration used either in this material.
  54771. */
  54772. get: function () {
  54773. return this._imageProcessingConfiguration;
  54774. },
  54775. /**
  54776. * Sets the Default image processing configuration used either in the this material.
  54777. *
  54778. * If sets to null, the scene one is in use.
  54779. */
  54780. set: function (value) {
  54781. this._attachImageProcessingConfiguration(value);
  54782. },
  54783. enumerable: true,
  54784. configurable: true
  54785. });
  54786. /**
  54787. * Attaches a new image processing configuration to the PBR Material.
  54788. * @param configuration
  54789. */
  54790. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  54791. var _this = this;
  54792. if (doNotBuild === void 0) { doNotBuild = false; }
  54793. if (configuration === this._imageProcessingConfiguration) {
  54794. return;
  54795. }
  54796. // Detaches observer.
  54797. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  54798. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  54799. }
  54800. // Pick the scene configuration if needed.
  54801. if (!configuration) {
  54802. var camera = this.getCamera();
  54803. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  54804. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  54805. }
  54806. else {
  54807. this._imageProcessingConfiguration = configuration;
  54808. }
  54809. // Attaches observer.
  54810. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  54811. _this._updateParameters();
  54812. });
  54813. // Ensure the effect will be rebuilt.
  54814. if (!doNotBuild) {
  54815. this._updateParameters();
  54816. }
  54817. };
  54818. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  54819. /**
  54820. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54821. */
  54822. get: function () {
  54823. return this.imageProcessingConfiguration.colorCurves;
  54824. },
  54825. /**
  54826. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54827. */
  54828. set: function (value) {
  54829. this.imageProcessingConfiguration.colorCurves = value;
  54830. },
  54831. enumerable: true,
  54832. configurable: true
  54833. });
  54834. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  54835. /**
  54836. * Gets wether the color curves effect is enabled.
  54837. */
  54838. get: function () {
  54839. return this.imageProcessingConfiguration.colorCurvesEnabled;
  54840. },
  54841. /**
  54842. * Sets wether the color curves effect is enabled.
  54843. */
  54844. set: function (value) {
  54845. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  54846. },
  54847. enumerable: true,
  54848. configurable: true
  54849. });
  54850. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  54851. /**
  54852. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  54853. */
  54854. get: function () {
  54855. return this.imageProcessingConfiguration.colorGradingTexture;
  54856. },
  54857. /**
  54858. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  54859. */
  54860. set: function (value) {
  54861. this.imageProcessingConfiguration.colorGradingTexture = value;
  54862. },
  54863. enumerable: true,
  54864. configurable: true
  54865. });
  54866. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  54867. /**
  54868. * Gets wether the color grading effect is enabled.
  54869. */
  54870. get: function () {
  54871. return this.imageProcessingConfiguration.colorGradingEnabled;
  54872. },
  54873. /**
  54874. * Gets wether the color grading effect is enabled.
  54875. */
  54876. set: function (value) {
  54877. this.imageProcessingConfiguration.colorGradingEnabled = value;
  54878. },
  54879. enumerable: true,
  54880. configurable: true
  54881. });
  54882. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  54883. /**
  54884. * Gets exposure used in the effect.
  54885. */
  54886. get: function () {
  54887. return this.imageProcessingConfiguration.exposure;
  54888. },
  54889. /**
  54890. * Sets exposure used in the effect.
  54891. */
  54892. set: function (value) {
  54893. this.imageProcessingConfiguration.exposure = value;
  54894. },
  54895. enumerable: true,
  54896. configurable: true
  54897. });
  54898. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  54899. /**
  54900. * Gets wether tonemapping is enabled or not.
  54901. */
  54902. get: function () {
  54903. return this._imageProcessingConfiguration.toneMappingEnabled;
  54904. },
  54905. /**
  54906. * Sets wether tonemapping is enabled or not
  54907. */
  54908. set: function (value) {
  54909. this._imageProcessingConfiguration.toneMappingEnabled = value;
  54910. },
  54911. enumerable: true,
  54912. configurable: true
  54913. });
  54914. ;
  54915. ;
  54916. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  54917. /**
  54918. * Gets contrast used in the effect.
  54919. */
  54920. get: function () {
  54921. return this.imageProcessingConfiguration.contrast;
  54922. },
  54923. /**
  54924. * Sets contrast used in the effect.
  54925. */
  54926. set: function (value) {
  54927. this.imageProcessingConfiguration.contrast = value;
  54928. },
  54929. enumerable: true,
  54930. configurable: true
  54931. });
  54932. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  54933. /**
  54934. * Gets Vignette stretch size.
  54935. */
  54936. get: function () {
  54937. return this.imageProcessingConfiguration.vignetteStretch;
  54938. },
  54939. /**
  54940. * Sets Vignette stretch size.
  54941. */
  54942. set: function (value) {
  54943. this.imageProcessingConfiguration.vignetteStretch = value;
  54944. },
  54945. enumerable: true,
  54946. configurable: true
  54947. });
  54948. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  54949. /**
  54950. * Gets Vignette centre X Offset.
  54951. */
  54952. get: function () {
  54953. return this.imageProcessingConfiguration.vignetteCentreX;
  54954. },
  54955. /**
  54956. * Sets Vignette centre X Offset.
  54957. */
  54958. set: function (value) {
  54959. this.imageProcessingConfiguration.vignetteCentreX = value;
  54960. },
  54961. enumerable: true,
  54962. configurable: true
  54963. });
  54964. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  54965. /**
  54966. * Gets Vignette centre Y Offset.
  54967. */
  54968. get: function () {
  54969. return this.imageProcessingConfiguration.vignetteCentreY;
  54970. },
  54971. /**
  54972. * Sets Vignette centre Y Offset.
  54973. */
  54974. set: function (value) {
  54975. this.imageProcessingConfiguration.vignetteCentreY = value;
  54976. },
  54977. enumerable: true,
  54978. configurable: true
  54979. });
  54980. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  54981. /**
  54982. * Gets Vignette weight or intensity of the vignette effect.
  54983. */
  54984. get: function () {
  54985. return this.imageProcessingConfiguration.vignetteWeight;
  54986. },
  54987. /**
  54988. * Sets Vignette weight or intensity of the vignette effect.
  54989. */
  54990. set: function (value) {
  54991. this.imageProcessingConfiguration.vignetteWeight = value;
  54992. },
  54993. enumerable: true,
  54994. configurable: true
  54995. });
  54996. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  54997. /**
  54998. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54999. * if vignetteEnabled is set to true.
  55000. */
  55001. get: function () {
  55002. return this.imageProcessingConfiguration.vignetteColor;
  55003. },
  55004. /**
  55005. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  55006. * if vignetteEnabled is set to true.
  55007. */
  55008. set: function (value) {
  55009. this.imageProcessingConfiguration.vignetteColor = value;
  55010. },
  55011. enumerable: true,
  55012. configurable: true
  55013. });
  55014. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  55015. /**
  55016. * Gets Camera field of view used by the Vignette effect.
  55017. */
  55018. get: function () {
  55019. return this.imageProcessingConfiguration.vignetteCameraFov;
  55020. },
  55021. /**
  55022. * Sets Camera field of view used by the Vignette effect.
  55023. */
  55024. set: function (value) {
  55025. this.imageProcessingConfiguration.vignetteCameraFov = value;
  55026. },
  55027. enumerable: true,
  55028. configurable: true
  55029. });
  55030. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  55031. /**
  55032. * Gets the vignette blend mode allowing different kind of effect.
  55033. */
  55034. get: function () {
  55035. return this.imageProcessingConfiguration.vignetteBlendMode;
  55036. },
  55037. /**
  55038. * Sets the vignette blend mode allowing different kind of effect.
  55039. */
  55040. set: function (value) {
  55041. this.imageProcessingConfiguration.vignetteBlendMode = value;
  55042. },
  55043. enumerable: true,
  55044. configurable: true
  55045. });
  55046. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  55047. /**
  55048. * Gets wether the vignette effect is enabled.
  55049. */
  55050. get: function () {
  55051. return this.imageProcessingConfiguration.vignetteEnabled;
  55052. },
  55053. /**
  55054. * Sets wether the vignette effect is enabled.
  55055. */
  55056. set: function (value) {
  55057. this.imageProcessingConfiguration.vignetteEnabled = value;
  55058. },
  55059. enumerable: true,
  55060. configurable: true
  55061. });
  55062. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  55063. /**
  55064. * Gets wether the input of the processing is in Gamma or Linear Space.
  55065. */
  55066. get: function () {
  55067. return this._fromLinearSpace;
  55068. },
  55069. /**
  55070. * Sets wether the input of the processing is in Gamma or Linear Space.
  55071. */
  55072. set: function (value) {
  55073. if (this._fromLinearSpace === value) {
  55074. return;
  55075. }
  55076. this._fromLinearSpace = value;
  55077. this._updateParameters();
  55078. },
  55079. enumerable: true,
  55080. configurable: true
  55081. });
  55082. ImageProcessingPostProcess.prototype.getClassName = function () {
  55083. return "ImageProcessingPostProcess";
  55084. };
  55085. ImageProcessingPostProcess.prototype._updateParameters = function () {
  55086. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  55087. this.imageProcessingConfiguration.prepareDefines(this._defines);
  55088. var defines = "";
  55089. for (var define in this._defines) {
  55090. if (this._defines[define]) {
  55091. defines += "#define " + define + ";\r\n";
  55092. }
  55093. }
  55094. var samplers = ["textureSampler"];
  55095. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  55096. var uniforms = ["scale"];
  55097. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  55098. this.updateEffect(defines, uniforms, samplers);
  55099. };
  55100. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  55101. _super.prototype.dispose.call(this, camera);
  55102. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  55103. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  55104. }
  55105. this.imageProcessingConfiguration.applyByPostProcess = false;
  55106. };
  55107. __decorate([
  55108. BABYLON.serialize()
  55109. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  55110. return ImageProcessingPostProcess;
  55111. }(BABYLON.PostProcess));
  55112. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  55113. })(BABYLON || (BABYLON = {}));
  55114. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  55115. var BABYLON;
  55116. (function (BABYLON) {
  55117. var BlurPostProcess = (function (_super) {
  55118. __extends(BlurPostProcess, _super);
  55119. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  55120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55122. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  55123. _this.direction = direction;
  55124. _this._packedFloat = false;
  55125. _this.onApplyObservable.add(function (effect) {
  55126. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  55127. });
  55128. _this.kernel = kernel;
  55129. return _this;
  55130. }
  55131. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  55132. /**
  55133. * Gets the length in pixels of the blur sample region
  55134. */
  55135. get: function () {
  55136. return this._idealKernel;
  55137. },
  55138. /**
  55139. * Sets the length in pixels of the blur sample region
  55140. */
  55141. set: function (v) {
  55142. if (this._idealKernel === v) {
  55143. return;
  55144. }
  55145. v = Math.max(v, 1);
  55146. this._idealKernel = v;
  55147. this._kernel = this._nearestBestKernel(v);
  55148. this._updateParameters();
  55149. },
  55150. enumerable: true,
  55151. configurable: true
  55152. });
  55153. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  55154. /**
  55155. * Gets wether or not the blur is unpacking/repacking floats
  55156. */
  55157. get: function () {
  55158. return this._packedFloat;
  55159. },
  55160. /**
  55161. * Sets wether or not the blur needs to unpack/repack floats
  55162. */
  55163. set: function (v) {
  55164. if (this._packedFloat === v) {
  55165. return;
  55166. }
  55167. this._packedFloat = v;
  55168. this._updateParameters();
  55169. },
  55170. enumerable: true,
  55171. configurable: true
  55172. });
  55173. BlurPostProcess.prototype._updateParameters = function () {
  55174. // Generate sampling offsets and weights
  55175. var N = this._kernel;
  55176. var centerIndex = (N - 1) / 2;
  55177. // Generate Gaussian sampling weights over kernel
  55178. var offsets = [];
  55179. var weights = [];
  55180. var totalWeight = 0;
  55181. for (var i = 0; i < N; i++) {
  55182. var u = i / (N - 1);
  55183. var w = this._gaussianWeight(u * 2.0 - 1);
  55184. offsets[i] = (i - centerIndex);
  55185. weights[i] = w;
  55186. totalWeight += w;
  55187. }
  55188. // Normalize weights
  55189. for (var i = 0; i < weights.length; i++) {
  55190. weights[i] /= totalWeight;
  55191. }
  55192. // Optimize: combine samples to take advantage of hardware linear sampling
  55193. // Walk from left to center, combining pairs (symmetrically)
  55194. var linearSamplingWeights = [];
  55195. var linearSamplingOffsets = [];
  55196. var linearSamplingMap = [];
  55197. for (var i = 0; i <= centerIndex; i += 2) {
  55198. var j = Math.min(i + 1, Math.floor(centerIndex));
  55199. var singleCenterSample = i === j;
  55200. if (singleCenterSample) {
  55201. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55202. }
  55203. else {
  55204. var sharedCell = j === centerIndex;
  55205. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  55206. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  55207. if (offsetLinear === 0) {
  55208. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55209. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  55210. }
  55211. else {
  55212. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  55213. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  55214. }
  55215. }
  55216. }
  55217. for (var i = 0; i < linearSamplingMap.length; i++) {
  55218. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  55219. linearSamplingWeights[i] = linearSamplingMap[i].w;
  55220. }
  55221. // Replace with optimized
  55222. offsets = linearSamplingOffsets;
  55223. weights = linearSamplingWeights;
  55224. // Generate shaders
  55225. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  55226. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  55227. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  55228. var defines = "";
  55229. for (var i = 0; i < varyingCount; i++) {
  55230. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  55231. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  55232. }
  55233. var depCount = 0;
  55234. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  55235. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  55236. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  55237. depCount++;
  55238. }
  55239. if (this.packedFloat) {
  55240. defines += "#define PACKEDFLOAT 1";
  55241. }
  55242. this.updateEffect(defines, null, null, {
  55243. varyingCount: varyingCount,
  55244. depCount: depCount
  55245. });
  55246. };
  55247. /**
  55248. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  55249. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  55250. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  55251. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  55252. * The gaps between physical kernels are compensated for in the weighting of the samples
  55253. * @param idealKernel Ideal blur kernel.
  55254. * @return Nearest best kernel.
  55255. */
  55256. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  55257. var v = Math.round(idealKernel);
  55258. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  55259. var k = _a[_i];
  55260. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  55261. return Math.max(k, 3);
  55262. }
  55263. }
  55264. return Math.max(v, 3);
  55265. };
  55266. /**
  55267. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  55268. * @param x The point on the Gaussian distribution to sample.
  55269. * @return the value of the Gaussian function at x.
  55270. */
  55271. BlurPostProcess.prototype._gaussianWeight = function (x) {
  55272. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  55273. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  55274. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  55275. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  55276. // truncated at around 1.3% of peak strength.
  55277. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  55278. var sigma = (1 / 3);
  55279. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  55280. var exponent = -((x * x) / (2.0 * sigma * sigma));
  55281. var weight = (1.0 / denominator) * Math.exp(exponent);
  55282. return weight;
  55283. };
  55284. /**
  55285. * Generates a string that can be used as a floating point number in GLSL.
  55286. * @param x Value to print.
  55287. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  55288. * @return GLSL float string.
  55289. */
  55290. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  55291. if (decimalFigures === void 0) { decimalFigures = 8; }
  55292. return x.toFixed(decimalFigures).replace(/0+$/, '');
  55293. };
  55294. return BlurPostProcess;
  55295. }(BABYLON.PostProcess));
  55296. BABYLON.BlurPostProcess = BlurPostProcess;
  55297. })(BABYLON || (BABYLON = {}));
  55298. //# sourceMappingURL=babylon.blurPostProcess.js.map
  55299. /// <reference path="..\babylon.node.ts" />
  55300. var BABYLON;
  55301. (function (BABYLON) {
  55302. var Bone = (function (_super) {
  55303. __extends(Bone, _super);
  55304. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  55305. if (parentBone === void 0) { parentBone = null; }
  55306. var _this = _super.call(this, name, skeleton.getScene()) || this;
  55307. _this.name = name;
  55308. _this.children = new Array();
  55309. _this.animations = new Array();
  55310. _this._worldTransform = new BABYLON.Matrix();
  55311. _this._absoluteTransform = new BABYLON.Matrix();
  55312. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  55313. _this._scaleMatrix = BABYLON.Matrix.Identity();
  55314. _this._scaleVector = BABYLON.Vector3.One();
  55315. _this._negateScaleChildren = BABYLON.Vector3.One();
  55316. _this._scalingDeterminant = 1;
  55317. _this._skeleton = skeleton;
  55318. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  55319. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  55320. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  55321. _this._index = index;
  55322. skeleton.bones.push(_this);
  55323. _this.setParent(parentBone, false);
  55324. _this._updateDifferenceMatrix();
  55325. return _this;
  55326. }
  55327. Object.defineProperty(Bone.prototype, "_matrix", {
  55328. get: function () {
  55329. return this._localMatrix;
  55330. },
  55331. set: function (val) {
  55332. if (this._localMatrix) {
  55333. this._localMatrix.copyFrom(val);
  55334. }
  55335. else {
  55336. this._localMatrix = val;
  55337. }
  55338. },
  55339. enumerable: true,
  55340. configurable: true
  55341. });
  55342. // Members
  55343. Bone.prototype.getSkeleton = function () {
  55344. return this._skeleton;
  55345. };
  55346. Bone.prototype.getParent = function () {
  55347. return this._parent;
  55348. };
  55349. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  55350. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  55351. if (this._parent === parent) {
  55352. return;
  55353. }
  55354. if (this._parent) {
  55355. var index = this._parent.children.indexOf(this);
  55356. if (index !== -1) {
  55357. this._parent.children.splice(index);
  55358. }
  55359. }
  55360. this._parent = parent;
  55361. if (this._parent) {
  55362. this._parent.children.push(this);
  55363. }
  55364. if (updateDifferenceMatrix) {
  55365. this._updateDifferenceMatrix();
  55366. }
  55367. };
  55368. Bone.prototype.getLocalMatrix = function () {
  55369. return this._localMatrix;
  55370. };
  55371. Bone.prototype.getBaseMatrix = function () {
  55372. return this._baseMatrix;
  55373. };
  55374. Bone.prototype.getRestPose = function () {
  55375. return this._restPose;
  55376. };
  55377. Bone.prototype.returnToRest = function () {
  55378. this.updateMatrix(this._restPose.clone());
  55379. };
  55380. Bone.prototype.getWorldMatrix = function () {
  55381. return this._worldTransform;
  55382. };
  55383. Bone.prototype.getInvertedAbsoluteTransform = function () {
  55384. return this._invertedAbsoluteTransform;
  55385. };
  55386. Bone.prototype.getAbsoluteTransform = function () {
  55387. return this._absoluteTransform;
  55388. };
  55389. Object.defineProperty(Bone.prototype, "position", {
  55390. // Properties (matches AbstractMesh properties)
  55391. get: function () {
  55392. return this.getPosition();
  55393. },
  55394. set: function (newPosition) {
  55395. this.setPosition(newPosition);
  55396. },
  55397. enumerable: true,
  55398. configurable: true
  55399. });
  55400. Object.defineProperty(Bone.prototype, "rotation", {
  55401. get: function () {
  55402. return this.getRotation();
  55403. },
  55404. set: function (newRotation) {
  55405. this.setRotation(newRotation);
  55406. },
  55407. enumerable: true,
  55408. configurable: true
  55409. });
  55410. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  55411. get: function () {
  55412. return this.getRotationQuaternion();
  55413. },
  55414. set: function (newRotation) {
  55415. this.setRotationQuaternion(newRotation);
  55416. },
  55417. enumerable: true,
  55418. configurable: true
  55419. });
  55420. Object.defineProperty(Bone.prototype, "scaling", {
  55421. get: function () {
  55422. return this.getScale();
  55423. },
  55424. set: function (newScaling) {
  55425. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  55426. },
  55427. enumerable: true,
  55428. configurable: true
  55429. });
  55430. // Methods
  55431. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  55432. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  55433. this._baseMatrix = matrix.clone();
  55434. this._localMatrix = matrix.clone();
  55435. this._skeleton._markAsDirty();
  55436. if (updateDifferenceMatrix) {
  55437. this._updateDifferenceMatrix();
  55438. }
  55439. };
  55440. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  55441. if (!rootMatrix) {
  55442. rootMatrix = this._baseMatrix;
  55443. }
  55444. if (this._parent) {
  55445. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  55446. }
  55447. else {
  55448. this._absoluteTransform.copyFrom(rootMatrix);
  55449. }
  55450. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  55451. for (var index = 0; index < this.children.length; index++) {
  55452. this.children[index]._updateDifferenceMatrix();
  55453. }
  55454. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  55455. };
  55456. Bone.prototype.markAsDirty = function () {
  55457. this._currentRenderId++;
  55458. this._skeleton._markAsDirty();
  55459. };
  55460. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  55461. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  55462. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  55463. // all animation may be coming from a library skeleton, so may need to create animation
  55464. if (this.animations.length === 0) {
  55465. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  55466. this.animations[0].setKeys([]);
  55467. }
  55468. // get animation info / verify there is such a range from the source bone
  55469. var sourceRange = source.animations[0].getRange(rangeName);
  55470. if (!sourceRange) {
  55471. return false;
  55472. }
  55473. var from = sourceRange.from;
  55474. var to = sourceRange.to;
  55475. var sourceKeys = source.animations[0].getKeys();
  55476. // rescaling prep
  55477. var sourceBoneLength = source.length;
  55478. var sourceParent = source.getParent();
  55479. var parent = this.getParent();
  55480. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  55481. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  55482. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  55483. var destKeys = this.animations[0].getKeys();
  55484. // loop vars declaration
  55485. var orig;
  55486. var origTranslation;
  55487. var mat;
  55488. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  55489. orig = sourceKeys[key];
  55490. if (orig.frame >= from && orig.frame <= to) {
  55491. if (rescaleAsRequired) {
  55492. mat = orig.value.clone();
  55493. // scale based on parent ratio, when bone has parent
  55494. if (parentScalingReqd) {
  55495. origTranslation = mat.getTranslation();
  55496. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  55497. // scale based on skeleton dimension ratio when root bone, and value is passed
  55498. }
  55499. else if (dimensionsScalingReqd) {
  55500. origTranslation = mat.getTranslation();
  55501. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  55502. // use original when root bone, and no data for skelDimensionsRatio
  55503. }
  55504. else {
  55505. mat = orig.value;
  55506. }
  55507. }
  55508. else {
  55509. mat = orig.value;
  55510. }
  55511. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  55512. }
  55513. }
  55514. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  55515. return true;
  55516. };
  55517. /**
  55518. * Translate the bone in local or world space.
  55519. * @param vec The amount to translate the bone.
  55520. * @param space The space that the translation is in.
  55521. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55522. */
  55523. Bone.prototype.translate = function (vec, space, mesh) {
  55524. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55525. var lm = this.getLocalMatrix();
  55526. if (space == BABYLON.Space.LOCAL) {
  55527. lm.m[12] += vec.x;
  55528. lm.m[13] += vec.y;
  55529. lm.m[14] += vec.z;
  55530. }
  55531. else {
  55532. var wm;
  55533. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55534. if (mesh) {
  55535. wm = mesh.getWorldMatrix();
  55536. }
  55537. this._skeleton.computeAbsoluteTransforms();
  55538. var tmat = Bone._tmpMats[0];
  55539. var tvec = Bone._tmpVecs[0];
  55540. if (mesh) {
  55541. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55542. tmat.multiplyToRef(wm, tmat);
  55543. }
  55544. else {
  55545. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55546. }
  55547. tmat.m[12] = 0;
  55548. tmat.m[13] = 0;
  55549. tmat.m[14] = 0;
  55550. tmat.invert();
  55551. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  55552. lm.m[12] += tvec.x;
  55553. lm.m[13] += tvec.y;
  55554. lm.m[14] += tvec.z;
  55555. }
  55556. this.markAsDirty();
  55557. };
  55558. /**
  55559. * Set the postion of the bone in local or world space.
  55560. * @param position The position to set the bone.
  55561. * @param space The space that the position is in.
  55562. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55563. */
  55564. Bone.prototype.setPosition = function (position, space, mesh) {
  55565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55566. var lm = this.getLocalMatrix();
  55567. if (space == BABYLON.Space.LOCAL) {
  55568. lm.m[12] = position.x;
  55569. lm.m[13] = position.y;
  55570. lm.m[14] = position.z;
  55571. }
  55572. else {
  55573. var wm;
  55574. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55575. if (mesh) {
  55576. wm = mesh.getWorldMatrix();
  55577. }
  55578. this._skeleton.computeAbsoluteTransforms();
  55579. var tmat = Bone._tmpMats[0];
  55580. var vec = Bone._tmpVecs[0];
  55581. if (mesh) {
  55582. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55583. tmat.multiplyToRef(wm, tmat);
  55584. }
  55585. else {
  55586. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55587. }
  55588. tmat.invert();
  55589. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  55590. lm.m[12] = vec.x;
  55591. lm.m[13] = vec.y;
  55592. lm.m[14] = vec.z;
  55593. }
  55594. this.markAsDirty();
  55595. };
  55596. /**
  55597. * Set the absolute postion of the bone (world space).
  55598. * @param position The position to set the bone.
  55599. * @param mesh The mesh that this bone is attached to.
  55600. */
  55601. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  55602. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  55603. };
  55604. /**
  55605. * Set the scale of the bone on the x, y and z axes.
  55606. * @param x The scale of the bone on the x axis.
  55607. * @param x The scale of the bone on the y axis.
  55608. * @param z The scale of the bone on the z axis.
  55609. * @param scaleChildren Set this to true if children of the bone should be scaled.
  55610. */
  55611. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  55612. if (scaleChildren === void 0) { scaleChildren = false; }
  55613. if (this.animations[0] && !this.animations[0].isStopped()) {
  55614. if (!scaleChildren) {
  55615. this._negateScaleChildren.x = 1 / x;
  55616. this._negateScaleChildren.y = 1 / y;
  55617. this._negateScaleChildren.z = 1 / z;
  55618. }
  55619. this._syncScaleVector();
  55620. }
  55621. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  55622. };
  55623. /**
  55624. * Scale the bone on the x, y and z axes.
  55625. * @param x The amount to scale the bone on the x axis.
  55626. * @param x The amount to scale the bone on the y axis.
  55627. * @param z The amount to scale the bone on the z axis.
  55628. * @param scaleChildren Set this to true if children of the bone should be scaled.
  55629. */
  55630. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  55631. if (scaleChildren === void 0) { scaleChildren = false; }
  55632. var locMat = this.getLocalMatrix();
  55633. var origLocMat = Bone._tmpMats[0];
  55634. origLocMat.copyFrom(locMat);
  55635. var origLocMatInv = Bone._tmpMats[1];
  55636. origLocMatInv.copyFrom(origLocMat);
  55637. origLocMatInv.invert();
  55638. var scaleMat = Bone._tmpMats[2];
  55639. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  55640. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  55641. this._scaleVector.x *= x;
  55642. this._scaleVector.y *= y;
  55643. this._scaleVector.z *= z;
  55644. locMat.multiplyToRef(origLocMatInv, locMat);
  55645. locMat.multiplyToRef(scaleMat, locMat);
  55646. locMat.multiplyToRef(origLocMat, locMat);
  55647. var parent = this.getParent();
  55648. if (parent) {
  55649. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  55650. }
  55651. else {
  55652. this.getAbsoluteTransform().copyFrom(locMat);
  55653. }
  55654. var len = this.children.length;
  55655. scaleMat.invert();
  55656. for (var i = 0; i < len; i++) {
  55657. var child = this.children[i];
  55658. var cm = child.getLocalMatrix();
  55659. cm.multiplyToRef(scaleMat, cm);
  55660. var lm = child.getLocalMatrix();
  55661. lm.m[12] *= x;
  55662. lm.m[13] *= y;
  55663. lm.m[14] *= z;
  55664. }
  55665. this.computeAbsoluteTransforms();
  55666. if (scaleChildren) {
  55667. for (var i = 0; i < len; i++) {
  55668. this.children[i].scale(x, y, z, scaleChildren);
  55669. }
  55670. }
  55671. this.markAsDirty();
  55672. };
  55673. /**
  55674. * Set the yaw, pitch, and roll of the bone in local or world space.
  55675. * @param yaw The rotation of the bone on the y axis.
  55676. * @param pitch The rotation of the bone on the x axis.
  55677. * @param roll The rotation of the bone on the z axis.
  55678. * @param space The space that the axes of rotation are in.
  55679. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55680. */
  55681. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  55682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55683. var rotMat = Bone._tmpMats[0];
  55684. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  55685. var rotMatInv = Bone._tmpMats[1];
  55686. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55687. rotMatInv.multiplyToRef(rotMat, rotMat);
  55688. this._rotateWithMatrix(rotMat, space, mesh);
  55689. };
  55690. /**
  55691. * Rotate the bone on an axis in local or world space.
  55692. * @param axis The axis to rotate the bone on.
  55693. * @param amount The amount to rotate the bone.
  55694. * @param space The space that the axis is in.
  55695. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55696. */
  55697. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  55698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55699. var rmat = Bone._tmpMats[0];
  55700. rmat.m[12] = 0;
  55701. rmat.m[13] = 0;
  55702. rmat.m[14] = 0;
  55703. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  55704. this._rotateWithMatrix(rmat, space, mesh);
  55705. };
  55706. /**
  55707. * Set the rotation of the bone to a particular axis angle in local or world space.
  55708. * @param axis The axis to rotate the bone on.
  55709. * @param angle The angle that the bone should be rotated to.
  55710. * @param space The space that the axis is in.
  55711. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55712. */
  55713. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  55714. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55715. var rotMat = Bone._tmpMats[0];
  55716. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  55717. var rotMatInv = Bone._tmpMats[1];
  55718. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55719. rotMatInv.multiplyToRef(rotMat, rotMat);
  55720. this._rotateWithMatrix(rotMat, space, mesh);
  55721. };
  55722. /**
  55723. * Set the euler rotation of the bone in local of world space.
  55724. * @param rotation The euler rotation that the bone should be set to.
  55725. * @param space The space that the rotation is in.
  55726. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55727. */
  55728. Bone.prototype.setRotation = function (rotation, space, mesh) {
  55729. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55730. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  55731. };
  55732. /**
  55733. * Set the quaternion rotation of the bone in local of world space.
  55734. * @param quat The quaternion rotation that the bone should be set to.
  55735. * @param space The space that the rotation is in.
  55736. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55737. */
  55738. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  55739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55740. var rotMatInv = Bone._tmpMats[0];
  55741. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55742. var rotMat = Bone._tmpMats[1];
  55743. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  55744. rotMatInv.multiplyToRef(rotMat, rotMat);
  55745. this._rotateWithMatrix(rotMat, space, mesh);
  55746. };
  55747. /**
  55748. * Set the rotation matrix of the bone in local of world space.
  55749. * @param rotMat The rotation matrix that the bone should be set to.
  55750. * @param space The space that the rotation is in.
  55751. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55752. */
  55753. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  55754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55755. var rotMatInv = Bone._tmpMats[0];
  55756. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55757. var rotMat2 = Bone._tmpMats[1];
  55758. rotMat2.copyFrom(rotMat);
  55759. rotMatInv.multiplyToRef(rotMat, rotMat2);
  55760. this._rotateWithMatrix(rotMat2, space, mesh);
  55761. };
  55762. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  55763. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55764. var lmat = this.getLocalMatrix();
  55765. var lx = lmat.m[12];
  55766. var ly = lmat.m[13];
  55767. var lz = lmat.m[14];
  55768. var parent = this.getParent();
  55769. var parentScale = Bone._tmpMats[3];
  55770. var parentScaleInv = Bone._tmpMats[4];
  55771. if (parent) {
  55772. if (space == BABYLON.Space.WORLD) {
  55773. if (mesh) {
  55774. parentScale.copyFrom(mesh.getWorldMatrix());
  55775. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  55776. }
  55777. else {
  55778. parentScale.copyFrom(parent.getAbsoluteTransform());
  55779. }
  55780. }
  55781. else {
  55782. parentScale = parent._scaleMatrix;
  55783. }
  55784. parentScaleInv.copyFrom(parentScale);
  55785. parentScaleInv.invert();
  55786. lmat.multiplyToRef(parentScale, lmat);
  55787. lmat.multiplyToRef(rmat, lmat);
  55788. lmat.multiplyToRef(parentScaleInv, lmat);
  55789. }
  55790. else {
  55791. if (space == BABYLON.Space.WORLD && mesh) {
  55792. parentScale.copyFrom(mesh.getWorldMatrix());
  55793. parentScaleInv.copyFrom(parentScale);
  55794. parentScaleInv.invert();
  55795. lmat.multiplyToRef(parentScale, lmat);
  55796. lmat.multiplyToRef(rmat, lmat);
  55797. lmat.multiplyToRef(parentScaleInv, lmat);
  55798. }
  55799. else {
  55800. lmat.multiplyToRef(rmat, lmat);
  55801. }
  55802. }
  55803. lmat.m[12] = lx;
  55804. lmat.m[13] = ly;
  55805. lmat.m[14] = lz;
  55806. this.computeAbsoluteTransforms();
  55807. this.markAsDirty();
  55808. };
  55809. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  55810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55811. if (space == BABYLON.Space.WORLD) {
  55812. var scaleMatrix = Bone._tmpMats[2];
  55813. scaleMatrix.copyFrom(this._scaleMatrix);
  55814. rotMatInv.copyFrom(this.getAbsoluteTransform());
  55815. if (mesh) {
  55816. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  55817. var meshScale = Bone._tmpMats[3];
  55818. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  55819. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  55820. }
  55821. rotMatInv.invert();
  55822. scaleMatrix.m[0] *= this._scalingDeterminant;
  55823. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55824. }
  55825. else {
  55826. rotMatInv.copyFrom(this.getLocalMatrix());
  55827. rotMatInv.invert();
  55828. var scaleMatrix = Bone._tmpMats[2];
  55829. scaleMatrix.copyFrom(this._scaleMatrix);
  55830. if (this._parent) {
  55831. var pscaleMatrix = Bone._tmpMats[3];
  55832. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  55833. pscaleMatrix.invert();
  55834. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  55835. }
  55836. else {
  55837. scaleMatrix.m[0] *= this._scalingDeterminant;
  55838. }
  55839. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55840. }
  55841. };
  55842. /**
  55843. * Get the scale of the bone
  55844. * @returns the scale of the bone
  55845. */
  55846. Bone.prototype.getScale = function () {
  55847. return this._scaleVector.clone();
  55848. };
  55849. /**
  55850. * Copy the scale of the bone to a vector3.
  55851. * @param result The vector3 to copy the scale to
  55852. */
  55853. Bone.prototype.getScaleToRef = function (result) {
  55854. result.copyFrom(this._scaleVector);
  55855. };
  55856. /**
  55857. * Get the position of the bone in local or world space.
  55858. * @param space The space that the returned position is in.
  55859. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55860. * @returns The position of the bone
  55861. */
  55862. Bone.prototype.getPosition = function (space, mesh) {
  55863. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55864. var pos = BABYLON.Vector3.Zero();
  55865. this.getPositionToRef(space, mesh, pos);
  55866. return pos;
  55867. };
  55868. /**
  55869. * Copy the position of the bone to a vector3 in local or world space.
  55870. * @param space The space that the returned position is in.
  55871. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55872. * @param result The vector3 to copy the position to.
  55873. */
  55874. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  55875. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55876. if (space == BABYLON.Space.LOCAL) {
  55877. var lm = this.getLocalMatrix();
  55878. result.x = lm.m[12];
  55879. result.y = lm.m[13];
  55880. result.z = lm.m[14];
  55881. }
  55882. else {
  55883. var wm;
  55884. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55885. if (mesh) {
  55886. wm = mesh.getWorldMatrix();
  55887. }
  55888. this._skeleton.computeAbsoluteTransforms();
  55889. var tmat = Bone._tmpMats[0];
  55890. if (mesh) {
  55891. tmat.copyFrom(this.getAbsoluteTransform());
  55892. tmat.multiplyToRef(wm, tmat);
  55893. }
  55894. else {
  55895. tmat = this.getAbsoluteTransform();
  55896. }
  55897. result.x = tmat.m[12];
  55898. result.y = tmat.m[13];
  55899. result.z = tmat.m[14];
  55900. }
  55901. };
  55902. /**
  55903. * Get the absolute position of the bone (world space).
  55904. * @param mesh The mesh that this bone is attached to.
  55905. * @returns The absolute position of the bone
  55906. */
  55907. Bone.prototype.getAbsolutePosition = function (mesh) {
  55908. var pos = BABYLON.Vector3.Zero();
  55909. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  55910. return pos;
  55911. };
  55912. /**
  55913. * Copy the absolute position of the bone (world space) to the result param.
  55914. * @param mesh The mesh that this bone is attached to.
  55915. * @param result The vector3 to copy the absolute position to.
  55916. */
  55917. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  55918. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  55919. };
  55920. /**
  55921. * Compute the absolute transforms of this bone and its children.
  55922. */
  55923. Bone.prototype.computeAbsoluteTransforms = function () {
  55924. if (this._parent) {
  55925. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  55926. }
  55927. else {
  55928. this._absoluteTransform.copyFrom(this._localMatrix);
  55929. var poseMatrix = this._skeleton.getPoseMatrix();
  55930. if (poseMatrix) {
  55931. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  55932. }
  55933. }
  55934. var children = this.children;
  55935. var len = children.length;
  55936. for (var i = 0; i < len; i++) {
  55937. children[i].computeAbsoluteTransforms();
  55938. }
  55939. };
  55940. Bone.prototype._syncScaleVector = function () {
  55941. var lm = this.getLocalMatrix();
  55942. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  55943. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  55944. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  55945. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  55946. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  55947. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  55948. this._scaleVector.x = xs * Math.sqrt(xsq);
  55949. this._scaleVector.y = ys * Math.sqrt(ysq);
  55950. this._scaleVector.z = zs * Math.sqrt(zsq);
  55951. if (this._parent) {
  55952. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  55953. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  55954. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  55955. }
  55956. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  55957. };
  55958. /**
  55959. * Get the world direction from an axis that is in the local space of the bone.
  55960. * @param localAxis The local direction that is used to compute the world direction.
  55961. * @param mesh The mesh that this bone is attached to.
  55962. * @returns The world direction
  55963. */
  55964. Bone.prototype.getDirection = function (localAxis, mesh) {
  55965. var result = BABYLON.Vector3.Zero();
  55966. this.getDirectionToRef(localAxis, mesh, result);
  55967. return result;
  55968. };
  55969. /**
  55970. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  55971. * @param localAxis The local direction that is used to compute the world direction.
  55972. * @param mesh The mesh that this bone is attached to.
  55973. * @param result The vector3 that the world direction will be copied to.
  55974. */
  55975. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  55976. var wm;
  55977. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55978. if (mesh) {
  55979. wm = mesh.getWorldMatrix();
  55980. }
  55981. this._skeleton.computeAbsoluteTransforms();
  55982. var mat = Bone._tmpMats[0];
  55983. mat.copyFrom(this.getAbsoluteTransform());
  55984. if (mesh) {
  55985. mat.multiplyToRef(wm, mat);
  55986. }
  55987. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  55988. result.normalize();
  55989. };
  55990. /**
  55991. * Get the euler rotation of the bone in local or world space.
  55992. * @param space The space that the rotation should be in.
  55993. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55994. * @returns The euler rotation
  55995. */
  55996. Bone.prototype.getRotation = function (space, mesh) {
  55997. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55998. var result = BABYLON.Vector3.Zero();
  55999. this.getRotationToRef(space, mesh, result);
  56000. return result;
  56001. };
  56002. /**
  56003. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  56004. * @param space The space that the rotation should be in.
  56005. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56006. * @param result The vector3 that the rotation should be copied to.
  56007. */
  56008. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  56009. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56010. var quat = Bone._tmpQuat;
  56011. this.getRotationQuaternionToRef(space, mesh, quat);
  56012. quat.toEulerAnglesToRef(result);
  56013. };
  56014. /**
  56015. * Get the quaternion rotation of the bone in either local or world space.
  56016. * @param space The space that the rotation should be in.
  56017. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56018. * @returns The quaternion rotation
  56019. */
  56020. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  56021. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56022. var result = BABYLON.Quaternion.Identity();
  56023. this.getRotationQuaternionToRef(space, mesh, result);
  56024. return result;
  56025. };
  56026. /**
  56027. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  56028. * @param space The space that the rotation should be in.
  56029. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56030. * @param result The quaternion that the rotation should be copied to.
  56031. */
  56032. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  56033. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56034. if (space == BABYLON.Space.LOCAL) {
  56035. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56036. }
  56037. else {
  56038. var mat = Bone._tmpMats[0];
  56039. var amat = this.getAbsoluteTransform();
  56040. if (mesh) {
  56041. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56042. }
  56043. else {
  56044. mat.copyFrom(amat);
  56045. }
  56046. mat.m[0] *= this._scalingDeterminant;
  56047. mat.m[1] *= this._scalingDeterminant;
  56048. mat.m[2] *= this._scalingDeterminant;
  56049. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56050. }
  56051. };
  56052. /**
  56053. * Get the rotation matrix of the bone in local or world space.
  56054. * @param space The space that the rotation should be in.
  56055. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56056. * @returns The rotation matrix
  56057. */
  56058. Bone.prototype.getRotationMatrix = function (space, mesh) {
  56059. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56060. var result = BABYLON.Matrix.Identity();
  56061. this.getRotationMatrixToRef(space, mesh, result);
  56062. return result;
  56063. };
  56064. /**
  56065. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  56066. * @param space The space that the rotation should be in.
  56067. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56068. * @param result The quaternion that the rotation should be copied to.
  56069. */
  56070. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  56071. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56072. if (space == BABYLON.Space.LOCAL) {
  56073. this.getLocalMatrix().getRotationMatrixToRef(result);
  56074. }
  56075. else {
  56076. var mat = Bone._tmpMats[0];
  56077. var amat = this.getAbsoluteTransform();
  56078. if (mesh) {
  56079. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56080. }
  56081. else {
  56082. mat.copyFrom(amat);
  56083. }
  56084. mat.m[0] *= this._scalingDeterminant;
  56085. mat.m[1] *= this._scalingDeterminant;
  56086. mat.m[2] *= this._scalingDeterminant;
  56087. mat.getRotationMatrixToRef(result);
  56088. }
  56089. };
  56090. /**
  56091. * Get the world position of a point that is in the local space of the bone.
  56092. * @param position The local position
  56093. * @param mesh The mesh that this bone is attached to.
  56094. * @returns The world position
  56095. */
  56096. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  56097. var result = BABYLON.Vector3.Zero();
  56098. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  56099. return result;
  56100. };
  56101. /**
  56102. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  56103. * @param position The local position
  56104. * @param mesh The mesh that this bone is attached to.
  56105. * @param result The vector3 that the world position should be copied to.
  56106. */
  56107. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  56108. var wm;
  56109. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56110. if (mesh) {
  56111. wm = mesh.getWorldMatrix();
  56112. }
  56113. this._skeleton.computeAbsoluteTransforms();
  56114. var tmat = Bone._tmpMats[0];
  56115. if (mesh) {
  56116. tmat.copyFrom(this.getAbsoluteTransform());
  56117. tmat.multiplyToRef(wm, tmat);
  56118. }
  56119. else {
  56120. tmat = this.getAbsoluteTransform();
  56121. }
  56122. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56123. };
  56124. /**
  56125. * Get the local position of a point that is in world space.
  56126. * @param position The world position
  56127. * @param mesh The mesh that this bone is attached to.
  56128. * @returns The local position
  56129. */
  56130. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  56131. var result = BABYLON.Vector3.Zero();
  56132. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  56133. return result;
  56134. };
  56135. /**
  56136. * Get the local position of a point that is in world space and copy it to the result param.
  56137. * @param position The world position
  56138. * @param mesh The mesh that this bone is attached to.
  56139. * @param result The vector3 that the local position should be copied to.
  56140. */
  56141. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  56142. var wm;
  56143. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56144. if (mesh) {
  56145. wm = mesh.getWorldMatrix();
  56146. }
  56147. this._skeleton.computeAbsoluteTransforms();
  56148. var tmat = Bone._tmpMats[0];
  56149. tmat.copyFrom(this.getAbsoluteTransform());
  56150. if (mesh) {
  56151. tmat.multiplyToRef(wm, tmat);
  56152. }
  56153. tmat.invert();
  56154. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56155. };
  56156. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56157. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  56158. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56159. return Bone;
  56160. }(BABYLON.Node));
  56161. BABYLON.Bone = Bone;
  56162. })(BABYLON || (BABYLON = {}));
  56163. //# sourceMappingURL=babylon.bone.js.map
  56164. var BABYLON;
  56165. (function (BABYLON) {
  56166. var BoneIKController = (function () {
  56167. function BoneIKController(mesh, bone, options) {
  56168. this.targetPosition = BABYLON.Vector3.Zero();
  56169. this.poleTargetPosition = BABYLON.Vector3.Zero();
  56170. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  56171. this.poleAngle = 0;
  56172. this.slerpAmount = 1;
  56173. this._bone1Quat = BABYLON.Quaternion.Identity();
  56174. this._bone1Mat = BABYLON.Matrix.Identity();
  56175. this._bone2Ang = Math.PI;
  56176. this._maxAngle = Math.PI;
  56177. this._rightHandedSystem = false;
  56178. this._bendAxis = BABYLON.Vector3.Right();
  56179. this._slerping = false;
  56180. this._adjustRoll = 0;
  56181. this._bone2 = bone;
  56182. this._bone1 = bone.getParent();
  56183. this.mesh = mesh;
  56184. var bonePos = bone.getPosition();
  56185. if (bone.getAbsoluteTransform().determinant() > 0) {
  56186. this._rightHandedSystem = true;
  56187. this._bendAxis.x = 0;
  56188. this._bendAxis.y = 0;
  56189. this._bendAxis.z = -1;
  56190. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  56191. this._adjustRoll = Math.PI * .5;
  56192. this._bendAxis.z = 1;
  56193. }
  56194. }
  56195. if (this._bone1.length) {
  56196. var boneScale1 = this._bone1.getScale();
  56197. var boneScale2 = this._bone2.getScale();
  56198. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  56199. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  56200. }
  56201. else if (this._bone1.children[0]) {
  56202. mesh.computeWorldMatrix(true);
  56203. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  56204. var pos2 = this._bone2.getAbsolutePosition(mesh);
  56205. var pos3 = this._bone1.getAbsolutePosition(mesh);
  56206. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  56207. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  56208. }
  56209. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  56210. this.maxAngle = Math.PI;
  56211. if (options) {
  56212. if (options.targetMesh) {
  56213. this.targetMesh = options.targetMesh;
  56214. this.targetMesh.computeWorldMatrix(true);
  56215. }
  56216. if (options.poleTargetMesh) {
  56217. this.poleTargetMesh = options.poleTargetMesh;
  56218. this.poleTargetMesh.computeWorldMatrix(true);
  56219. }
  56220. else if (options.poleTargetBone) {
  56221. this.poleTargetBone = options.poleTargetBone;
  56222. }
  56223. else if (this._bone1.getParent()) {
  56224. this.poleTargetBone = this._bone1.getParent();
  56225. }
  56226. if (options.poleTargetLocalOffset) {
  56227. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  56228. }
  56229. if (options.poleAngle) {
  56230. this.poleAngle = options.poleAngle;
  56231. }
  56232. if (options.bendAxis) {
  56233. this._bendAxis.copyFrom(options.bendAxis);
  56234. }
  56235. if (options.maxAngle) {
  56236. this.maxAngle = options.maxAngle;
  56237. }
  56238. if (options.slerpAmount) {
  56239. this.slerpAmount = options.slerpAmount;
  56240. }
  56241. }
  56242. }
  56243. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  56244. get: function () {
  56245. return this._maxAngle;
  56246. },
  56247. set: function (value) {
  56248. this._setMaxAngle(value);
  56249. },
  56250. enumerable: true,
  56251. configurable: true
  56252. });
  56253. BoneIKController.prototype._setMaxAngle = function (ang) {
  56254. if (ang < 0) {
  56255. ang = 0;
  56256. }
  56257. if (ang > Math.PI || ang == undefined) {
  56258. ang = Math.PI;
  56259. }
  56260. this._maxAngle = ang;
  56261. var a = this._bone1Length;
  56262. var b = this._bone2Length;
  56263. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  56264. };
  56265. BoneIKController.prototype.update = function () {
  56266. var bone1 = this._bone1;
  56267. var target = this.targetPosition;
  56268. var poleTarget = this.poleTargetPosition;
  56269. var mat1 = BoneIKController._tmpMats[0];
  56270. var mat2 = BoneIKController._tmpMats[1];
  56271. if (this.targetMesh) {
  56272. target.copyFrom(this.targetMesh.getAbsolutePosition());
  56273. }
  56274. if (this.poleTargetBone) {
  56275. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  56276. }
  56277. else if (this.poleTargetMesh) {
  56278. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  56279. }
  56280. var bonePos = BoneIKController._tmpVecs[0];
  56281. var zaxis = BoneIKController._tmpVecs[1];
  56282. var xaxis = BoneIKController._tmpVecs[2];
  56283. var yaxis = BoneIKController._tmpVecs[3];
  56284. var upAxis = BoneIKController._tmpVecs[4];
  56285. var _tmpQuat = BoneIKController._tmpQuat;
  56286. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  56287. poleTarget.subtractToRef(bonePos, upAxis);
  56288. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  56289. upAxis.y = 1;
  56290. }
  56291. else {
  56292. upAxis.normalize();
  56293. }
  56294. target.subtractToRef(bonePos, yaxis);
  56295. yaxis.normalize();
  56296. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  56297. zaxis.normalize();
  56298. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  56299. xaxis.normalize();
  56300. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  56301. var a = this._bone1Length;
  56302. var b = this._bone2Length;
  56303. var c = BABYLON.Vector3.Distance(bonePos, target);
  56304. if (this._maxReach > 0) {
  56305. c = Math.min(this._maxReach, c);
  56306. }
  56307. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  56308. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  56309. if (acosa > 1) {
  56310. acosa = 1;
  56311. }
  56312. if (acosb > 1) {
  56313. acosb = 1;
  56314. }
  56315. if (acosa < -1) {
  56316. acosa = -1;
  56317. }
  56318. if (acosb < -1) {
  56319. acosb = -1;
  56320. }
  56321. var angA = Math.acos(acosa);
  56322. var angB = Math.acos(acosb);
  56323. var angC = -angA - angB;
  56324. if (this._rightHandedSystem) {
  56325. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  56326. mat2.multiplyToRef(mat1, mat1);
  56327. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  56328. mat2.multiplyToRef(mat1, mat1);
  56329. }
  56330. else {
  56331. var _tmpVec = BoneIKController._tmpVecs[5];
  56332. _tmpVec.copyFrom(this._bendAxis);
  56333. _tmpVec.x *= -1;
  56334. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  56335. mat2.multiplyToRef(mat1, mat1);
  56336. }
  56337. if (this.poleAngle) {
  56338. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  56339. mat1.multiplyToRef(mat2, mat1);
  56340. }
  56341. if (this.slerpAmount < 1) {
  56342. if (!this._slerping) {
  56343. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  56344. }
  56345. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  56346. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  56347. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  56348. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  56349. this._slerping = true;
  56350. }
  56351. else {
  56352. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  56353. this._bone1Mat.copyFrom(mat1);
  56354. this._slerping = false;
  56355. }
  56356. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  56357. this._bone2Ang = angC;
  56358. };
  56359. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56360. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  56361. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56362. return BoneIKController;
  56363. }());
  56364. BABYLON.BoneIKController = BoneIKController;
  56365. })(BABYLON || (BABYLON = {}));
  56366. //# sourceMappingURL=babylon.boneIKController.js.map
  56367. var BABYLON;
  56368. (function (BABYLON) {
  56369. var BoneLookController = (function () {
  56370. /**
  56371. * Create a BoneLookController
  56372. * @param mesh the mesh that the bone belongs to
  56373. * @param bone the bone that will be looking to the target
  56374. * @param target the target Vector3 to look at
  56375. * @param settings optional settings:
  56376. * - maxYaw: the maximum angle the bone will yaw to
  56377. * - minYaw: the minimum angle the bone will yaw to
  56378. * - maxPitch: the maximum angle the bone will pitch to
  56379. * - minPitch: the minimum angle the bone will yaw to
  56380. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  56381. * - upAxis: the up axis of the coordinate system
  56382. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  56383. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  56384. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  56385. * - adjustYaw: used to make an adjustment to the yaw of the bone
  56386. * - adjustPitch: used to make an adjustment to the pitch of the bone
  56387. * - adjustRoll: used to make an adjustment to the roll of the bone
  56388. **/
  56389. function BoneLookController(mesh, bone, target, options) {
  56390. /**
  56391. * The up axis of the coordinate system that is used when the bone is rotated.
  56392. */
  56393. this.upAxis = BABYLON.Vector3.Up();
  56394. /**
  56395. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  56396. */
  56397. this.upAxisSpace = BABYLON.Space.LOCAL;
  56398. /**
  56399. * Used to make an adjustment to the yaw of the bone.
  56400. */
  56401. this.adjustYaw = 0;
  56402. /**
  56403. * Used to make an adjustment to the pitch of the bone.
  56404. */
  56405. this.adjustPitch = 0;
  56406. /**
  56407. * Used to make an adjustment to the roll of the bone.
  56408. */
  56409. this.adjustRoll = 0;
  56410. /**
  56411. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  56412. */
  56413. this.slerpAmount = 1;
  56414. this._boneQuat = BABYLON.Quaternion.Identity();
  56415. this._slerping = false;
  56416. this._firstFrameSkipped = false;
  56417. this._fowardAxis = BABYLON.Vector3.Forward();
  56418. this.mesh = mesh;
  56419. this.bone = bone;
  56420. this.target = target;
  56421. if (options) {
  56422. if (options.adjustYaw) {
  56423. this.adjustYaw = options.adjustYaw;
  56424. }
  56425. if (options.adjustPitch) {
  56426. this.adjustPitch = options.adjustPitch;
  56427. }
  56428. if (options.adjustRoll) {
  56429. this.adjustRoll = options.adjustRoll;
  56430. }
  56431. if (options.maxYaw != null) {
  56432. this.maxYaw = options.maxYaw;
  56433. }
  56434. else {
  56435. this.maxYaw = Math.PI;
  56436. }
  56437. if (options.minYaw != null) {
  56438. this.minYaw = options.minYaw;
  56439. }
  56440. else {
  56441. this.minYaw = -Math.PI;
  56442. }
  56443. if (options.maxPitch != null) {
  56444. this.maxPitch = options.maxPitch;
  56445. }
  56446. else {
  56447. this.maxPitch = Math.PI;
  56448. }
  56449. if (options.minPitch != null) {
  56450. this.minPitch = options.minPitch;
  56451. }
  56452. else {
  56453. this.minPitch = -Math.PI;
  56454. }
  56455. if (options.slerpAmount != null) {
  56456. this.slerpAmount = options.slerpAmount;
  56457. }
  56458. if (options.upAxis != null) {
  56459. this.upAxis = options.upAxis;
  56460. }
  56461. if (options.upAxisSpace != null) {
  56462. this.upAxisSpace = options.upAxisSpace;
  56463. }
  56464. if (options.yawAxis != null || options.pitchAxis != null) {
  56465. var newYawAxis = BABYLON.Axis.Y;
  56466. var newPitchAxis = BABYLON.Axis.X;
  56467. if (options.yawAxis != null) {
  56468. newYawAxis = options.yawAxis.clone();
  56469. newYawAxis.normalize();
  56470. }
  56471. if (options.pitchAxis != null) {
  56472. newPitchAxis = options.pitchAxis.clone();
  56473. newPitchAxis.normalize();
  56474. }
  56475. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  56476. this._transformYawPitch = BABYLON.Matrix.Identity();
  56477. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  56478. this._transformYawPitchInv = this._transformYawPitch.clone();
  56479. this._transformYawPitch.invert();
  56480. }
  56481. }
  56482. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  56483. this.upAxisSpace = BABYLON.Space.LOCAL;
  56484. }
  56485. }
  56486. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  56487. /**
  56488. * Get/set the minimum yaw angle that the bone can look to.
  56489. */
  56490. get: function () {
  56491. return this._minYaw;
  56492. },
  56493. set: function (value) {
  56494. this._minYaw = value;
  56495. this._minYawSin = Math.sin(value);
  56496. this._minYawCos = Math.cos(value);
  56497. if (this._maxYaw != null) {
  56498. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  56499. this._yawRange = this._maxYaw - this._minYaw;
  56500. }
  56501. },
  56502. enumerable: true,
  56503. configurable: true
  56504. });
  56505. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  56506. /**
  56507. * Get/set the maximum yaw angle that the bone can look to.
  56508. */
  56509. get: function () {
  56510. return this._maxYaw;
  56511. },
  56512. set: function (value) {
  56513. this._maxYaw = value;
  56514. this._maxYawSin = Math.sin(value);
  56515. this._maxYawCos = Math.cos(value);
  56516. if (this._minYaw != null) {
  56517. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  56518. this._yawRange = this._maxYaw - this._minYaw;
  56519. }
  56520. },
  56521. enumerable: true,
  56522. configurable: true
  56523. });
  56524. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  56525. /**
  56526. * Get/set the minimum pitch angle that the bone can look to.
  56527. */
  56528. get: function () {
  56529. return this._minPitch;
  56530. },
  56531. set: function (value) {
  56532. this._minPitch = value;
  56533. this._minPitchTan = Math.tan(value);
  56534. },
  56535. enumerable: true,
  56536. configurable: true
  56537. });
  56538. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  56539. /**
  56540. * Get/set the maximum pitch angle that the bone can look to.
  56541. */
  56542. get: function () {
  56543. return this._maxPitch;
  56544. },
  56545. set: function (value) {
  56546. this._maxPitch = value;
  56547. this._maxPitchTan = Math.tan(value);
  56548. },
  56549. enumerable: true,
  56550. configurable: true
  56551. });
  56552. /**
  56553. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  56554. */
  56555. BoneLookController.prototype.update = function () {
  56556. //skip the first frame when slerping so that the mesh rotation is correct
  56557. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  56558. this._firstFrameSkipped = true;
  56559. return;
  56560. }
  56561. var bone = this.bone;
  56562. var bonePos = BoneLookController._tmpVecs[0];
  56563. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  56564. var target = this.target;
  56565. var _tmpMat1 = BoneLookController._tmpMats[0];
  56566. var _tmpMat2 = BoneLookController._tmpMats[1];
  56567. var mesh = this.mesh;
  56568. var parentBone = bone.getParent();
  56569. var upAxis = BoneLookController._tmpVecs[1];
  56570. upAxis.copyFrom(this.upAxis);
  56571. if (this.upAxisSpace == BABYLON.Space.BONE) {
  56572. if (this._transformYawPitch) {
  56573. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  56574. }
  56575. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  56576. }
  56577. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  56578. mesh.getDirectionToRef(upAxis, upAxis);
  56579. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  56580. upAxis.normalize();
  56581. }
  56582. }
  56583. var checkYaw = false;
  56584. var checkPitch = false;
  56585. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  56586. checkYaw = true;
  56587. }
  56588. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  56589. checkPitch = true;
  56590. }
  56591. if (checkYaw || checkPitch) {
  56592. var spaceMat = BoneLookController._tmpMats[2];
  56593. var spaceMatInv = BoneLookController._tmpMats[3];
  56594. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  56595. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  56596. }
  56597. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  56598. spaceMat.copyFrom(mesh.getWorldMatrix());
  56599. }
  56600. else {
  56601. var forwardAxis = BoneLookController._tmpVecs[2];
  56602. forwardAxis.copyFrom(this._fowardAxis);
  56603. if (this._transformYawPitch) {
  56604. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  56605. }
  56606. if (parentBone) {
  56607. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  56608. }
  56609. else {
  56610. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  56611. }
  56612. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  56613. rightAxis.normalize();
  56614. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  56615. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  56616. }
  56617. spaceMat.invertToRef(spaceMatInv);
  56618. var xzlen;
  56619. if (checkPitch) {
  56620. var localTarget = BoneLookController._tmpVecs[3];
  56621. target.subtractToRef(bonePos, localTarget);
  56622. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  56623. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56624. var pitch = Math.atan2(localTarget.y, xzlen);
  56625. var newPitch = pitch;
  56626. if (pitch > this._maxPitch) {
  56627. localTarget.y = this._maxPitchTan * xzlen;
  56628. newPitch = this._maxPitch;
  56629. }
  56630. else if (pitch < this._minPitch) {
  56631. localTarget.y = this._minPitchTan * xzlen;
  56632. newPitch = this._minPitch;
  56633. }
  56634. if (pitch != newPitch) {
  56635. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  56636. localTarget.addInPlace(bonePos);
  56637. target = localTarget;
  56638. }
  56639. }
  56640. if (checkYaw) {
  56641. var localTarget = BoneLookController._tmpVecs[4];
  56642. target.subtractToRef(bonePos, localTarget);
  56643. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  56644. var yaw = Math.atan2(localTarget.x, localTarget.z);
  56645. var newYaw = yaw;
  56646. if (yaw > this._maxYaw || yaw < this._minYaw) {
  56647. if (xzlen == null) {
  56648. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56649. }
  56650. if (this._yawRange > Math.PI) {
  56651. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  56652. localTarget.z = this._maxYawCos * xzlen;
  56653. localTarget.x = this._maxYawSin * xzlen;
  56654. newYaw = this._maxYaw;
  56655. }
  56656. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  56657. localTarget.z = this._minYawCos * xzlen;
  56658. localTarget.x = this._minYawSin * xzlen;
  56659. newYaw = this._minYaw;
  56660. }
  56661. }
  56662. else {
  56663. if (yaw > this._maxYaw) {
  56664. localTarget.z = this._maxYawCos * xzlen;
  56665. localTarget.x = this._maxYawSin * xzlen;
  56666. newYaw = this._maxYaw;
  56667. }
  56668. else if (yaw < this._minYaw) {
  56669. localTarget.z = this._minYawCos * xzlen;
  56670. localTarget.x = this._minYawSin * xzlen;
  56671. newYaw = this._minYaw;
  56672. }
  56673. }
  56674. }
  56675. if (this._slerping && this._yawRange > Math.PI) {
  56676. //are we going to be crossing into the min/max region?
  56677. var boneFwd = BoneLookController._tmpVecs[8];
  56678. boneFwd.copyFrom(BABYLON.Axis.Z);
  56679. if (this._transformYawPitch) {
  56680. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  56681. }
  56682. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  56683. this._boneQuat.toRotationMatrix(boneRotMat);
  56684. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  56685. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  56686. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  56687. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  56688. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  56689. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  56690. if (angBtwTar > angBtwMidYaw) {
  56691. if (xzlen == null) {
  56692. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56693. }
  56694. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  56695. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  56696. if (angBtwMin < angBtwMax) {
  56697. newYaw = boneYaw + Math.PI * .75;
  56698. localTarget.z = Math.cos(newYaw) * xzlen;
  56699. localTarget.x = Math.sin(newYaw) * xzlen;
  56700. }
  56701. else {
  56702. newYaw = boneYaw - Math.PI * .75;
  56703. localTarget.z = Math.cos(newYaw) * xzlen;
  56704. localTarget.x = Math.sin(newYaw) * xzlen;
  56705. }
  56706. }
  56707. }
  56708. if (yaw != newYaw) {
  56709. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  56710. localTarget.addInPlace(bonePos);
  56711. target = localTarget;
  56712. }
  56713. }
  56714. }
  56715. var zaxis = BoneLookController._tmpVecs[5];
  56716. var xaxis = BoneLookController._tmpVecs[6];
  56717. var yaxis = BoneLookController._tmpVecs[7];
  56718. var _tmpQuat = BoneLookController._tmpQuat;
  56719. target.subtractToRef(bonePos, zaxis);
  56720. zaxis.normalize();
  56721. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  56722. xaxis.normalize();
  56723. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  56724. yaxis.normalize();
  56725. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  56726. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  56727. return;
  56728. }
  56729. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  56730. return;
  56731. }
  56732. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  56733. return;
  56734. }
  56735. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  56736. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  56737. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  56738. }
  56739. if (this.slerpAmount < 1) {
  56740. if (!this._slerping) {
  56741. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  56742. }
  56743. if (this._transformYawPitch) {
  56744. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  56745. }
  56746. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  56747. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  56748. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  56749. this._slerping = true;
  56750. }
  56751. else {
  56752. if (this._transformYawPitch) {
  56753. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  56754. }
  56755. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  56756. this._slerping = false;
  56757. }
  56758. };
  56759. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  56760. var angDiff = ang2 - ang1;
  56761. angDiff %= Math.PI * 2;
  56762. if (angDiff > Math.PI) {
  56763. angDiff -= Math.PI * 2;
  56764. }
  56765. else if (angDiff < -Math.PI) {
  56766. angDiff += Math.PI * 2;
  56767. }
  56768. return angDiff;
  56769. };
  56770. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  56771. ang1 %= (2 * Math.PI);
  56772. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56773. ang2 %= (2 * Math.PI);
  56774. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56775. var ab = 0;
  56776. if (ang1 < ang2) {
  56777. ab = ang2 - ang1;
  56778. }
  56779. else {
  56780. ab = ang1 - ang2;
  56781. }
  56782. if (ab > Math.PI) {
  56783. ab = Math.PI * 2 - ab;
  56784. }
  56785. return ab;
  56786. };
  56787. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  56788. ang %= (2 * Math.PI);
  56789. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  56790. ang1 %= (2 * Math.PI);
  56791. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56792. ang2 %= (2 * Math.PI);
  56793. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56794. if (ang1 < ang2) {
  56795. if (ang > ang1 && ang < ang2) {
  56796. return true;
  56797. }
  56798. }
  56799. else {
  56800. if (ang > ang2 && ang < ang1) {
  56801. return true;
  56802. }
  56803. }
  56804. return false;
  56805. };
  56806. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56807. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  56808. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56809. return BoneLookController;
  56810. }());
  56811. BABYLON.BoneLookController = BoneLookController;
  56812. })(BABYLON || (BABYLON = {}));
  56813. //# sourceMappingURL=babylon.boneLookController.js.map
  56814. var BABYLON;
  56815. (function (BABYLON) {
  56816. var Skeleton = (function () {
  56817. function Skeleton(name, id, scene) {
  56818. this.name = name;
  56819. this.id = id;
  56820. this.bones = new Array();
  56821. this.needInitialSkinMatrix = false;
  56822. this._isDirty = true;
  56823. this._meshesWithPoseMatrix = new Array();
  56824. this._identity = BABYLON.Matrix.Identity();
  56825. this._ranges = {};
  56826. this._lastAbsoluteTransformsUpdateId = -1;
  56827. // Events
  56828. /**
  56829. * An event triggered before computing the skeleton's matrices
  56830. * @type {BABYLON.Observable}
  56831. */
  56832. this.onBeforeComputeObservable = new BABYLON.Observable();
  56833. this.bones = [];
  56834. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56835. scene.skeletons.push(this);
  56836. //make sure it will recalculate the matrix next time prepare is called.
  56837. this._isDirty = true;
  56838. }
  56839. // Members
  56840. Skeleton.prototype.getTransformMatrices = function (mesh) {
  56841. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  56842. return mesh._bonesTransformMatrices;
  56843. }
  56844. if (!this._transformMatrices) {
  56845. this.prepare();
  56846. }
  56847. return this._transformMatrices;
  56848. };
  56849. Skeleton.prototype.getScene = function () {
  56850. return this._scene;
  56851. };
  56852. // Methods
  56853. /**
  56854. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  56855. */
  56856. Skeleton.prototype.toString = function (fullDetails) {
  56857. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  56858. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  56859. if (fullDetails) {
  56860. ret += ", Ranges: {";
  56861. var first = true;
  56862. for (var name_1 in this._ranges) {
  56863. if (first) {
  56864. ret += ", ";
  56865. first = false;
  56866. }
  56867. ret += name_1;
  56868. }
  56869. ret += "}";
  56870. }
  56871. return ret;
  56872. };
  56873. /**
  56874. * Get bone's index searching by name
  56875. * @param {string} name is bone's name to search for
  56876. * @return {number} Indice of the bone. Returns -1 if not found
  56877. */
  56878. Skeleton.prototype.getBoneIndexByName = function (name) {
  56879. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  56880. if (this.bones[boneIndex].name === name) {
  56881. return boneIndex;
  56882. }
  56883. }
  56884. return -1;
  56885. };
  56886. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  56887. // check name not already in use
  56888. if (!this._ranges[name]) {
  56889. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  56890. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56891. if (this.bones[i].animations[0]) {
  56892. this.bones[i].animations[0].createRange(name, from, to);
  56893. }
  56894. }
  56895. }
  56896. };
  56897. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  56898. if (deleteFrames === void 0) { deleteFrames = true; }
  56899. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56900. if (this.bones[i].animations[0]) {
  56901. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  56902. }
  56903. }
  56904. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  56905. };
  56906. Skeleton.prototype.getAnimationRange = function (name) {
  56907. return this._ranges[name];
  56908. };
  56909. /**
  56910. * Returns as an Array, all AnimationRanges defined on this skeleton
  56911. */
  56912. Skeleton.prototype.getAnimationRanges = function () {
  56913. var animationRanges = [];
  56914. var name;
  56915. var i = 0;
  56916. for (name in this._ranges) {
  56917. animationRanges[i] = this._ranges[name];
  56918. i++;
  56919. }
  56920. return animationRanges;
  56921. };
  56922. /**
  56923. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  56924. */
  56925. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  56926. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56927. if (this._ranges[name] || !source.getAnimationRange(name)) {
  56928. return false;
  56929. }
  56930. var ret = true;
  56931. var frameOffset = this._getHighestAnimationFrame() + 1;
  56932. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  56933. var boneDict = {};
  56934. var sourceBones = source.bones;
  56935. var nBones;
  56936. var i;
  56937. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  56938. boneDict[sourceBones[i].name] = sourceBones[i];
  56939. }
  56940. if (this.bones.length !== sourceBones.length) {
  56941. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  56942. ret = false;
  56943. }
  56944. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  56945. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  56946. var boneName = this.bones[i].name;
  56947. var sourceBone = boneDict[boneName];
  56948. if (sourceBone) {
  56949. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  56950. }
  56951. else {
  56952. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  56953. ret = false;
  56954. }
  56955. }
  56956. // do not call createAnimationRange(), since it also is done to bones, which was already done
  56957. var range = source.getAnimationRange(name);
  56958. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  56959. return ret;
  56960. };
  56961. Skeleton.prototype.returnToRest = function () {
  56962. for (var index = 0; index < this.bones.length; index++) {
  56963. this.bones[index].returnToRest();
  56964. }
  56965. };
  56966. Skeleton.prototype._getHighestAnimationFrame = function () {
  56967. var ret = 0;
  56968. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56969. if (this.bones[i].animations[0]) {
  56970. var highest = this.bones[i].animations[0].getHighestFrame();
  56971. if (ret < highest) {
  56972. ret = highest;
  56973. }
  56974. }
  56975. }
  56976. return ret;
  56977. };
  56978. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  56979. var range = this.getAnimationRange(name);
  56980. if (!range) {
  56981. return null;
  56982. }
  56983. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  56984. };
  56985. Skeleton.prototype._markAsDirty = function () {
  56986. this._isDirty = true;
  56987. };
  56988. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  56989. this._meshesWithPoseMatrix.push(mesh);
  56990. };
  56991. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  56992. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  56993. if (index > -1) {
  56994. this._meshesWithPoseMatrix.splice(index, 1);
  56995. }
  56996. };
  56997. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  56998. this.onBeforeComputeObservable.notifyObservers(this);
  56999. for (var index = 0; index < this.bones.length; index++) {
  57000. var bone = this.bones[index];
  57001. var parentBone = bone.getParent();
  57002. if (parentBone) {
  57003. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  57004. }
  57005. else {
  57006. if (initialSkinMatrix) {
  57007. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  57008. }
  57009. else {
  57010. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  57011. }
  57012. }
  57013. if (bone._index !== -1) {
  57014. var mappedIndex = bone._index === undefined ? index : bone._index;
  57015. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  57016. }
  57017. }
  57018. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  57019. };
  57020. Skeleton.prototype.prepare = function () {
  57021. if (!this._isDirty) {
  57022. return;
  57023. }
  57024. if (this.needInitialSkinMatrix) {
  57025. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  57026. var mesh = this._meshesWithPoseMatrix[index];
  57027. var poseMatrix = mesh.getPoseMatrix();
  57028. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  57029. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57030. }
  57031. if (this._synchronizedWithMesh !== mesh) {
  57032. this._synchronizedWithMesh = mesh;
  57033. // Prepare bones
  57034. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  57035. var bone = this.bones[boneIndex];
  57036. if (!bone.getParent()) {
  57037. var matrix = bone.getBaseMatrix();
  57038. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  57039. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  57040. }
  57041. }
  57042. }
  57043. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  57044. }
  57045. }
  57046. else {
  57047. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  57048. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57049. }
  57050. this._computeTransformMatrices(this._transformMatrices, null);
  57051. }
  57052. this._isDirty = false;
  57053. this._scene._activeBones.addCount(this.bones.length, false);
  57054. };
  57055. Skeleton.prototype.getAnimatables = function () {
  57056. if (!this._animatables || this._animatables.length !== this.bones.length) {
  57057. this._animatables = [];
  57058. for (var index = 0; index < this.bones.length; index++) {
  57059. this._animatables.push(this.bones[index]);
  57060. }
  57061. }
  57062. return this._animatables;
  57063. };
  57064. Skeleton.prototype.clone = function (name, id) {
  57065. var result = new Skeleton(name, id || name, this._scene);
  57066. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57067. for (var index = 0; index < this.bones.length; index++) {
  57068. var source = this.bones[index];
  57069. var parentBone = null;
  57070. if (source.getParent()) {
  57071. var parentIndex = this.bones.indexOf(source.getParent());
  57072. parentBone = result.bones[parentIndex];
  57073. }
  57074. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  57075. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  57076. }
  57077. if (this._ranges) {
  57078. result._ranges = {};
  57079. for (var rangeName in this._ranges) {
  57080. result._ranges[rangeName] = this._ranges[rangeName].clone();
  57081. }
  57082. }
  57083. this._isDirty = true;
  57084. return result;
  57085. };
  57086. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  57087. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  57088. this.bones.forEach(function (bone) {
  57089. bone.animations.forEach(function (animation) {
  57090. animation.enableBlending = true;
  57091. animation.blendingSpeed = blendingSpeed;
  57092. });
  57093. });
  57094. };
  57095. Skeleton.prototype.dispose = function () {
  57096. this._meshesWithPoseMatrix = [];
  57097. // Animations
  57098. this.getScene().stopAnimation(this);
  57099. // Remove from scene
  57100. this.getScene().removeSkeleton(this);
  57101. };
  57102. Skeleton.prototype.serialize = function () {
  57103. var serializationObject = {};
  57104. serializationObject.name = this.name;
  57105. serializationObject.id = this.id;
  57106. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  57107. serializationObject.bones = [];
  57108. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57109. for (var index = 0; index < this.bones.length; index++) {
  57110. var bone = this.bones[index];
  57111. var serializedBone = {
  57112. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  57113. name: bone.name,
  57114. matrix: bone.getBaseMatrix().toArray(),
  57115. rest: bone.getRestPose().toArray()
  57116. };
  57117. serializationObject.bones.push(serializedBone);
  57118. if (bone.length) {
  57119. serializedBone.length = bone.length;
  57120. }
  57121. if (bone.animations && bone.animations.length > 0) {
  57122. serializedBone.animation = bone.animations[0].serialize();
  57123. }
  57124. serializationObject.ranges = [];
  57125. for (var name in this._ranges) {
  57126. var range = {};
  57127. range.name = name;
  57128. range.from = this._ranges[name].from;
  57129. range.to = this._ranges[name].to;
  57130. serializationObject.ranges.push(range);
  57131. }
  57132. }
  57133. return serializationObject;
  57134. };
  57135. Skeleton.Parse = function (parsedSkeleton, scene) {
  57136. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  57137. if (parsedSkeleton.dimensionsAtRest) {
  57138. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  57139. }
  57140. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  57141. var index;
  57142. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  57143. var parsedBone = parsedSkeleton.bones[index];
  57144. var parentBone = null;
  57145. if (parsedBone.parentBoneIndex > -1) {
  57146. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  57147. }
  57148. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  57149. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  57150. if (parsedBone.length) {
  57151. bone.length = parsedBone.length;
  57152. }
  57153. if (parsedBone.animation) {
  57154. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  57155. }
  57156. }
  57157. // placed after bones, so createAnimationRange can cascade down
  57158. if (parsedSkeleton.ranges) {
  57159. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  57160. var data = parsedSkeleton.ranges[index];
  57161. skeleton.createAnimationRange(data.name, data.from, data.to);
  57162. }
  57163. }
  57164. return skeleton;
  57165. };
  57166. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  57167. if (forceUpdate === void 0) { forceUpdate = false; }
  57168. var renderId = this._scene.getRenderId();
  57169. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  57170. this.bones[0].computeAbsoluteTransforms();
  57171. this._lastAbsoluteTransformsUpdateId = renderId;
  57172. }
  57173. };
  57174. Skeleton.prototype.getPoseMatrix = function () {
  57175. var poseMatrix;
  57176. if (this._meshesWithPoseMatrix.length > 0) {
  57177. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  57178. }
  57179. return poseMatrix;
  57180. };
  57181. Skeleton.prototype.sortBones = function () {
  57182. var bones = new Array();
  57183. var visited = new Array(this.bones.length);
  57184. for (var index = 0; index < this.bones.length; index++) {
  57185. this._sortBones(index, bones, visited);
  57186. }
  57187. this.bones = bones;
  57188. };
  57189. Skeleton.prototype._sortBones = function (index, bones, visited) {
  57190. if (visited[index]) {
  57191. return;
  57192. }
  57193. visited[index] = true;
  57194. var bone = this.bones[index];
  57195. if (bone._index === undefined) {
  57196. bone._index = index;
  57197. }
  57198. var parentBone = bone.getParent();
  57199. if (parentBone) {
  57200. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  57201. }
  57202. bones.push(bone);
  57203. };
  57204. return Skeleton;
  57205. }());
  57206. BABYLON.Skeleton = Skeleton;
  57207. })(BABYLON || (BABYLON = {}));
  57208. //# sourceMappingURL=babylon.skeleton.js.map
  57209. var BABYLON;
  57210. (function (BABYLON) {
  57211. var SphericalPolynomial = (function () {
  57212. function SphericalPolynomial() {
  57213. this.x = BABYLON.Vector3.Zero();
  57214. this.y = BABYLON.Vector3.Zero();
  57215. this.z = BABYLON.Vector3.Zero();
  57216. this.xx = BABYLON.Vector3.Zero();
  57217. this.yy = BABYLON.Vector3.Zero();
  57218. this.zz = BABYLON.Vector3.Zero();
  57219. this.xy = BABYLON.Vector3.Zero();
  57220. this.yz = BABYLON.Vector3.Zero();
  57221. this.zx = BABYLON.Vector3.Zero();
  57222. }
  57223. SphericalPolynomial.prototype.addAmbient = function (color) {
  57224. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57225. this.xx = this.xx.add(colorVector);
  57226. this.yy = this.yy.add(colorVector);
  57227. this.zz = this.zz.add(colorVector);
  57228. };
  57229. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  57230. var result = new SphericalPolynomial();
  57231. result.x = harmonics.L11.scale(1.02333);
  57232. result.y = harmonics.L1_1.scale(1.02333);
  57233. result.z = harmonics.L10.scale(1.02333);
  57234. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  57235. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  57236. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  57237. result.yz = harmonics.L2_1.scale(0.858086);
  57238. result.zx = harmonics.L21.scale(0.858086);
  57239. result.xy = harmonics.L2_2.scale(0.858086);
  57240. result.scale(1.0 / Math.PI);
  57241. return result;
  57242. };
  57243. SphericalPolynomial.prototype.scale = function (scale) {
  57244. this.x = this.x.scale(scale);
  57245. this.y = this.y.scale(scale);
  57246. this.z = this.z.scale(scale);
  57247. this.xx = this.xx.scale(scale);
  57248. this.yy = this.yy.scale(scale);
  57249. this.zz = this.zz.scale(scale);
  57250. this.yz = this.yz.scale(scale);
  57251. this.zx = this.zx.scale(scale);
  57252. this.xy = this.xy.scale(scale);
  57253. };
  57254. return SphericalPolynomial;
  57255. }());
  57256. BABYLON.SphericalPolynomial = SphericalPolynomial;
  57257. var SphericalHarmonics = (function () {
  57258. function SphericalHarmonics() {
  57259. this.L00 = BABYLON.Vector3.Zero();
  57260. this.L1_1 = BABYLON.Vector3.Zero();
  57261. this.L10 = BABYLON.Vector3.Zero();
  57262. this.L11 = BABYLON.Vector3.Zero();
  57263. this.L2_2 = BABYLON.Vector3.Zero();
  57264. this.L2_1 = BABYLON.Vector3.Zero();
  57265. this.L20 = BABYLON.Vector3.Zero();
  57266. this.L21 = BABYLON.Vector3.Zero();
  57267. this.L22 = BABYLON.Vector3.Zero();
  57268. }
  57269. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  57270. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57271. var c = colorVector.scale(deltaSolidAngle);
  57272. this.L00 = this.L00.add(c.scale(0.282095));
  57273. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  57274. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  57275. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  57276. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  57277. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  57278. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  57279. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  57280. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  57281. };
  57282. SphericalHarmonics.prototype.scale = function (scale) {
  57283. this.L00 = this.L00.scale(scale);
  57284. this.L1_1 = this.L1_1.scale(scale);
  57285. this.L10 = this.L10.scale(scale);
  57286. this.L11 = this.L11.scale(scale);
  57287. this.L2_2 = this.L2_2.scale(scale);
  57288. this.L2_1 = this.L2_1.scale(scale);
  57289. this.L20 = this.L20.scale(scale);
  57290. this.L21 = this.L21.scale(scale);
  57291. this.L22 = this.L22.scale(scale);
  57292. };
  57293. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  57294. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  57295. //
  57296. // E_lm = A_l * L_lm
  57297. //
  57298. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  57299. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  57300. // the scaling factors are given in equation 9.
  57301. // Constant (Band 0)
  57302. this.L00 = this.L00.scale(3.141593);
  57303. // Linear (Band 1)
  57304. this.L1_1 = this.L1_1.scale(2.094395);
  57305. this.L10 = this.L10.scale(2.094395);
  57306. this.L11 = this.L11.scale(2.094395);
  57307. // Quadratic (Band 2)
  57308. this.L2_2 = this.L2_2.scale(0.785398);
  57309. this.L2_1 = this.L2_1.scale(0.785398);
  57310. this.L20 = this.L20.scale(0.785398);
  57311. this.L21 = this.L21.scale(0.785398);
  57312. this.L22 = this.L22.scale(0.785398);
  57313. };
  57314. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  57315. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  57316. // L = (1/pi) * E * rho
  57317. //
  57318. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  57319. this.scale(1.0 / Math.PI);
  57320. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  57321. // (The pixel shader must apply albedo after texture fetches, etc).
  57322. };
  57323. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  57324. var result = new SphericalHarmonics();
  57325. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  57326. result.L1_1 = polynomial.y.scale(0.977204);
  57327. result.L10 = polynomial.z.scale(0.977204);
  57328. result.L11 = polynomial.x.scale(0.977204);
  57329. result.L2_2 = polynomial.xy.scale(1.16538);
  57330. result.L2_1 = polynomial.yz.scale(1.16538);
  57331. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  57332. result.L21 = polynomial.zx.scale(1.16538);
  57333. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  57334. result.scale(Math.PI);
  57335. return result;
  57336. };
  57337. return SphericalHarmonics;
  57338. }());
  57339. BABYLON.SphericalHarmonics = SphericalHarmonics;
  57340. })(BABYLON || (BABYLON = {}));
  57341. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  57342. var BABYLON;
  57343. (function (BABYLON) {
  57344. var Internals;
  57345. (function (Internals) {
  57346. var FileFaceOrientation = (function () {
  57347. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57348. this.name = name;
  57349. this.worldAxisForNormal = worldAxisForNormal;
  57350. this.worldAxisForFileX = worldAxisForFileX;
  57351. this.worldAxisForFileY = worldAxisForFileY;
  57352. }
  57353. return FileFaceOrientation;
  57354. }());
  57355. ;
  57356. /**
  57357. * Helper class dealing with the extraction of spherical polynomial dataArray
  57358. * from a cube map.
  57359. */
  57360. var CubeMapToSphericalPolynomialTools = (function () {
  57361. function CubeMapToSphericalPolynomialTools() {
  57362. }
  57363. /**
  57364. * Converts a texture to the according Spherical Polynomial data.
  57365. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57366. *
  57367. * @param texture The texture to extract the information from.
  57368. * @return The Spherical Polynomial data.
  57369. */
  57370. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  57371. if (!texture.isCube) {
  57372. // Only supports cube Textures currently.
  57373. return null;
  57374. }
  57375. var size = texture.getSize().width;
  57376. var right = texture.readPixels(0);
  57377. var left = texture.readPixels(1);
  57378. var up;
  57379. var down;
  57380. if (texture.isRenderTarget) {
  57381. up = texture.readPixels(3);
  57382. down = texture.readPixels(2);
  57383. }
  57384. else {
  57385. up = texture.readPixels(2);
  57386. down = texture.readPixels(3);
  57387. }
  57388. var front = texture.readPixels(4);
  57389. var back = texture.readPixels(5);
  57390. var gammaSpace = texture.gammaSpace;
  57391. // Always read as RGBA.
  57392. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  57393. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57394. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57395. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57396. }
  57397. var cubeInfo = {
  57398. size: size,
  57399. right: right,
  57400. left: left,
  57401. up: up,
  57402. down: down,
  57403. front: front,
  57404. back: back,
  57405. format: format,
  57406. type: type,
  57407. gammaSpace: gammaSpace,
  57408. };
  57409. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  57410. };
  57411. /**
  57412. * Converts a cubemap to the according Spherical Polynomial data.
  57413. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57414. *
  57415. * @param cubeInfo The Cube map to extract the information from.
  57416. * @return The Spherical Polynomial data.
  57417. */
  57418. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  57419. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  57420. var totalSolidAngle = 0.0;
  57421. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  57422. var du = 2.0 / cubeInfo.size;
  57423. var dv = du;
  57424. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  57425. var minUV = du * 0.5 - 1.0;
  57426. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57427. var fileFace = this.FileFaces[faceIndex];
  57428. var dataArray = cubeInfo[fileFace.name];
  57429. var v = minUV;
  57430. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  57431. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  57432. // Because SP is still linear, so summation is fine in that basis.
  57433. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  57434. for (var y = 0; y < cubeInfo.size; y++) {
  57435. var u = minUV;
  57436. for (var x = 0; x < cubeInfo.size; x++) {
  57437. // World direction (not normalised)
  57438. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  57439. worldDirection.normalize();
  57440. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  57441. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  57442. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  57443. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  57444. // Handle Integer types.
  57445. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57446. r /= 255;
  57447. g /= 255;
  57448. b /= 255;
  57449. }
  57450. // Handle Gamma space textures.
  57451. if (cubeInfo.gammaSpace) {
  57452. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  57453. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  57454. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  57455. }
  57456. var color = new BABYLON.Color3(r, g, b);
  57457. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57458. totalSolidAngle += deltaSolidAngle;
  57459. u += du;
  57460. }
  57461. v += dv;
  57462. }
  57463. }
  57464. // Solid angle for entire sphere is 4*pi
  57465. var sphereSolidAngle = 4.0 * Math.PI;
  57466. // Adjust the solid angle to allow for how many faces we processed.
  57467. var facesProcessed = 6.0;
  57468. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  57469. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  57470. // This is needed because the numerical integration over the cube uses a
  57471. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  57472. // and also to compensate for accumulative error due to float precision in the summation.
  57473. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  57474. sphericalHarmonics.scale(correctionFactor);
  57475. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  57476. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  57477. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  57478. };
  57479. CubeMapToSphericalPolynomialTools.FileFaces = [
  57480. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  57481. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  57482. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  57483. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  57484. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  57485. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  57486. ];
  57487. return CubeMapToSphericalPolynomialTools;
  57488. }());
  57489. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  57490. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57491. })(BABYLON || (BABYLON = {}));
  57492. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  57493. var BABYLON;
  57494. (function (BABYLON) {
  57495. var Internals;
  57496. (function (Internals) {
  57497. /**
  57498. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  57499. */
  57500. var PanoramaToCubeMapTools = (function () {
  57501. function PanoramaToCubeMapTools() {
  57502. }
  57503. /**
  57504. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  57505. *
  57506. * @param float32Array The source data.
  57507. * @param inputWidth The width of the input panorama.
  57508. * @param inputhHeight The height of the input panorama.
  57509. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57510. * @return The cubemap data
  57511. */
  57512. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57513. if (!float32Array) {
  57514. throw "ConvertPanoramaToCubemap: input cannot be null";
  57515. }
  57516. if (float32Array.length != inputWidth * inputHeight * 3) {
  57517. throw "ConvertPanoramaToCubemap: input size is wrong";
  57518. }
  57519. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57520. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57521. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57522. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57523. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57524. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57525. return {
  57526. front: textureFront,
  57527. back: textureBack,
  57528. left: textureLeft,
  57529. right: textureRight,
  57530. up: textureUp,
  57531. down: textureDown,
  57532. size: size,
  57533. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  57534. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  57535. gammaSpace: false,
  57536. };
  57537. };
  57538. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57539. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57540. var textureArray = new Float32Array(buffer);
  57541. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57542. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57543. var dy = 1 / texSize;
  57544. var fy = 0;
  57545. for (var y = 0; y < texSize; y++) {
  57546. var xv1 = faceData[0];
  57547. var xv2 = faceData[2];
  57548. for (var x = 0; x < texSize; x++) {
  57549. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57550. v.normalize();
  57551. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57552. // 3 channels per pixels
  57553. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57554. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57555. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57556. xv1 = xv1.add(rotDX1);
  57557. xv2 = xv2.add(rotDX2);
  57558. }
  57559. fy += dy;
  57560. }
  57561. return textureArray;
  57562. };
  57563. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57564. var theta = Math.atan2(vDir.z, vDir.x);
  57565. var phi = Math.acos(vDir.y);
  57566. while (theta < -Math.PI)
  57567. theta += 2 * Math.PI;
  57568. while (theta > Math.PI)
  57569. theta -= 2 * Math.PI;
  57570. var dx = theta / Math.PI;
  57571. var dy = phi / Math.PI;
  57572. // recenter.
  57573. dx = dx * 0.5 + 0.5;
  57574. var px = Math.round(dx * inputWidth);
  57575. if (px < 0)
  57576. px = 0;
  57577. else if (px >= inputWidth)
  57578. px = inputWidth - 1;
  57579. var py = Math.round(dy * inputHeight);
  57580. if (py < 0)
  57581. py = 0;
  57582. else if (py >= inputHeight)
  57583. py = inputHeight - 1;
  57584. var inputY = (inputHeight - py - 1);
  57585. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57586. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57587. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57588. return {
  57589. r: r,
  57590. g: g,
  57591. b: b
  57592. };
  57593. };
  57594. PanoramaToCubeMapTools.FACE_FRONT = [
  57595. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57596. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57597. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57598. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57599. ];
  57600. PanoramaToCubeMapTools.FACE_BACK = [
  57601. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57602. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57603. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57604. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57605. ];
  57606. PanoramaToCubeMapTools.FACE_RIGHT = [
  57607. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57608. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57609. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57610. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57611. ];
  57612. PanoramaToCubeMapTools.FACE_LEFT = [
  57613. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57614. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57615. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57616. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57617. ];
  57618. PanoramaToCubeMapTools.FACE_DOWN = [
  57619. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57620. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57621. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57622. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57623. ];
  57624. PanoramaToCubeMapTools.FACE_UP = [
  57625. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57626. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57627. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57628. new BABYLON.Vector3(1.0, -1.0, -1.0)
  57629. ];
  57630. return PanoramaToCubeMapTools;
  57631. }());
  57632. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  57633. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57634. })(BABYLON || (BABYLON = {}));
  57635. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  57636. var BABYLON;
  57637. (function (BABYLON) {
  57638. var Internals;
  57639. (function (Internals) {
  57640. ;
  57641. /**
  57642. * This groups tools to convert HDR texture to native colors array.
  57643. */
  57644. var HDRTools = (function () {
  57645. function HDRTools() {
  57646. }
  57647. HDRTools.Ldexp = function (mantissa, exponent) {
  57648. if (exponent > 1023) {
  57649. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57650. }
  57651. if (exponent < -1074) {
  57652. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57653. }
  57654. return mantissa * Math.pow(2, exponent);
  57655. };
  57656. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57657. if (exponent > 0) {
  57658. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57659. float32array[index + 0] = red * exponent;
  57660. float32array[index + 1] = green * exponent;
  57661. float32array[index + 2] = blue * exponent;
  57662. }
  57663. else {
  57664. float32array[index + 0] = 0;
  57665. float32array[index + 1] = 0;
  57666. float32array[index + 2] = 0;
  57667. }
  57668. };
  57669. HDRTools.readStringLine = function (uint8array, startIndex) {
  57670. var line = "";
  57671. var character = "";
  57672. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57673. character = String.fromCharCode(uint8array[i]);
  57674. if (character == "\n") {
  57675. break;
  57676. }
  57677. line += character;
  57678. }
  57679. return line;
  57680. };
  57681. /**
  57682. * Reads header information from an RGBE texture stored in a native array.
  57683. * More information on this format are available here:
  57684. * https://en.wikipedia.org/wiki/RGBE_image_format
  57685. *
  57686. * @param uint8array The binary file stored in native array.
  57687. * @return The header information.
  57688. */
  57689. HDRTools.RGBE_ReadHeader = function (uint8array) {
  57690. var height = 0;
  57691. var width = 0;
  57692. var line = this.readStringLine(uint8array, 0);
  57693. if (line[0] != '#' || line[1] != '?') {
  57694. throw "Bad HDR Format.";
  57695. }
  57696. var endOfHeader = false;
  57697. var findFormat = false;
  57698. var lineIndex = 0;
  57699. do {
  57700. lineIndex += (line.length + 1);
  57701. line = this.readStringLine(uint8array, lineIndex);
  57702. if (line == "FORMAT=32-bit_rle_rgbe") {
  57703. findFormat = true;
  57704. }
  57705. else if (line.length == 0) {
  57706. endOfHeader = true;
  57707. }
  57708. } while (!endOfHeader);
  57709. if (!findFormat) {
  57710. throw "HDR Bad header format, unsupported FORMAT";
  57711. }
  57712. lineIndex += (line.length + 1);
  57713. line = this.readStringLine(uint8array, lineIndex);
  57714. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  57715. var match = sizeRegexp.exec(line);
  57716. // TODO. Support +Y and -X if needed.
  57717. if (match.length < 3) {
  57718. throw "HDR Bad header format, no size";
  57719. }
  57720. width = parseInt(match[2]);
  57721. height = parseInt(match[1]);
  57722. if (width < 8 || width > 0x7fff) {
  57723. throw "HDR Bad header format, unsupported size";
  57724. }
  57725. lineIndex += (line.length + 1);
  57726. return {
  57727. height: height,
  57728. width: width,
  57729. dataPosition: lineIndex
  57730. };
  57731. };
  57732. /**
  57733. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  57734. * This RGBE texture needs to store the information as a panorama.
  57735. *
  57736. * More information on this format are available here:
  57737. * https://en.wikipedia.org/wiki/RGBE_image_format
  57738. *
  57739. * @param buffer The binary file stored in an array buffer.
  57740. * @param size The expected size of the extracted cubemap.
  57741. * @return The Cube Map information.
  57742. */
  57743. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  57744. var uint8array = new Uint8Array(buffer);
  57745. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  57746. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57747. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  57748. return cubeMapData;
  57749. };
  57750. /**
  57751. * Returns the pixels data extracted from an RGBE texture.
  57752. * This pixels will be stored left to right up to down in the R G B order in one array.
  57753. *
  57754. * More information on this format are available here:
  57755. * https://en.wikipedia.org/wiki/RGBE_image_format
  57756. *
  57757. * @param uint8array The binary file stored in an array buffer.
  57758. * @param hdrInfo The header information of the file.
  57759. * @return The pixels data in RGB right to left up to down order.
  57760. */
  57761. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  57762. // Keep for multi format supports.
  57763. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57764. };
  57765. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  57766. var num_scanlines = hdrInfo.height;
  57767. var scanline_width = hdrInfo.width;
  57768. var a, b, c, d, count;
  57769. var dataIndex = hdrInfo.dataPosition;
  57770. var index = 0, endIndex = 0, i = 0;
  57771. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  57772. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  57773. // 3 channels of 4 bytes per pixel in float.
  57774. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  57775. var resultArray = new Float32Array(resultBuffer);
  57776. // read in each successive scanline
  57777. while (num_scanlines > 0) {
  57778. a = uint8array[dataIndex++];
  57779. b = uint8array[dataIndex++];
  57780. c = uint8array[dataIndex++];
  57781. d = uint8array[dataIndex++];
  57782. if (a != 2 || b != 2 || (c & 0x80)) {
  57783. // this file is not run length encoded
  57784. throw "HDR Bad header format, not RLE";
  57785. }
  57786. if (((c << 8) | d) != scanline_width) {
  57787. throw "HDR Bad header format, wrong scan line width";
  57788. }
  57789. index = 0;
  57790. // read each of the four channels for the scanline into the buffer
  57791. for (i = 0; i < 4; i++) {
  57792. endIndex = (i + 1) * scanline_width;
  57793. while (index < endIndex) {
  57794. a = uint8array[dataIndex++];
  57795. b = uint8array[dataIndex++];
  57796. if (a > 128) {
  57797. // a run of the same value
  57798. count = a - 128;
  57799. if ((count == 0) || (count > endIndex - index)) {
  57800. throw "HDR Bad Format, bad scanline data (run)";
  57801. }
  57802. while (count-- > 0) {
  57803. scanLineArray[index++] = b;
  57804. }
  57805. }
  57806. else {
  57807. // a non-run
  57808. count = a;
  57809. if ((count == 0) || (count > endIndex - index)) {
  57810. throw "HDR Bad Format, bad scanline data (non-run)";
  57811. }
  57812. scanLineArray[index++] = b;
  57813. if (--count > 0) {
  57814. for (var j = 0; j < count; j++) {
  57815. scanLineArray[index++] = uint8array[dataIndex++];
  57816. }
  57817. }
  57818. }
  57819. }
  57820. }
  57821. // now convert data from buffer into floats
  57822. for (i = 0; i < scanline_width; i++) {
  57823. a = scanLineArray[i];
  57824. b = scanLineArray[i + scanline_width];
  57825. c = scanLineArray[i + 2 * scanline_width];
  57826. d = scanLineArray[i + 3 * scanline_width];
  57827. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57828. }
  57829. num_scanlines--;
  57830. }
  57831. return resultArray;
  57832. };
  57833. return HDRTools;
  57834. }());
  57835. Internals.HDRTools = HDRTools;
  57836. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57837. })(BABYLON || (BABYLON = {}));
  57838. //# sourceMappingURL=babylon.hdr.js.map
  57839. var BABYLON;
  57840. (function (BABYLON) {
  57841. /**
  57842. * This represents a texture coming from an HDR input.
  57843. *
  57844. * The only supported format is currently panorama picture stored in RGBE format.
  57845. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57846. */
  57847. var HDRCubeTexture = (function (_super) {
  57848. __extends(HDRCubeTexture, _super);
  57849. /**
  57850. * Instantiates an HDRTexture from the following parameters.
  57851. *
  57852. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57853. * @param scene The scene the texture will be used in
  57854. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  57855. * @param noMipmap Forces to not generate the mipmap if true
  57856. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57857. * @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)
  57858. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57859. */
  57860. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  57861. if (noMipmap === void 0) { noMipmap = false; }
  57862. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57863. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57864. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57865. if (onLoad === void 0) { onLoad = null; }
  57866. if (onError === void 0) { onError = null; }
  57867. var _this = _super.call(this, scene) || this;
  57868. _this._useInGammaSpace = false;
  57869. _this._generateHarmonics = true;
  57870. _this._isBABYLONPreprocessed = false;
  57871. _this._onLoad = null;
  57872. _this._onError = null;
  57873. /**
  57874. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57875. */
  57876. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57877. /**
  57878. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57879. * This is usefull at run time to apply the good shader.
  57880. */
  57881. _this.isPMREM = false;
  57882. _this._isBlocking = true;
  57883. if (!url) {
  57884. return _this;
  57885. }
  57886. _this.name = url;
  57887. _this.url = url;
  57888. _this.hasAlpha = false;
  57889. _this.isCube = true;
  57890. _this._textureMatrix = BABYLON.Matrix.Identity();
  57891. _this._onLoad = onLoad;
  57892. _this._onError = onError;
  57893. _this.gammaSpace = false;
  57894. if (size) {
  57895. _this._isBABYLONPreprocessed = false;
  57896. _this._noMipmap = noMipmap;
  57897. _this._size = size;
  57898. _this._useInGammaSpace = useInGammaSpace;
  57899. _this._usePMREMGenerator = usePMREMGenerator &&
  57900. scene.getEngine().getCaps().textureLOD &&
  57901. _this.getScene().getEngine().getCaps().textureFloat &&
  57902. !_this._useInGammaSpace;
  57903. }
  57904. else {
  57905. _this._isBABYLONPreprocessed = true;
  57906. _this._noMipmap = false;
  57907. _this._useInGammaSpace = false;
  57908. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57909. _this.getScene().getEngine().getCaps().textureFloat &&
  57910. !_this._useInGammaSpace;
  57911. }
  57912. _this.isPMREM = _this._usePMREMGenerator;
  57913. _this._texture = _this._getFromCache(url, _this._noMipmap);
  57914. if (!_this._texture) {
  57915. if (!scene.useDelayedTextureLoading) {
  57916. _this.loadTexture();
  57917. }
  57918. else {
  57919. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57920. }
  57921. }
  57922. return _this;
  57923. }
  57924. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  57925. /**
  57926. * Gets wether or not the texture is blocking during loading.
  57927. */
  57928. get: function () {
  57929. return this._isBlocking;
  57930. },
  57931. /**
  57932. * Sets wether or not the texture is blocking during loading.
  57933. */
  57934. set: function (value) {
  57935. this._isBlocking = value;
  57936. },
  57937. enumerable: true,
  57938. configurable: true
  57939. });
  57940. /**
  57941. * Occurs when the file is a preprocessed .babylon.hdr file.
  57942. */
  57943. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57944. var _this = this;
  57945. var mipLevels = 0;
  57946. var floatArrayView = null;
  57947. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57948. var mips = [];
  57949. var startIndex = 30;
  57950. for (var level = 0; level < mipLevels; level++) {
  57951. mips.push([]);
  57952. // Fill each pixel of the mip level.
  57953. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57954. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57955. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57956. mips[level].push(faceData);
  57957. startIndex += faceSize;
  57958. }
  57959. }
  57960. return mips;
  57961. } : null;
  57962. var callback = function (buffer) {
  57963. // Create Native Array Views
  57964. var intArrayView = new Int32Array(buffer);
  57965. floatArrayView = new Float32Array(buffer);
  57966. // Fill header.
  57967. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57968. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57969. // Update Texture Information.
  57970. _this._texture.updateSize(_this._size, _this._size);
  57971. // Fill polynomial information.
  57972. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57973. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57974. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57975. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57976. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57977. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57978. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57979. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57980. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57981. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57982. _this.sphericalPolynomial = sphericalPolynomial;
  57983. // Fill pixel data.
  57984. mipLevels = intArrayView[29]; // Number of mip levels.
  57985. var startIndex = 30;
  57986. var data = [];
  57987. var faceSize = Math.pow(_this._size, 2) * 3;
  57988. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57989. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57990. startIndex += faceSize;
  57991. }
  57992. var results = [];
  57993. var byteArray = null;
  57994. // Push each faces.
  57995. for (var k = 0; k < 6; k++) {
  57996. var dataFace = null;
  57997. // To be deprecated.
  57998. if (version === 1) {
  57999. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  58000. dataFace = data[j];
  58001. }
  58002. // If special cases.
  58003. if (!mipmapGenerator) {
  58004. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58005. // 3 channels of 1 bytes per pixel in bytes.
  58006. var byteBuffer = new ArrayBuffer(faceSize);
  58007. byteArray = new Uint8Array(byteBuffer);
  58008. }
  58009. for (var i = 0; i < _this._size * _this._size; i++) {
  58010. // Put in gamma space if requested.
  58011. if (_this._useInGammaSpace) {
  58012. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58013. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58014. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58015. }
  58016. // Convert to int texture for fallback.
  58017. if (byteArray) {
  58018. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58019. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58020. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58021. // May use luminance instead if the result is not accurate.
  58022. var max = Math.max(Math.max(r, g), b);
  58023. if (max > 255) {
  58024. var scale = 255 / max;
  58025. r *= scale;
  58026. g *= scale;
  58027. b *= scale;
  58028. }
  58029. byteArray[(i * 3) + 0] = r;
  58030. byteArray[(i * 3) + 1] = g;
  58031. byteArray[(i * 3) + 2] = b;
  58032. }
  58033. }
  58034. }
  58035. // Fill the array accordingly.
  58036. if (byteArray) {
  58037. results.push(byteArray);
  58038. }
  58039. else {
  58040. results.push(dataFace);
  58041. }
  58042. }
  58043. return results;
  58044. };
  58045. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  58046. };
  58047. /**
  58048. * Occurs when the file is raw .hdr file.
  58049. */
  58050. HDRCubeTexture.prototype.loadHDRTexture = function () {
  58051. var _this = this;
  58052. var callback = function (buffer) {
  58053. // Extract the raw linear data.
  58054. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  58055. // Generate harmonics if needed.
  58056. if (_this._generateHarmonics) {
  58057. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  58058. _this.sphericalPolynomial = sphericalPolynomial;
  58059. }
  58060. var results = [];
  58061. var byteArray = null;
  58062. // Push each faces.
  58063. for (var j = 0; j < 6; j++) {
  58064. // Create uintarray fallback.
  58065. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58066. // 3 channels of 1 bytes per pixel in bytes.
  58067. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  58068. byteArray = new Uint8Array(byteBuffer);
  58069. }
  58070. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  58071. // If special cases.
  58072. if (_this._useInGammaSpace || byteArray) {
  58073. for (var i = 0; i < _this._size * _this._size; i++) {
  58074. // Put in gamma space if requested.
  58075. if (_this._useInGammaSpace) {
  58076. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58077. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58078. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58079. }
  58080. // Convert to int texture for fallback.
  58081. if (byteArray) {
  58082. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58083. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58084. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58085. // May use luminance instead if the result is not accurate.
  58086. var max = Math.max(Math.max(r, g), b);
  58087. if (max > 255) {
  58088. var scale = 255 / max;
  58089. r *= scale;
  58090. g *= scale;
  58091. b *= scale;
  58092. }
  58093. byteArray[(i * 3) + 0] = r;
  58094. byteArray[(i * 3) + 1] = g;
  58095. byteArray[(i * 3) + 2] = b;
  58096. }
  58097. }
  58098. }
  58099. if (byteArray) {
  58100. results.push(byteArray);
  58101. }
  58102. else {
  58103. results.push(dataFace);
  58104. }
  58105. }
  58106. return results;
  58107. };
  58108. var mipmapGenerator = null;
  58109. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  58110. // if (!this._noMipmap &&
  58111. // this._usePMREMGenerator) {
  58112. // mipmapGenerator = (data: ArrayBufferView[]) => {
  58113. // // Custom setup of the generator matching with the PBR shader values.
  58114. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  58115. // this._size,
  58116. // this._size,
  58117. // 0,
  58118. // 3,
  58119. // this.getScene().getEngine().getCaps().textureFloat,
  58120. // 2048,
  58121. // 0.25,
  58122. // false,
  58123. // true);
  58124. // return generator.filterCubeMap();
  58125. // };
  58126. // }
  58127. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  58128. };
  58129. /**
  58130. * Starts the loading process of the texture.
  58131. */
  58132. HDRCubeTexture.prototype.loadTexture = function () {
  58133. if (this._isBABYLONPreprocessed) {
  58134. this.loadBabylonTexture();
  58135. }
  58136. else {
  58137. this.loadHDRTexture();
  58138. }
  58139. };
  58140. HDRCubeTexture.prototype.clone = function () {
  58141. var size = this._isBABYLONPreprocessed ? null : this._size;
  58142. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  58143. // Base texture
  58144. newTexture.level = this.level;
  58145. newTexture.wrapU = this.wrapU;
  58146. newTexture.wrapV = this.wrapV;
  58147. newTexture.coordinatesIndex = this.coordinatesIndex;
  58148. newTexture.coordinatesMode = this.coordinatesMode;
  58149. return newTexture;
  58150. };
  58151. // Methods
  58152. HDRCubeTexture.prototype.delayLoad = function () {
  58153. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58154. return;
  58155. }
  58156. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58157. this._texture = this._getFromCache(this.url, this._noMipmap);
  58158. if (!this._texture) {
  58159. this.loadTexture();
  58160. }
  58161. };
  58162. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  58163. return this._textureMatrix;
  58164. };
  58165. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58166. this._textureMatrix = value;
  58167. };
  58168. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58169. var texture = null;
  58170. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58171. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  58172. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  58173. texture.name = parsedTexture.name;
  58174. texture.hasAlpha = parsedTexture.hasAlpha;
  58175. texture.level = parsedTexture.level;
  58176. texture.coordinatesMode = parsedTexture.coordinatesMode;
  58177. texture.isBlocking = parsedTexture.isBlocking;
  58178. }
  58179. return texture;
  58180. };
  58181. HDRCubeTexture.prototype.serialize = function () {
  58182. if (!this.name) {
  58183. return null;
  58184. }
  58185. var serializationObject = {};
  58186. serializationObject.name = this.name;
  58187. serializationObject.hasAlpha = this.hasAlpha;
  58188. serializationObject.isCube = true;
  58189. serializationObject.level = this.level;
  58190. serializationObject.size = this._size;
  58191. serializationObject.coordinatesMode = this.coordinatesMode;
  58192. serializationObject.useInGammaSpace = this._useInGammaSpace;
  58193. serializationObject.generateHarmonics = this._generateHarmonics;
  58194. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  58195. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  58196. serializationObject.customType = "BABYLON.HDRCubeTexture";
  58197. serializationObject.noMipmap = this._noMipmap;
  58198. serializationObject.isBlocking = this._isBlocking;
  58199. return serializationObject;
  58200. };
  58201. /**
  58202. * Saves as a file the data contained in the texture in a binary format.
  58203. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58204. * as the spherical used in the lighting.
  58205. * @param url The HDR file url.
  58206. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58207. * @param onError Method called if any error happens during download.
  58208. * @return The packed binary data.
  58209. */
  58210. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  58211. if (onError === void 0) { onError = null; }
  58212. var callback = function (buffer) {
  58213. var data = new Blob([buffer], { type: 'application/octet-stream' });
  58214. // Returns a URL you can use as a href.
  58215. var objUrl = window.URL.createObjectURL(data);
  58216. // Simulates a link to it and click to dowload.
  58217. var a = document.createElement("a");
  58218. document.body.appendChild(a);
  58219. a.style.display = "none";
  58220. a.href = objUrl;
  58221. a.download = "envmap.babylon.hdr";
  58222. a.click();
  58223. };
  58224. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  58225. };
  58226. /**
  58227. * Serializes the data contained in the texture in a binary format.
  58228. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58229. * as the spherical used in the lighting.
  58230. * @param url The HDR file url.
  58231. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58232. * @param onError Method called if any error happens during download.
  58233. * @return The packed binary data.
  58234. */
  58235. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  58236. if (onError === void 0) { onError = null; }
  58237. // Needs the url tho create the texture.
  58238. if (!url) {
  58239. return null;
  58240. }
  58241. // Check Power of two size.
  58242. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  58243. return null;
  58244. }
  58245. // Coming Back in 3.1.
  58246. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  58247. return null;
  58248. };
  58249. HDRCubeTexture._facesMapping = [
  58250. "right",
  58251. "left",
  58252. "up",
  58253. "down",
  58254. "front",
  58255. "back"
  58256. ];
  58257. return HDRCubeTexture;
  58258. }(BABYLON.BaseTexture));
  58259. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58260. })(BABYLON || (BABYLON = {}));
  58261. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  58262. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  58263. // Huge respect for a such great lib.
  58264. // Earcut license:
  58265. // Copyright (c) 2016, Mapbox
  58266. //
  58267. // Permission to use, copy, modify, and/or distribute this software for any purpose
  58268. // with or without fee is hereby granted, provided that the above copyright notice
  58269. // and this permission notice appear in all copies.
  58270. //
  58271. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  58272. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  58273. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  58274. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  58275. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  58276. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  58277. // THIS SOFTWARE.
  58278. var Earcut;
  58279. (function (Earcut) {
  58280. /**
  58281. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  58282. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  58283. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  58284. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  58285. */
  58286. function earcut(data, holeIndices, dim) {
  58287. dim = dim || 2;
  58288. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  58289. if (!outerNode)
  58290. return triangles;
  58291. var minX, minY, maxX, maxY, x, y, size;
  58292. if (hasHoles)
  58293. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  58294. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  58295. if (data.length > 80 * dim) {
  58296. minX = maxX = data[0];
  58297. minY = maxY = data[1];
  58298. for (var i = dim; i < outerLen; i += dim) {
  58299. x = data[i];
  58300. y = data[i + 1];
  58301. if (x < minX)
  58302. minX = x;
  58303. if (y < minY)
  58304. minY = y;
  58305. if (x > maxX)
  58306. maxX = x;
  58307. if (y > maxY)
  58308. maxY = y;
  58309. }
  58310. // minX, minY and size are later used to transform coords into integers for z-order calculation
  58311. size = Math.max(maxX - minX, maxY - minY);
  58312. }
  58313. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  58314. return triangles;
  58315. }
  58316. Earcut.earcut = earcut;
  58317. // create a circular doubly linked list from polygon points in the specified winding order
  58318. function linkedList(data, start, end, dim, clockwise) {
  58319. var i, last;
  58320. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  58321. for (i = start; i < end; i += dim)
  58322. last = insertNode(i, data[i], data[i + 1], last);
  58323. }
  58324. else {
  58325. for (i = end - dim; i >= start; i -= dim)
  58326. last = insertNode(i, data[i], data[i + 1], last);
  58327. }
  58328. if (last && equals(last, last.next)) {
  58329. removeNode(last);
  58330. last = last.next;
  58331. }
  58332. return last;
  58333. }
  58334. // eliminate colinear or duplicate points
  58335. function filterPoints(start, end) {
  58336. if (!start)
  58337. return start;
  58338. if (!end)
  58339. end = start;
  58340. var p = start, again;
  58341. do {
  58342. again = false;
  58343. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  58344. removeNode(p);
  58345. p = end = p.prev;
  58346. if (p === p.next)
  58347. return null;
  58348. again = true;
  58349. }
  58350. else {
  58351. p = p.next;
  58352. }
  58353. } while (again || p !== end);
  58354. return end;
  58355. }
  58356. // main ear slicing loop which triangulates a polygon (given as a linked list)
  58357. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  58358. if (!ear)
  58359. return;
  58360. // interlink polygon nodes in z-order
  58361. if (!pass && size)
  58362. indexCurve(ear, minX, minY, size);
  58363. var stop = ear, prev, next;
  58364. // iterate through ears, slicing them one by one
  58365. while (ear.prev !== ear.next) {
  58366. prev = ear.prev;
  58367. next = ear.next;
  58368. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  58369. // cut off the triangle
  58370. triangles.push(prev.i / dim);
  58371. triangles.push(ear.i / dim);
  58372. triangles.push(next.i / dim);
  58373. removeNode(ear);
  58374. // skipping the next vertice leads to less sliver triangles
  58375. ear = next.next;
  58376. stop = next.next;
  58377. continue;
  58378. }
  58379. ear = next;
  58380. // if we looped through the whole remaining polygon and can't find any more ears
  58381. if (ear === stop) {
  58382. // try filtering points and slicing again
  58383. if (!pass) {
  58384. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  58385. // if this didn't work, try curing all small self-intersections locally
  58386. }
  58387. else if (pass === 1) {
  58388. ear = cureLocalIntersections(ear, triangles, dim);
  58389. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  58390. // as a last resort, try splitting the remaining polygon into two
  58391. }
  58392. else if (pass === 2) {
  58393. splitEarcut(ear, triangles, dim, minX, minY, size);
  58394. }
  58395. break;
  58396. }
  58397. }
  58398. }
  58399. // check whether a polygon node forms a valid ear with adjacent nodes
  58400. function isEar(ear) {
  58401. var a = ear.prev, b = ear, c = ear.next;
  58402. if (area(a, b, c) >= 0)
  58403. return false; // reflex, can't be an ear
  58404. // now make sure we don't have other points inside the potential ear
  58405. var p = ear.next.next;
  58406. while (p !== ear.prev) {
  58407. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58408. area(p.prev, p, p.next) >= 0)
  58409. return false;
  58410. p = p.next;
  58411. }
  58412. return true;
  58413. }
  58414. function isEarHashed(ear, minX, minY, size) {
  58415. var a = ear.prev, b = ear, c = ear.next;
  58416. if (area(a, b, c) >= 0)
  58417. return false; // reflex, can't be an ear
  58418. // triangle bbox; min & max are calculated like this for speed
  58419. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  58420. // z-order range for the current triangle bbox;
  58421. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  58422. // first look for points inside the triangle in increasing z-order
  58423. var p = ear.nextZ;
  58424. while (p && p.z <= maxZ) {
  58425. if (p !== ear.prev &&
  58426. p !== ear.next &&
  58427. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58428. area(p.prev, p, p.next) >= 0)
  58429. return false;
  58430. p = p.nextZ;
  58431. }
  58432. // then look for points in decreasing z-order
  58433. p = ear.prevZ;
  58434. while (p && p.z >= minZ) {
  58435. if (p !== ear.prev &&
  58436. p !== ear.next &&
  58437. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58438. area(p.prev, p, p.next) >= 0)
  58439. return false;
  58440. p = p.prevZ;
  58441. }
  58442. return true;
  58443. }
  58444. // go through all polygon nodes and cure small local self-intersections
  58445. function cureLocalIntersections(start, triangles, dim) {
  58446. var p = start;
  58447. do {
  58448. var a = p.prev, b = p.next.next;
  58449. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  58450. triangles.push(a.i / dim);
  58451. triangles.push(p.i / dim);
  58452. triangles.push(b.i / dim);
  58453. // remove two nodes involved
  58454. removeNode(p);
  58455. removeNode(p.next);
  58456. p = start = b;
  58457. }
  58458. p = p.next;
  58459. } while (p !== start);
  58460. return p;
  58461. }
  58462. // try splitting polygon into two and triangulate them independently
  58463. function splitEarcut(start, triangles, dim, minX, minY, size) {
  58464. // look for a valid diagonal that divides the polygon into two
  58465. var a = start;
  58466. do {
  58467. var b = a.next.next;
  58468. while (b !== a.prev) {
  58469. if (a.i !== b.i && isValidDiagonal(a, b)) {
  58470. // split the polygon in two by the diagonal
  58471. var c = splitPolygon(a, b);
  58472. // filter colinear points around the cuts
  58473. a = filterPoints(a, a.next);
  58474. c = filterPoints(c, c.next);
  58475. // run earcut on each half
  58476. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  58477. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  58478. return;
  58479. }
  58480. b = b.next;
  58481. }
  58482. a = a.next;
  58483. } while (a !== start);
  58484. }
  58485. // link every hole into the outer loop, producing a single-ring polygon without holes
  58486. function eliminateHoles(data, holeIndices, outerNode, dim) {
  58487. var queue = [], i, len, start, end, list;
  58488. for (i = 0, len = holeIndices.length; i < len; i++) {
  58489. start = holeIndices[i] * dim;
  58490. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  58491. list = linkedList(data, start, end, dim, false);
  58492. if (list === list.next)
  58493. list.steiner = true;
  58494. queue.push(getLeftmost(list));
  58495. }
  58496. queue.sort(compareX);
  58497. // process holes from left to right
  58498. for (i = 0; i < queue.length; i++) {
  58499. eliminateHole(queue[i], outerNode);
  58500. outerNode = filterPoints(outerNode, outerNode.next);
  58501. }
  58502. return outerNode;
  58503. }
  58504. function compareX(a, b) {
  58505. return a.x - b.x;
  58506. }
  58507. // find a bridge between vertices that connects hole with an outer ring and and link it
  58508. function eliminateHole(hole, outerNode) {
  58509. outerNode = findHoleBridge(hole, outerNode);
  58510. if (outerNode) {
  58511. var b = splitPolygon(outerNode, hole);
  58512. filterPoints(b, b.next);
  58513. }
  58514. }
  58515. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  58516. function findHoleBridge(hole, outerNode) {
  58517. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  58518. // find a segment intersected by a ray from the hole's leftmost point to the left;
  58519. // segment's endpoint with lesser x will be potential connection point
  58520. do {
  58521. if (hy <= p.y && hy >= p.next.y) {
  58522. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  58523. if (x <= hx && x > qx) {
  58524. qx = x;
  58525. if (x === hx) {
  58526. if (hy === p.y)
  58527. return p;
  58528. if (hy === p.next.y)
  58529. return p.next;
  58530. }
  58531. m = p.x < p.next.x ? p : p.next;
  58532. }
  58533. }
  58534. p = p.next;
  58535. } while (p !== outerNode);
  58536. if (!m)
  58537. return null;
  58538. if (hx === qx)
  58539. return m.prev; // hole touches outer segment; pick lower endpoint
  58540. // look for points inside the triangle of hole point, segment intersection and endpoint;
  58541. // if there are no points found, we have a valid connection;
  58542. // otherwise choose the point of the minimum angle with the ray as connection point
  58543. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  58544. p = m.next;
  58545. while (p !== stop) {
  58546. if (hx >= p.x &&
  58547. p.x >= mx &&
  58548. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  58549. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  58550. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  58551. m = p;
  58552. tanMin = tan;
  58553. }
  58554. }
  58555. p = p.next;
  58556. }
  58557. return m;
  58558. }
  58559. // interlink polygon nodes in z-order
  58560. function indexCurve(start, minX, minY, size) {
  58561. var p = start;
  58562. do {
  58563. if (p.z === null)
  58564. p.z = zOrder(p.x, p.y, minX, minY, size);
  58565. p.prevZ = p.prev;
  58566. p.nextZ = p.next;
  58567. p = p.next;
  58568. } while (p !== start);
  58569. p.prevZ.nextZ = null;
  58570. p.prevZ = null;
  58571. sortLinked(p);
  58572. }
  58573. // Simon Tatham's linked list merge sort algorithm
  58574. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  58575. function sortLinked(list) {
  58576. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  58577. do {
  58578. p = list;
  58579. list = null;
  58580. tail = null;
  58581. numMerges = 0;
  58582. while (p) {
  58583. numMerges++;
  58584. q = p;
  58585. pSize = 0;
  58586. for (i = 0; i < inSize; i++) {
  58587. pSize++;
  58588. q = q.nextZ;
  58589. if (!q)
  58590. break;
  58591. }
  58592. qSize = inSize;
  58593. while (pSize > 0 || (qSize > 0 && q)) {
  58594. if (pSize === 0) {
  58595. e = q;
  58596. q = q.nextZ;
  58597. qSize--;
  58598. }
  58599. else if (qSize === 0 || !q) {
  58600. e = p;
  58601. p = p.nextZ;
  58602. pSize--;
  58603. }
  58604. else if (p.z <= q.z) {
  58605. e = p;
  58606. p = p.nextZ;
  58607. pSize--;
  58608. }
  58609. else {
  58610. e = q;
  58611. q = q.nextZ;
  58612. qSize--;
  58613. }
  58614. if (tail)
  58615. tail.nextZ = e;
  58616. else
  58617. list = e;
  58618. e.prevZ = tail;
  58619. tail = e;
  58620. }
  58621. p = q;
  58622. }
  58623. tail.nextZ = null;
  58624. inSize *= 2;
  58625. } while (numMerges > 1);
  58626. return list;
  58627. }
  58628. // z-order of a point given coords and size of the data bounding box
  58629. function zOrder(x, y, minX, minY, size) {
  58630. // coords are transformed into non-negative 15-bit integer range
  58631. x = 32767 * (x - minX) / size;
  58632. y = 32767 * (y - minY) / size;
  58633. x = (x | (x << 8)) & 0x00FF00FF;
  58634. x = (x | (x << 4)) & 0x0F0F0F0F;
  58635. x = (x | (x << 2)) & 0x33333333;
  58636. x = (x | (x << 1)) & 0x55555555;
  58637. y = (y | (y << 8)) & 0x00FF00FF;
  58638. y = (y | (y << 4)) & 0x0F0F0F0F;
  58639. y = (y | (y << 2)) & 0x33333333;
  58640. y = (y | (y << 1)) & 0x55555555;
  58641. return x | (y << 1);
  58642. }
  58643. // find the leftmost node of a polygon ring
  58644. function getLeftmost(start) {
  58645. var p = start, leftmost = start;
  58646. do {
  58647. if (p.x < leftmost.x)
  58648. leftmost = p;
  58649. p = p.next;
  58650. } while (p !== start);
  58651. return leftmost;
  58652. }
  58653. // check if a point lies within a convex triangle
  58654. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  58655. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  58656. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  58657. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  58658. }
  58659. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  58660. function isValidDiagonal(a, b) {
  58661. return a.next.i !== b.i &&
  58662. a.prev.i !== b.i &&
  58663. !intersectsPolygon(a, b) &&
  58664. locallyInside(a, b) &&
  58665. locallyInside(b, a) &&
  58666. middleInside(a, b);
  58667. }
  58668. // signed area of a triangle
  58669. function area(p, q, r) {
  58670. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  58671. }
  58672. // check if two points are equal
  58673. function equals(p1, p2) {
  58674. return p1.x === p2.x && p1.y === p2.y;
  58675. }
  58676. // check if two segments intersect
  58677. function intersects(p1, q1, p2, q2) {
  58678. if ((equals(p1, q1) && equals(p2, q2)) ||
  58679. (equals(p1, q2) && equals(p2, q1)))
  58680. return true;
  58681. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  58682. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  58683. }
  58684. // check if a polygon diagonal intersects any polygon segments
  58685. function intersectsPolygon(a, b) {
  58686. var p = a;
  58687. do {
  58688. if (p.i !== a.i &&
  58689. p.next.i !== a.i &&
  58690. p.i !== b.i &&
  58691. p.next.i !== b.i &&
  58692. intersects(p, p.next, a, b))
  58693. return true;
  58694. p = p.next;
  58695. } while (p !== a);
  58696. return false;
  58697. }
  58698. // check if a polygon diagonal is locally inside the polygon
  58699. function locallyInside(a, b) {
  58700. return area(a.prev, a, a.next) < 0
  58701. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  58702. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  58703. }
  58704. // check if the middle point of a polygon diagonal is inside the polygon
  58705. function middleInside(a, b) {
  58706. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  58707. do {
  58708. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  58709. inside = !inside;
  58710. p = p.next;
  58711. } while (p !== a);
  58712. return inside;
  58713. }
  58714. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  58715. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  58716. function splitPolygon(a, b) {
  58717. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  58718. a.next = b;
  58719. b.prev = a;
  58720. a2.next = an;
  58721. an.prev = a2;
  58722. b2.next = a2;
  58723. a2.prev = b2;
  58724. bp.next = b2;
  58725. b2.prev = bp;
  58726. return b2;
  58727. }
  58728. // create a node and optionally link it with previous one (in a circular doubly linked list)
  58729. function insertNode(i, x, y, last) {
  58730. var p = new Node(i, x, y);
  58731. if (!last) {
  58732. p.prev = p;
  58733. p.next = p;
  58734. }
  58735. else {
  58736. p.next = last.next;
  58737. p.prev = last;
  58738. last.next.prev = p;
  58739. last.next = p;
  58740. }
  58741. return p;
  58742. }
  58743. function removeNode(p) {
  58744. p.next.prev = p.prev;
  58745. p.prev.next = p.next;
  58746. if (p.prevZ)
  58747. p.prevZ.nextZ = p.nextZ;
  58748. if (p.nextZ)
  58749. p.nextZ.prevZ = p.prevZ;
  58750. }
  58751. function Node(i, x, y) {
  58752. // vertice index in coordinates array
  58753. this.i = i;
  58754. // vertex coordinates
  58755. this.x = x;
  58756. this.y = y;
  58757. // previous and next vertice nodes in a polygon ring
  58758. this.prev = null;
  58759. this.next = null;
  58760. // z-order curve value
  58761. this.z = null;
  58762. // previous and next nodes in z-order
  58763. this.prevZ = null;
  58764. this.nextZ = null;
  58765. // indicates whether this is a steiner point
  58766. this.steiner = false;
  58767. }
  58768. /**
  58769. * return a percentage difference between the polygon area and its triangulation area;
  58770. * used to verify correctness of triangulation
  58771. */
  58772. function deviation(data, holeIndices, dim, triangles) {
  58773. var hasHoles = holeIndices && holeIndices.length;
  58774. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  58775. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  58776. if (hasHoles) {
  58777. for (var i = 0, len = holeIndices.length; i < len; i++) {
  58778. var start = holeIndices[i] * dim;
  58779. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  58780. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  58781. }
  58782. }
  58783. var trianglesArea = 0;
  58784. for (i = 0; i < triangles.length; i += 3) {
  58785. var a = triangles[i] * dim;
  58786. var b = triangles[i + 1] * dim;
  58787. var c = triangles[i + 2] * dim;
  58788. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  58789. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  58790. }
  58791. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  58792. }
  58793. Earcut.deviation = deviation;
  58794. ;
  58795. function signedArea(data, start, end, dim) {
  58796. var sum = 0;
  58797. for (var i = start, j = end - dim; i < end; i += dim) {
  58798. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  58799. j = i;
  58800. }
  58801. return sum;
  58802. }
  58803. /**
  58804. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  58805. */
  58806. function flatten(data) {
  58807. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  58808. for (var i = 0; i < data.length; i++) {
  58809. for (var j = 0; j < data[i].length; j++) {
  58810. for (var d = 0; d < dim; d++)
  58811. result.vertices.push(data[i][j][d]);
  58812. }
  58813. if (i > 0) {
  58814. holeIndex += data[i - 1].length;
  58815. result.holes.push(holeIndex);
  58816. }
  58817. }
  58818. return result;
  58819. }
  58820. Earcut.flatten = flatten;
  58821. ;
  58822. })(Earcut || (Earcut = {}));
  58823. //# sourceMappingURL=babylon.earcut.js.map
  58824. /// <reference path="..\Math\babylon.math.ts" />
  58825. var BABYLON;
  58826. (function (BABYLON) {
  58827. var IndexedVector2 = (function (_super) {
  58828. __extends(IndexedVector2, _super);
  58829. function IndexedVector2(original, index) {
  58830. var _this = _super.call(this, original.x, original.y) || this;
  58831. _this.index = index;
  58832. return _this;
  58833. }
  58834. return IndexedVector2;
  58835. }(BABYLON.Vector2));
  58836. var PolygonPoints = (function () {
  58837. function PolygonPoints() {
  58838. this.elements = new Array();
  58839. }
  58840. PolygonPoints.prototype.add = function (originalPoints) {
  58841. var _this = this;
  58842. var result = new Array();
  58843. originalPoints.forEach(function (point) {
  58844. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  58845. var newPoint = new IndexedVector2(point, _this.elements.length);
  58846. result.push(newPoint);
  58847. _this.elements.push(newPoint);
  58848. }
  58849. });
  58850. return result;
  58851. };
  58852. PolygonPoints.prototype.computeBounds = function () {
  58853. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  58854. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  58855. this.elements.forEach(function (point) {
  58856. // x
  58857. if (point.x < lmin.x) {
  58858. lmin.x = point.x;
  58859. }
  58860. else if (point.x > lmax.x) {
  58861. lmax.x = point.x;
  58862. }
  58863. // y
  58864. if (point.y < lmin.y) {
  58865. lmin.y = point.y;
  58866. }
  58867. else if (point.y > lmax.y) {
  58868. lmax.y = point.y;
  58869. }
  58870. });
  58871. return {
  58872. min: lmin,
  58873. max: lmax,
  58874. width: lmax.x - lmin.x,
  58875. height: lmax.y - lmin.y
  58876. };
  58877. };
  58878. return PolygonPoints;
  58879. }());
  58880. var Polygon = (function () {
  58881. function Polygon() {
  58882. }
  58883. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  58884. return [
  58885. new BABYLON.Vector2(xmin, ymin),
  58886. new BABYLON.Vector2(xmax, ymin),
  58887. new BABYLON.Vector2(xmax, ymax),
  58888. new BABYLON.Vector2(xmin, ymax)
  58889. ];
  58890. };
  58891. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  58892. if (cx === void 0) { cx = 0; }
  58893. if (cy === void 0) { cy = 0; }
  58894. if (numberOfSides === void 0) { numberOfSides = 32; }
  58895. var result = new Array();
  58896. var angle = 0;
  58897. var increment = (Math.PI * 2) / numberOfSides;
  58898. for (var i = 0; i < numberOfSides; i++) {
  58899. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  58900. angle -= increment;
  58901. }
  58902. return result;
  58903. };
  58904. Polygon.Parse = function (input) {
  58905. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  58906. var i, result = [];
  58907. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  58908. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  58909. }
  58910. return result;
  58911. };
  58912. Polygon.StartingAt = function (x, y) {
  58913. return BABYLON.Path2.StartingAt(x, y);
  58914. };
  58915. return Polygon;
  58916. }());
  58917. BABYLON.Polygon = Polygon;
  58918. var PolygonMeshBuilder = (function () {
  58919. function PolygonMeshBuilder(name, contours, scene) {
  58920. this._points = new PolygonPoints();
  58921. this._outlinepoints = new PolygonPoints();
  58922. this._holes = [];
  58923. this._epoints = new Array();
  58924. this._eholes = new Array();
  58925. this._name = name;
  58926. this._scene = scene;
  58927. var points;
  58928. if (contours instanceof BABYLON.Path2) {
  58929. points = contours.getPoints();
  58930. }
  58931. else {
  58932. points = contours;
  58933. }
  58934. this._addToepoint(points);
  58935. this._points.add(points);
  58936. this._outlinepoints.add(points);
  58937. }
  58938. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  58939. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  58940. var p = points_1[_i];
  58941. this._epoints.push(p.x, p.y);
  58942. }
  58943. };
  58944. PolygonMeshBuilder.prototype.addHole = function (hole) {
  58945. this._points.add(hole);
  58946. var holepoints = new PolygonPoints();
  58947. holepoints.add(hole);
  58948. this._holes.push(holepoints);
  58949. this._eholes.push(this._epoints.length / 2);
  58950. this._addToepoint(hole);
  58951. return this;
  58952. };
  58953. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  58954. var _this = this;
  58955. if (updatable === void 0) { updatable = false; }
  58956. var result = new BABYLON.Mesh(this._name, this._scene);
  58957. var normals = [];
  58958. var positions = [];
  58959. var uvs = [];
  58960. var bounds = this._points.computeBounds();
  58961. this._points.elements.forEach(function (p) {
  58962. normals.push(0, 1.0, 0);
  58963. positions.push(p.x, 0, p.y);
  58964. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  58965. });
  58966. var indices = [];
  58967. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  58968. for (var i = 0; i < res.length; i++) {
  58969. indices.push(res[i]);
  58970. }
  58971. if (depth > 0) {
  58972. var positionscount = (positions.length / 3); //get the current pointcount
  58973. this._points.elements.forEach(function (p) {
  58974. normals.push(0, -1.0, 0);
  58975. positions.push(p.x, -depth, p.y);
  58976. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  58977. });
  58978. var totalCount = indices.length;
  58979. for (var i = 0; i < totalCount; i += 3) {
  58980. var i0 = indices[i + 0];
  58981. var i1 = indices[i + 1];
  58982. var i2 = indices[i + 2];
  58983. indices.push(i2 + positionscount);
  58984. indices.push(i1 + positionscount);
  58985. indices.push(i0 + positionscount);
  58986. }
  58987. //Add the sides
  58988. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  58989. this._holes.forEach(function (hole) {
  58990. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  58991. });
  58992. }
  58993. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  58994. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  58995. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  58996. result.setIndices(indices);
  58997. return result;
  58998. };
  58999. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  59000. var StartIndex = positions.length / 3;
  59001. var ulength = 0;
  59002. for (var i = 0; i < points.elements.length; i++) {
  59003. var p = points.elements[i];
  59004. var p1;
  59005. if ((i + 1) > points.elements.length - 1) {
  59006. p1 = points.elements[0];
  59007. }
  59008. else {
  59009. p1 = points.elements[i + 1];
  59010. }
  59011. positions.push(p.x, 0, p.y);
  59012. positions.push(p.x, -depth, p.y);
  59013. positions.push(p1.x, 0, p1.y);
  59014. positions.push(p1.x, -depth, p1.y);
  59015. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  59016. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  59017. var v3 = v2.subtract(v1);
  59018. var v4 = new BABYLON.Vector3(0, 1, 0);
  59019. var vn = BABYLON.Vector3.Cross(v3, v4);
  59020. vn = vn.normalize();
  59021. uvs.push(ulength / bounds.width, 0);
  59022. uvs.push(ulength / bounds.width, 1);
  59023. ulength += v3.length();
  59024. uvs.push((ulength / bounds.width), 0);
  59025. uvs.push((ulength / bounds.width), 1);
  59026. if (!flip) {
  59027. normals.push(-vn.x, -vn.y, -vn.z);
  59028. normals.push(-vn.x, -vn.y, -vn.z);
  59029. normals.push(-vn.x, -vn.y, -vn.z);
  59030. normals.push(-vn.x, -vn.y, -vn.z);
  59031. indices.push(StartIndex);
  59032. indices.push(StartIndex + 1);
  59033. indices.push(StartIndex + 2);
  59034. indices.push(StartIndex + 1);
  59035. indices.push(StartIndex + 3);
  59036. indices.push(StartIndex + 2);
  59037. }
  59038. else {
  59039. normals.push(vn.x, vn.y, vn.z);
  59040. normals.push(vn.x, vn.y, vn.z);
  59041. normals.push(vn.x, vn.y, vn.z);
  59042. normals.push(vn.x, vn.y, vn.z);
  59043. indices.push(StartIndex);
  59044. indices.push(StartIndex + 2);
  59045. indices.push(StartIndex + 1);
  59046. indices.push(StartIndex + 1);
  59047. indices.push(StartIndex + 2);
  59048. indices.push(StartIndex + 3);
  59049. }
  59050. StartIndex += 4;
  59051. }
  59052. ;
  59053. };
  59054. return PolygonMeshBuilder;
  59055. }());
  59056. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  59057. })(BABYLON || (BABYLON = {}));
  59058. //# sourceMappingURL=babylon.polygonMesh.js.map
  59059. var BABYLON;
  59060. (function (BABYLON) {
  59061. // Unique ID when we import meshes from Babylon to CSG
  59062. var currentCSGMeshId = 0;
  59063. // # class Vertex
  59064. // Represents a vertex of a polygon. Use your own vertex class instead of this
  59065. // one to provide additional features like texture coordinates and vertex
  59066. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  59067. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  59068. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  59069. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  59070. // is not used anywhere else.
  59071. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  59072. var Vertex = (function () {
  59073. function Vertex(pos, normal, uv) {
  59074. this.pos = pos;
  59075. this.normal = normal;
  59076. this.uv = uv;
  59077. }
  59078. Vertex.prototype.clone = function () {
  59079. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  59080. };
  59081. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  59082. // orientation of a polygon is flipped.
  59083. Vertex.prototype.flip = function () {
  59084. this.normal = this.normal.scale(-1);
  59085. };
  59086. // Create a new vertex between this vertex and `other` by linearly
  59087. // interpolating all properties using a parameter of `t`. Subclasses should
  59088. // override this to interpolate additional properties.
  59089. Vertex.prototype.interpolate = function (other, t) {
  59090. 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));
  59091. };
  59092. return Vertex;
  59093. }());
  59094. // # class Plane
  59095. // Represents a plane in 3D space.
  59096. var Plane = (function () {
  59097. function Plane(normal, w) {
  59098. this.normal = normal;
  59099. this.w = w;
  59100. }
  59101. Plane.FromPoints = function (a, b, c) {
  59102. var v0 = c.subtract(a);
  59103. var v1 = b.subtract(a);
  59104. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  59105. return null;
  59106. }
  59107. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  59108. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  59109. };
  59110. Plane.prototype.clone = function () {
  59111. return new Plane(this.normal.clone(), this.w);
  59112. };
  59113. Plane.prototype.flip = function () {
  59114. this.normal.scaleInPlace(-1);
  59115. this.w = -this.w;
  59116. };
  59117. // Split `polygon` by this plane if needed, then put the polygon or polygon
  59118. // fragments in the appropriate lists. Coplanar polygons go into either
  59119. // `coplanarFront` or `coplanarBack` depending on their orientation with
  59120. // respect to this plane. Polygons in front or in back of this plane go into
  59121. // either `front` or `back`.
  59122. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  59123. var COPLANAR = 0;
  59124. var FRONT = 1;
  59125. var BACK = 2;
  59126. var SPANNING = 3;
  59127. // Classify each point as well as the entire polygon into one of the above
  59128. // four classes.
  59129. var polygonType = 0;
  59130. var types = [];
  59131. var i;
  59132. var t;
  59133. for (i = 0; i < polygon.vertices.length; i++) {
  59134. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  59135. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  59136. polygonType |= type;
  59137. types.push(type);
  59138. }
  59139. // Put the polygon in the correct list, splitting it when necessary.
  59140. switch (polygonType) {
  59141. case COPLANAR:
  59142. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  59143. break;
  59144. case FRONT:
  59145. front.push(polygon);
  59146. break;
  59147. case BACK:
  59148. back.push(polygon);
  59149. break;
  59150. case SPANNING:
  59151. var f = [], b = [];
  59152. for (i = 0; i < polygon.vertices.length; i++) {
  59153. var j = (i + 1) % polygon.vertices.length;
  59154. var ti = types[i], tj = types[j];
  59155. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  59156. if (ti !== BACK)
  59157. f.push(vi);
  59158. if (ti !== FRONT)
  59159. b.push(ti !== BACK ? vi.clone() : vi);
  59160. if ((ti | tj) === SPANNING) {
  59161. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  59162. var v = vi.interpolate(vj, t);
  59163. f.push(v);
  59164. b.push(v.clone());
  59165. }
  59166. }
  59167. var poly;
  59168. if (f.length >= 3) {
  59169. poly = new Polygon(f, polygon.shared);
  59170. if (poly.plane)
  59171. front.push(poly);
  59172. }
  59173. if (b.length >= 3) {
  59174. poly = new Polygon(b, polygon.shared);
  59175. if (poly.plane)
  59176. back.push(poly);
  59177. }
  59178. break;
  59179. }
  59180. };
  59181. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  59182. // point is on the plane.
  59183. Plane.EPSILON = 1e-5;
  59184. return Plane;
  59185. }());
  59186. // # class Polygon
  59187. // Represents a convex polygon. The vertices used to initialize a polygon must
  59188. // be coplanar and form a convex loop.
  59189. //
  59190. // Each convex polygon has a `shared` property, which is shared between all
  59191. // polygons that are clones of each other or were split from the same polygon.
  59192. // This can be used to define per-polygon properties (such as surface color).
  59193. var Polygon = (function () {
  59194. function Polygon(vertices, shared) {
  59195. this.vertices = vertices;
  59196. this.shared = shared;
  59197. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  59198. }
  59199. Polygon.prototype.clone = function () {
  59200. var vertices = this.vertices.map(function (v) { return v.clone(); });
  59201. return new Polygon(vertices, this.shared);
  59202. };
  59203. Polygon.prototype.flip = function () {
  59204. this.vertices.reverse().map(function (v) { v.flip(); });
  59205. this.plane.flip();
  59206. };
  59207. return Polygon;
  59208. }());
  59209. // # class Node
  59210. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  59211. // by picking a polygon to split along. That polygon (and all other coplanar
  59212. // polygons) are added directly to that node and the other polygons are added to
  59213. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  59214. // no distinction between internal and leaf nodes.
  59215. var Node = (function () {
  59216. function Node(polygons) {
  59217. this.plane = null;
  59218. this.front = null;
  59219. this.back = null;
  59220. this.polygons = [];
  59221. if (polygons) {
  59222. this.build(polygons);
  59223. }
  59224. }
  59225. Node.prototype.clone = function () {
  59226. var node = new Node();
  59227. node.plane = this.plane && this.plane.clone();
  59228. node.front = this.front && this.front.clone();
  59229. node.back = this.back && this.back.clone();
  59230. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  59231. return node;
  59232. };
  59233. // Convert solid space to empty space and empty space to solid space.
  59234. Node.prototype.invert = function () {
  59235. for (var i = 0; i < this.polygons.length; i++) {
  59236. this.polygons[i].flip();
  59237. }
  59238. if (this.plane) {
  59239. this.plane.flip();
  59240. }
  59241. if (this.front) {
  59242. this.front.invert();
  59243. }
  59244. if (this.back) {
  59245. this.back.invert();
  59246. }
  59247. var temp = this.front;
  59248. this.front = this.back;
  59249. this.back = temp;
  59250. };
  59251. // Recursively remove all polygons in `polygons` that are inside this BSP
  59252. // tree.
  59253. Node.prototype.clipPolygons = function (polygons) {
  59254. if (!this.plane)
  59255. return polygons.slice();
  59256. var front = [], back = [];
  59257. for (var i = 0; i < polygons.length; i++) {
  59258. this.plane.splitPolygon(polygons[i], front, back, front, back);
  59259. }
  59260. if (this.front) {
  59261. front = this.front.clipPolygons(front);
  59262. }
  59263. if (this.back) {
  59264. back = this.back.clipPolygons(back);
  59265. }
  59266. else {
  59267. back = [];
  59268. }
  59269. return front.concat(back);
  59270. };
  59271. // Remove all polygons in this BSP tree that are inside the other BSP tree
  59272. // `bsp`.
  59273. Node.prototype.clipTo = function (bsp) {
  59274. this.polygons = bsp.clipPolygons(this.polygons);
  59275. if (this.front)
  59276. this.front.clipTo(bsp);
  59277. if (this.back)
  59278. this.back.clipTo(bsp);
  59279. };
  59280. // Return a list of all polygons in this BSP tree.
  59281. Node.prototype.allPolygons = function () {
  59282. var polygons = this.polygons.slice();
  59283. if (this.front)
  59284. polygons = polygons.concat(this.front.allPolygons());
  59285. if (this.back)
  59286. polygons = polygons.concat(this.back.allPolygons());
  59287. return polygons;
  59288. };
  59289. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  59290. // new polygons are filtered down to the bottom of the tree and become new
  59291. // nodes there. Each set of polygons is partitioned using the first polygon
  59292. // (no heuristic is used to pick a good split).
  59293. Node.prototype.build = function (polygons) {
  59294. if (!polygons.length)
  59295. return;
  59296. if (!this.plane)
  59297. this.plane = polygons[0].plane.clone();
  59298. var front = [], back = [];
  59299. for (var i = 0; i < polygons.length; i++) {
  59300. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  59301. }
  59302. if (front.length) {
  59303. if (!this.front)
  59304. this.front = new Node();
  59305. this.front.build(front);
  59306. }
  59307. if (back.length) {
  59308. if (!this.back)
  59309. this.back = new Node();
  59310. this.back.build(back);
  59311. }
  59312. };
  59313. return Node;
  59314. }());
  59315. var CSG = (function () {
  59316. function CSG() {
  59317. this.polygons = new Array();
  59318. }
  59319. // Convert BABYLON.Mesh to BABYLON.CSG
  59320. CSG.FromMesh = function (mesh) {
  59321. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  59322. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  59323. if (mesh instanceof BABYLON.Mesh) {
  59324. mesh.computeWorldMatrix(true);
  59325. matrix = mesh.getWorldMatrix();
  59326. meshPosition = mesh.position.clone();
  59327. meshRotation = mesh.rotation.clone();
  59328. if (mesh.rotationQuaternion) {
  59329. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  59330. }
  59331. meshScaling = mesh.scaling.clone();
  59332. }
  59333. else {
  59334. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  59335. }
  59336. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59337. var subMeshes = mesh.subMeshes;
  59338. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  59339. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  59340. vertices = [];
  59341. for (var j = 0; j < 3; j++) {
  59342. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  59343. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  59344. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  59345. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  59346. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  59347. vertex = new Vertex(position, normal, uv);
  59348. vertices.push(vertex);
  59349. }
  59350. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  59351. // To handle the case of degenerated triangle
  59352. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  59353. if (polygon.plane)
  59354. polygons.push(polygon);
  59355. }
  59356. }
  59357. var csg = CSG.FromPolygons(polygons);
  59358. csg.matrix = matrix;
  59359. csg.position = meshPosition;
  59360. csg.rotation = meshRotation;
  59361. csg.scaling = meshScaling;
  59362. csg.rotationQuaternion = meshRotationQuaternion;
  59363. currentCSGMeshId++;
  59364. return csg;
  59365. };
  59366. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  59367. CSG.FromPolygons = function (polygons) {
  59368. var csg = new CSG();
  59369. csg.polygons = polygons;
  59370. return csg;
  59371. };
  59372. CSG.prototype.clone = function () {
  59373. var csg = new CSG();
  59374. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  59375. csg.copyTransformAttributes(this);
  59376. return csg;
  59377. };
  59378. CSG.prototype.toPolygons = function () {
  59379. return this.polygons;
  59380. };
  59381. CSG.prototype.union = function (csg) {
  59382. var a = new Node(this.clone().polygons);
  59383. var b = new Node(csg.clone().polygons);
  59384. a.clipTo(b);
  59385. b.clipTo(a);
  59386. b.invert();
  59387. b.clipTo(a);
  59388. b.invert();
  59389. a.build(b.allPolygons());
  59390. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59391. };
  59392. CSG.prototype.unionInPlace = function (csg) {
  59393. var a = new Node(this.polygons);
  59394. var b = new Node(csg.polygons);
  59395. a.clipTo(b);
  59396. b.clipTo(a);
  59397. b.invert();
  59398. b.clipTo(a);
  59399. b.invert();
  59400. a.build(b.allPolygons());
  59401. this.polygons = a.allPolygons();
  59402. };
  59403. CSG.prototype.subtract = function (csg) {
  59404. var a = new Node(this.clone().polygons);
  59405. var b = new Node(csg.clone().polygons);
  59406. a.invert();
  59407. a.clipTo(b);
  59408. b.clipTo(a);
  59409. b.invert();
  59410. b.clipTo(a);
  59411. b.invert();
  59412. a.build(b.allPolygons());
  59413. a.invert();
  59414. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59415. };
  59416. CSG.prototype.subtractInPlace = function (csg) {
  59417. var a = new Node(this.polygons);
  59418. var b = new Node(csg.polygons);
  59419. a.invert();
  59420. a.clipTo(b);
  59421. b.clipTo(a);
  59422. b.invert();
  59423. b.clipTo(a);
  59424. b.invert();
  59425. a.build(b.allPolygons());
  59426. a.invert();
  59427. this.polygons = a.allPolygons();
  59428. };
  59429. CSG.prototype.intersect = function (csg) {
  59430. var a = new Node(this.clone().polygons);
  59431. var b = new Node(csg.clone().polygons);
  59432. a.invert();
  59433. b.clipTo(a);
  59434. b.invert();
  59435. a.clipTo(b);
  59436. b.clipTo(a);
  59437. a.build(b.allPolygons());
  59438. a.invert();
  59439. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59440. };
  59441. CSG.prototype.intersectInPlace = function (csg) {
  59442. var a = new Node(this.polygons);
  59443. var b = new Node(csg.polygons);
  59444. a.invert();
  59445. b.clipTo(a);
  59446. b.invert();
  59447. a.clipTo(b);
  59448. b.clipTo(a);
  59449. a.build(b.allPolygons());
  59450. a.invert();
  59451. this.polygons = a.allPolygons();
  59452. };
  59453. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  59454. // not modified.
  59455. CSG.prototype.inverse = function () {
  59456. var csg = this.clone();
  59457. csg.inverseInPlace();
  59458. return csg;
  59459. };
  59460. CSG.prototype.inverseInPlace = function () {
  59461. this.polygons.map(function (p) { p.flip(); });
  59462. };
  59463. // This is used to keep meshes transformations so they can be restored
  59464. // when we build back a Babylon Mesh
  59465. // NB : All CSG operations are performed in world coordinates
  59466. CSG.prototype.copyTransformAttributes = function (csg) {
  59467. this.matrix = csg.matrix;
  59468. this.position = csg.position;
  59469. this.rotation = csg.rotation;
  59470. this.scaling = csg.scaling;
  59471. this.rotationQuaternion = csg.rotationQuaternion;
  59472. return this;
  59473. };
  59474. // Build Raw mesh from CSG
  59475. // Coordinates here are in world space
  59476. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  59477. var matrix = this.matrix.clone();
  59478. matrix.invert();
  59479. 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;
  59480. if (keepSubMeshes) {
  59481. // Sort Polygons, since subMeshes are indices range
  59482. polygons.sort(function (a, b) {
  59483. if (a.shared.meshId === b.shared.meshId) {
  59484. return a.shared.subMeshId - b.shared.subMeshId;
  59485. }
  59486. else {
  59487. return a.shared.meshId - b.shared.meshId;
  59488. }
  59489. });
  59490. }
  59491. for (var i = 0, il = polygons.length; i < il; i++) {
  59492. polygon = polygons[i];
  59493. // Building SubMeshes
  59494. if (!subMesh_dict[polygon.shared.meshId]) {
  59495. subMesh_dict[polygon.shared.meshId] = {};
  59496. }
  59497. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  59498. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  59499. indexStart: +Infinity,
  59500. indexEnd: -Infinity,
  59501. materialIndex: polygon.shared.materialIndex
  59502. };
  59503. }
  59504. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  59505. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  59506. polygonIndices[0] = 0;
  59507. polygonIndices[1] = j - 1;
  59508. polygonIndices[2] = j;
  59509. for (var k = 0; k < 3; k++) {
  59510. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  59511. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  59512. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  59513. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  59514. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  59515. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  59516. // Check if 2 points can be merged
  59517. if (!(typeof vertex_idx !== 'undefined' &&
  59518. normals[vertex_idx * 3] === localNormal.x &&
  59519. normals[vertex_idx * 3 + 1] === localNormal.y &&
  59520. normals[vertex_idx * 3 + 2] === localNormal.z &&
  59521. uvs[vertex_idx * 2] === uv.x &&
  59522. uvs[vertex_idx * 2 + 1] === uv.y)) {
  59523. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  59524. uvs.push(uv.x, uv.y);
  59525. normals.push(normal.x, normal.y, normal.z);
  59526. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  59527. }
  59528. indices.push(vertex_idx);
  59529. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  59530. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  59531. currentIndex++;
  59532. }
  59533. }
  59534. }
  59535. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  59536. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  59537. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  59538. mesh.setIndices(indices);
  59539. if (keepSubMeshes) {
  59540. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  59541. var materialIndexOffset = 0, materialMaxIndex;
  59542. mesh.subMeshes = new Array();
  59543. for (var m in subMesh_dict) {
  59544. materialMaxIndex = -1;
  59545. for (var sm in subMesh_dict[m]) {
  59546. subMesh_obj = subMesh_dict[m][sm];
  59547. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  59548. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  59549. }
  59550. materialIndexOffset += ++materialMaxIndex;
  59551. }
  59552. }
  59553. return mesh;
  59554. };
  59555. // Build Mesh from CSG taking material and transforms into account
  59556. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  59557. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  59558. mesh.material = material;
  59559. mesh.position.copyFrom(this.position);
  59560. mesh.rotation.copyFrom(this.rotation);
  59561. if (this.rotationQuaternion) {
  59562. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  59563. }
  59564. mesh.scaling.copyFrom(this.scaling);
  59565. mesh.computeWorldMatrix(true);
  59566. return mesh;
  59567. };
  59568. return CSG;
  59569. }());
  59570. BABYLON.CSG = CSG;
  59571. })(BABYLON || (BABYLON = {}));
  59572. //# sourceMappingURL=babylon.csg.js.map
  59573. var BABYLON;
  59574. (function (BABYLON) {
  59575. var LensFlare = (function () {
  59576. function LensFlare(size, position, color, imgUrl, system) {
  59577. this.size = size;
  59578. this.position = position;
  59579. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  59580. this.dispose = function () {
  59581. if (this.texture) {
  59582. this.texture.dispose();
  59583. }
  59584. // Remove from scene
  59585. var index = this._system.lensFlares.indexOf(this);
  59586. this._system.lensFlares.splice(index, 1);
  59587. };
  59588. this.color = color || new BABYLON.Color3(1, 1, 1);
  59589. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  59590. this._system = system;
  59591. system.lensFlares.push(this);
  59592. }
  59593. return LensFlare;
  59594. }());
  59595. BABYLON.LensFlare = LensFlare;
  59596. })(BABYLON || (BABYLON = {}));
  59597. //# sourceMappingURL=babylon.lensFlare.js.map
  59598. var BABYLON;
  59599. (function (BABYLON) {
  59600. var LensFlareSystem = (function () {
  59601. function LensFlareSystem(name, emitter, scene) {
  59602. this.name = name;
  59603. this.lensFlares = new Array();
  59604. this.borderLimit = 300;
  59605. this.viewportBorder = 0;
  59606. this.layerMask = 0x0FFFFFFF;
  59607. this._vertexBuffers = {};
  59608. this._isEnabled = true;
  59609. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59610. this._emitter = emitter;
  59611. this.id = name;
  59612. scene.lensFlareSystems.push(this);
  59613. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  59614. var engine = scene.getEngine();
  59615. // VBO
  59616. var vertices = [];
  59617. vertices.push(1, 1);
  59618. vertices.push(-1, 1);
  59619. vertices.push(-1, -1);
  59620. vertices.push(1, -1);
  59621. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59622. // Indices
  59623. var indices = [];
  59624. indices.push(0);
  59625. indices.push(1);
  59626. indices.push(2);
  59627. indices.push(0);
  59628. indices.push(2);
  59629. indices.push(3);
  59630. this._indexBuffer = engine.createIndexBuffer(indices);
  59631. // Effects
  59632. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  59633. }
  59634. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  59635. get: function () {
  59636. return this._isEnabled;
  59637. },
  59638. set: function (value) {
  59639. this._isEnabled = value;
  59640. },
  59641. enumerable: true,
  59642. configurable: true
  59643. });
  59644. LensFlareSystem.prototype.getScene = function () {
  59645. return this._scene;
  59646. };
  59647. LensFlareSystem.prototype.getEmitter = function () {
  59648. return this._emitter;
  59649. };
  59650. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  59651. this._emitter = newEmitter;
  59652. };
  59653. LensFlareSystem.prototype.getEmitterPosition = function () {
  59654. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  59655. };
  59656. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  59657. var position = this.getEmitterPosition();
  59658. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  59659. this._positionX = position.x;
  59660. this._positionY = position.y;
  59661. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  59662. if (this.viewportBorder > 0) {
  59663. globalViewport.x -= this.viewportBorder;
  59664. globalViewport.y -= this.viewportBorder;
  59665. globalViewport.width += this.viewportBorder * 2;
  59666. globalViewport.height += this.viewportBorder * 2;
  59667. position.x += this.viewportBorder;
  59668. position.y += this.viewportBorder;
  59669. this._positionX += this.viewportBorder;
  59670. this._positionY += this.viewportBorder;
  59671. }
  59672. if (position.z > 0) {
  59673. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  59674. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  59675. return true;
  59676. }
  59677. return true;
  59678. }
  59679. return false;
  59680. };
  59681. LensFlareSystem.prototype._isVisible = function () {
  59682. if (!this._isEnabled) {
  59683. return false;
  59684. }
  59685. var emitterPosition = this.getEmitterPosition();
  59686. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  59687. var distance = direction.length();
  59688. direction.normalize();
  59689. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  59690. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  59691. return !pickInfo.hit || pickInfo.distance > distance;
  59692. };
  59693. LensFlareSystem.prototype.render = function () {
  59694. if (!this._effect.isReady())
  59695. return false;
  59696. var engine = this._scene.getEngine();
  59697. var viewport = this._scene.activeCamera.viewport;
  59698. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  59699. // Position
  59700. if (!this.computeEffectivePosition(globalViewport)) {
  59701. return false;
  59702. }
  59703. // Visibility
  59704. if (!this._isVisible()) {
  59705. return false;
  59706. }
  59707. // Intensity
  59708. var awayX;
  59709. var awayY;
  59710. if (this._positionX < this.borderLimit + globalViewport.x) {
  59711. awayX = this.borderLimit + globalViewport.x - this._positionX;
  59712. }
  59713. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  59714. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  59715. }
  59716. else {
  59717. awayX = 0;
  59718. }
  59719. if (this._positionY < this.borderLimit + globalViewport.y) {
  59720. awayY = this.borderLimit + globalViewport.y - this._positionY;
  59721. }
  59722. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  59723. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  59724. }
  59725. else {
  59726. awayY = 0;
  59727. }
  59728. var away = (awayX > awayY) ? awayX : awayY;
  59729. away -= this.viewportBorder;
  59730. if (away > this.borderLimit) {
  59731. away = this.borderLimit;
  59732. }
  59733. var intensity = 1.0 - (away / this.borderLimit);
  59734. if (intensity < 0) {
  59735. return false;
  59736. }
  59737. if (intensity > 1.0) {
  59738. intensity = 1.0;
  59739. }
  59740. if (this.viewportBorder > 0) {
  59741. globalViewport.x += this.viewportBorder;
  59742. globalViewport.y += this.viewportBorder;
  59743. globalViewport.width -= this.viewportBorder * 2;
  59744. globalViewport.height -= this.viewportBorder * 2;
  59745. this._positionX -= this.viewportBorder;
  59746. this._positionY -= this.viewportBorder;
  59747. }
  59748. // Position
  59749. var centerX = globalViewport.x + globalViewport.width / 2;
  59750. var centerY = globalViewport.y + globalViewport.height / 2;
  59751. var distX = centerX - this._positionX;
  59752. var distY = centerY - this._positionY;
  59753. // Effects
  59754. engine.enableEffect(this._effect);
  59755. engine.setState(false);
  59756. engine.setDepthBuffer(false);
  59757. // VBOs
  59758. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59759. // Flares
  59760. for (var index = 0; index < this.lensFlares.length; index++) {
  59761. var flare = this.lensFlares[index];
  59762. engine.setAlphaMode(flare.alphaMode);
  59763. var x = centerX - (distX * flare.position);
  59764. var y = centerY - (distY * flare.position);
  59765. var cw = flare.size;
  59766. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  59767. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  59768. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  59769. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  59770. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  59771. // Texture
  59772. this._effect.setTexture("textureSampler", flare.texture);
  59773. // Color
  59774. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  59775. // Draw order
  59776. engine.draw(true, 0, 6);
  59777. }
  59778. engine.setDepthBuffer(true);
  59779. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59780. return true;
  59781. };
  59782. LensFlareSystem.prototype.dispose = function () {
  59783. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59784. if (vertexBuffer) {
  59785. vertexBuffer.dispose();
  59786. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59787. }
  59788. if (this._indexBuffer) {
  59789. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59790. this._indexBuffer = null;
  59791. }
  59792. while (this.lensFlares.length) {
  59793. this.lensFlares[0].dispose();
  59794. }
  59795. // Remove from scene
  59796. var index = this._scene.lensFlareSystems.indexOf(this);
  59797. this._scene.lensFlareSystems.splice(index, 1);
  59798. };
  59799. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  59800. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  59801. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  59802. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  59803. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  59804. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  59805. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  59806. var parsedFlare = parsedLensFlareSystem.flares[index];
  59807. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  59808. }
  59809. return lensFlareSystem;
  59810. };
  59811. LensFlareSystem.prototype.serialize = function () {
  59812. var serializationObject = {};
  59813. serializationObject.id = this.id;
  59814. serializationObject.name = this.name;
  59815. serializationObject.emitterId = this.getEmitter().id;
  59816. serializationObject.borderLimit = this.borderLimit;
  59817. serializationObject.flares = [];
  59818. for (var index = 0; index < this.lensFlares.length; index++) {
  59819. var flare = this.lensFlares[index];
  59820. serializationObject.flares.push({
  59821. size: flare.size,
  59822. position: flare.position,
  59823. color: flare.color.asArray(),
  59824. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  59825. });
  59826. }
  59827. return serializationObject;
  59828. };
  59829. return LensFlareSystem;
  59830. }());
  59831. BABYLON.LensFlareSystem = LensFlareSystem;
  59832. })(BABYLON || (BABYLON = {}));
  59833. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  59834. var BABYLON;
  59835. (function (BABYLON) {
  59836. /**
  59837. * This is a holder class for the physics joint created by the physics plugin.
  59838. * It holds a set of functions to control the underlying joint.
  59839. */
  59840. var PhysicsJoint = (function () {
  59841. function PhysicsJoint(type, jointData) {
  59842. this.type = type;
  59843. this.jointData = jointData;
  59844. jointData.nativeParams = jointData.nativeParams || {};
  59845. }
  59846. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  59847. get: function () {
  59848. return this._physicsJoint;
  59849. },
  59850. set: function (newJoint) {
  59851. if (this._physicsJoint) {
  59852. //remove from the wolrd
  59853. }
  59854. this._physicsJoint = newJoint;
  59855. },
  59856. enumerable: true,
  59857. configurable: true
  59858. });
  59859. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  59860. set: function (physicsPlugin) {
  59861. this._physicsPlugin = physicsPlugin;
  59862. },
  59863. enumerable: true,
  59864. configurable: true
  59865. });
  59866. /**
  59867. * Execute a function that is physics-plugin specific.
  59868. * @param {Function} func the function that will be executed.
  59869. * It accepts two parameters: the physics world and the physics joint.
  59870. */
  59871. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  59872. func(this._physicsPlugin.world, this._physicsJoint);
  59873. };
  59874. //TODO check if the native joints are the same
  59875. //Joint Types
  59876. PhysicsJoint.DistanceJoint = 0;
  59877. PhysicsJoint.HingeJoint = 1;
  59878. PhysicsJoint.BallAndSocketJoint = 2;
  59879. PhysicsJoint.WheelJoint = 3;
  59880. PhysicsJoint.SliderJoint = 4;
  59881. //OIMO
  59882. PhysicsJoint.PrismaticJoint = 5;
  59883. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  59884. PhysicsJoint.UniversalJoint = 6;
  59885. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  59886. //Cannon
  59887. //Similar to a Ball-Joint. Different in params
  59888. PhysicsJoint.PointToPointJoint = 8;
  59889. //Cannon only at the moment
  59890. PhysicsJoint.SpringJoint = 9;
  59891. PhysicsJoint.LockJoint = 10;
  59892. return PhysicsJoint;
  59893. }());
  59894. BABYLON.PhysicsJoint = PhysicsJoint;
  59895. /**
  59896. * A class representing a physics distance joint.
  59897. */
  59898. var DistanceJoint = (function (_super) {
  59899. __extends(DistanceJoint, _super);
  59900. function DistanceJoint(jointData) {
  59901. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  59902. }
  59903. /**
  59904. * Update the predefined distance.
  59905. */
  59906. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  59907. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  59908. };
  59909. return DistanceJoint;
  59910. }(PhysicsJoint));
  59911. BABYLON.DistanceJoint = DistanceJoint;
  59912. var MotorEnabledJoint = (function (_super) {
  59913. __extends(MotorEnabledJoint, _super);
  59914. function MotorEnabledJoint(type, jointData) {
  59915. return _super.call(this, type, jointData) || this;
  59916. }
  59917. /**
  59918. * Set the motor values.
  59919. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59920. * @param {number} force the force to apply
  59921. * @param {number} maxForce max force for this motor.
  59922. */
  59923. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  59924. this._physicsPlugin.setMotor(this, force, maxForce);
  59925. };
  59926. /**
  59927. * Set the motor's limits.
  59928. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59929. */
  59930. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  59931. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  59932. };
  59933. return MotorEnabledJoint;
  59934. }(PhysicsJoint));
  59935. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  59936. /**
  59937. * This class represents a single hinge physics joint
  59938. */
  59939. var HingeJoint = (function (_super) {
  59940. __extends(HingeJoint, _super);
  59941. function HingeJoint(jointData) {
  59942. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  59943. }
  59944. /**
  59945. * Set the motor values.
  59946. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59947. * @param {number} force the force to apply
  59948. * @param {number} maxForce max force for this motor.
  59949. */
  59950. HingeJoint.prototype.setMotor = function (force, maxForce) {
  59951. this._physicsPlugin.setMotor(this, force, maxForce);
  59952. };
  59953. /**
  59954. * Set the motor's limits.
  59955. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59956. */
  59957. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  59958. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  59959. };
  59960. return HingeJoint;
  59961. }(MotorEnabledJoint));
  59962. BABYLON.HingeJoint = HingeJoint;
  59963. /**
  59964. * This class represents a dual hinge physics joint (same as wheel joint)
  59965. */
  59966. var Hinge2Joint = (function (_super) {
  59967. __extends(Hinge2Joint, _super);
  59968. function Hinge2Joint(jointData) {
  59969. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  59970. }
  59971. /**
  59972. * Set the motor values.
  59973. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59974. * @param {number} force the force to apply
  59975. * @param {number} maxForce max force for this motor.
  59976. * @param {motorIndex} the motor's index, 0 or 1.
  59977. */
  59978. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  59979. if (motorIndex === void 0) { motorIndex = 0; }
  59980. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  59981. };
  59982. /**
  59983. * Set the motor limits.
  59984. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59985. * @param {number} upperLimit the upper limit
  59986. * @param {number} lowerLimit lower limit
  59987. * @param {motorIndex} the motor's index, 0 or 1.
  59988. */
  59989. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  59990. if (motorIndex === void 0) { motorIndex = 0; }
  59991. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  59992. };
  59993. return Hinge2Joint;
  59994. }(MotorEnabledJoint));
  59995. BABYLON.Hinge2Joint = Hinge2Joint;
  59996. })(BABYLON || (BABYLON = {}));
  59997. //# sourceMappingURL=babylon.physicsJoint.js.map
  59998. var BABYLON;
  59999. (function (BABYLON) {
  60000. var PhysicsImpostor = (function () {
  60001. function PhysicsImpostor(object, type, _options, _scene) {
  60002. if (_options === void 0) { _options = { mass: 0 }; }
  60003. var _this = this;
  60004. this.object = object;
  60005. this.type = type;
  60006. this._options = _options;
  60007. this._scene = _scene;
  60008. this._bodyUpdateRequired = false;
  60009. this._onBeforePhysicsStepCallbacks = new Array();
  60010. this._onAfterPhysicsStepCallbacks = new Array();
  60011. this._onPhysicsCollideCallbacks = [];
  60012. this._deltaPosition = BABYLON.Vector3.Zero();
  60013. this._isDisposed = false;
  60014. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  60015. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  60016. /**
  60017. * this function is executed by the physics engine.
  60018. */
  60019. this.beforeStep = function () {
  60020. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  60021. //conjugate deltaRotation
  60022. if (_this._deltaRotationConjugated) {
  60023. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  60024. }
  60025. else {
  60026. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  60027. }
  60028. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  60029. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  60030. func(_this);
  60031. });
  60032. };
  60033. /**
  60034. * this function is executed by the physics engine.
  60035. */
  60036. this.afterStep = function () {
  60037. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  60038. func(_this);
  60039. });
  60040. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  60041. _this.object.position.addInPlace(_this._deltaPosition);
  60042. if (_this._deltaRotation) {
  60043. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  60044. }
  60045. };
  60046. /**
  60047. * Legacy collision detection event support
  60048. */
  60049. this.onCollideEvent = null;
  60050. //event and body object due to cannon's event-based architecture.
  60051. this.onCollide = function (e) {
  60052. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  60053. return;
  60054. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  60055. if (otherImpostor) {
  60056. // Legacy collision detection event support
  60057. if (_this.onCollideEvent) {
  60058. _this.onCollideEvent(_this, otherImpostor);
  60059. }
  60060. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  60061. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  60062. }).forEach(function (obj) {
  60063. obj.callback(_this, otherImpostor);
  60064. });
  60065. }
  60066. };
  60067. //sanity check!
  60068. if (!this.object) {
  60069. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  60070. return;
  60071. }
  60072. //legacy support for old syntax.
  60073. if (!this._scene && object.getScene) {
  60074. this._scene = object.getScene();
  60075. }
  60076. this._physicsEngine = this._scene.getPhysicsEngine();
  60077. if (!this._physicsEngine) {
  60078. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  60079. }
  60080. else {
  60081. //set the object's quaternion, if not set
  60082. if (!this.object.rotationQuaternion) {
  60083. if (this.object.rotation) {
  60084. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  60085. }
  60086. else {
  60087. this.object.rotationQuaternion = new BABYLON.Quaternion();
  60088. }
  60089. }
  60090. //default options params
  60091. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  60092. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  60093. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  60094. this._joints = [];
  60095. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  60096. if (!this.object.parent) {
  60097. this._init();
  60098. }
  60099. else if (this.object.parent.physicsImpostor) {
  60100. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  60101. }
  60102. }
  60103. }
  60104. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  60105. get: function () {
  60106. return this._isDisposed;
  60107. },
  60108. enumerable: true,
  60109. configurable: true
  60110. });
  60111. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  60112. get: function () {
  60113. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  60114. },
  60115. set: function (value) {
  60116. this.setMass(value);
  60117. },
  60118. enumerable: true,
  60119. configurable: true
  60120. });
  60121. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  60122. get: function () {
  60123. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  60124. },
  60125. set: function (value) {
  60126. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  60127. },
  60128. enumerable: true,
  60129. configurable: true
  60130. });
  60131. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  60132. get: function () {
  60133. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  60134. },
  60135. set: function (value) {
  60136. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  60137. },
  60138. enumerable: true,
  60139. configurable: true
  60140. });
  60141. /**
  60142. * This function will completly initialize this impostor.
  60143. * It will create a new body - but only if this mesh has no parent.
  60144. * If it has, this impostor will not be used other than to define the impostor
  60145. * of the child mesh.
  60146. */
  60147. PhysicsImpostor.prototype._init = function () {
  60148. this._physicsEngine.removeImpostor(this);
  60149. this.physicsBody = null;
  60150. this._parent = this._parent || this._getPhysicsParent();
  60151. if (!this.parent) {
  60152. this._physicsEngine.addImpostor(this);
  60153. }
  60154. };
  60155. PhysicsImpostor.prototype._getPhysicsParent = function () {
  60156. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  60157. var parentMesh = this.object.parent;
  60158. return parentMesh.physicsImpostor;
  60159. }
  60160. return;
  60161. };
  60162. /**
  60163. * Should a new body be generated.
  60164. */
  60165. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  60166. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  60167. };
  60168. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  60169. this.forceUpdate();
  60170. };
  60171. /**
  60172. * Force a regeneration of this or the parent's impostor's body.
  60173. * Use under cautious - This will remove all joints already implemented.
  60174. */
  60175. PhysicsImpostor.prototype.forceUpdate = function () {
  60176. this._init();
  60177. if (this.parent) {
  60178. this.parent.forceUpdate();
  60179. }
  60180. };
  60181. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  60182. /*public get mesh(): AbstractMesh {
  60183. return this._mesh;
  60184. }*/
  60185. /**
  60186. * Gets the body that holds this impostor. Either its own, or its parent.
  60187. */
  60188. get: function () {
  60189. return this._parent ? this._parent.physicsBody : this._physicsBody;
  60190. },
  60191. /**
  60192. * Set the physics body. Used mainly by the physics engine/plugin
  60193. */
  60194. set: function (physicsBody) {
  60195. if (this._physicsBody) {
  60196. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  60197. }
  60198. this._physicsBody = physicsBody;
  60199. this.resetUpdateFlags();
  60200. },
  60201. enumerable: true,
  60202. configurable: true
  60203. });
  60204. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  60205. get: function () {
  60206. return this._parent;
  60207. },
  60208. set: function (value) {
  60209. this._parent = value;
  60210. },
  60211. enumerable: true,
  60212. configurable: true
  60213. });
  60214. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  60215. this._bodyUpdateRequired = false;
  60216. };
  60217. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  60218. if (this.object.getBoundingInfo) {
  60219. var q = this.object.rotationQuaternion;
  60220. //reset rotation
  60221. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  60222. //calculate the world matrix with no rotation
  60223. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60224. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  60225. //bring back the rotation
  60226. this.object.rotationQuaternion = q;
  60227. //calculate the world matrix with the new rotation
  60228. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60229. return size;
  60230. }
  60231. else {
  60232. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  60233. }
  60234. };
  60235. PhysicsImpostor.prototype.getObjectCenter = function () {
  60236. if (this.object.getBoundingInfo) {
  60237. return this.object.getBoundingInfo().boundingBox.centerWorld;
  60238. }
  60239. else {
  60240. return this.object.position;
  60241. }
  60242. };
  60243. /**
  60244. * Get a specific parametes from the options parameter.
  60245. */
  60246. PhysicsImpostor.prototype.getParam = function (paramName) {
  60247. return this._options[paramName];
  60248. };
  60249. /**
  60250. * Sets a specific parameter in the options given to the physics plugin
  60251. */
  60252. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  60253. this._options[paramName] = value;
  60254. this._bodyUpdateRequired = true;
  60255. };
  60256. /**
  60257. * Specifically change the body's mass option. Won't recreate the physics body object
  60258. */
  60259. PhysicsImpostor.prototype.setMass = function (mass) {
  60260. if (this.getParam("mass") !== mass) {
  60261. this.setParam("mass", mass);
  60262. }
  60263. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  60264. };
  60265. PhysicsImpostor.prototype.getLinearVelocity = function () {
  60266. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  60267. };
  60268. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  60269. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  60270. };
  60271. PhysicsImpostor.prototype.getAngularVelocity = function () {
  60272. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  60273. };
  60274. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  60275. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  60276. };
  60277. /**
  60278. * Execute a function with the physics plugin native code.
  60279. * Provide a function the will have two variables - the world object and the physics body object.
  60280. */
  60281. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  60282. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  60283. };
  60284. /**
  60285. * Register a function that will be executed before the physics world is stepping forward.
  60286. */
  60287. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  60288. this._onBeforePhysicsStepCallbacks.push(func);
  60289. };
  60290. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  60291. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  60292. if (index > -1) {
  60293. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  60294. }
  60295. else {
  60296. BABYLON.Tools.Warn("Function to remove was not found");
  60297. }
  60298. };
  60299. /**
  60300. * Register a function that will be executed after the physics step
  60301. */
  60302. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  60303. this._onAfterPhysicsStepCallbacks.push(func);
  60304. };
  60305. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  60306. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  60307. if (index > -1) {
  60308. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  60309. }
  60310. else {
  60311. BABYLON.Tools.Warn("Function to remove was not found");
  60312. }
  60313. };
  60314. /**
  60315. * register a function that will be executed when this impostor collides against a different body.
  60316. */
  60317. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  60318. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  60319. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  60320. };
  60321. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  60322. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  60323. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  60324. if (index > -1) {
  60325. this._onPhysicsCollideCallbacks.splice(index, 1);
  60326. }
  60327. else {
  60328. BABYLON.Tools.Warn("Function to remove was not found");
  60329. }
  60330. };
  60331. /**
  60332. * Apply a force
  60333. */
  60334. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  60335. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  60336. };
  60337. /**
  60338. * Apply an impulse
  60339. */
  60340. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  60341. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  60342. };
  60343. /**
  60344. * A help function to create a joint.
  60345. */
  60346. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  60347. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  60348. this.addJoint(otherImpostor, joint);
  60349. };
  60350. /**
  60351. * Add a joint to this impostor with a different impostor.
  60352. */
  60353. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  60354. this._joints.push({
  60355. otherImpostor: otherImpostor,
  60356. joint: joint
  60357. });
  60358. this._physicsEngine.addJoint(this, otherImpostor, joint);
  60359. };
  60360. /**
  60361. * Will keep this body still, in a sleep mode.
  60362. */
  60363. PhysicsImpostor.prototype.sleep = function () {
  60364. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  60365. };
  60366. /**
  60367. * Wake the body up.
  60368. */
  60369. PhysicsImpostor.prototype.wakeUp = function () {
  60370. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  60371. };
  60372. PhysicsImpostor.prototype.clone = function (newObject) {
  60373. if (!newObject)
  60374. return null;
  60375. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  60376. };
  60377. PhysicsImpostor.prototype.dispose = function () {
  60378. var _this = this;
  60379. //no dispose if no physics engine is available.
  60380. if (!this._physicsEngine) {
  60381. return;
  60382. }
  60383. this._joints.forEach(function (j) {
  60384. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  60385. });
  60386. //dispose the physics body
  60387. this._physicsEngine.removeImpostor(this);
  60388. if (this.parent) {
  60389. this.parent.forceUpdate();
  60390. }
  60391. else {
  60392. /*this._object.getChildMeshes().forEach(function(mesh) {
  60393. if (mesh.physicsImpostor) {
  60394. if (disposeChildren) {
  60395. mesh.physicsImpostor.dispose();
  60396. mesh.physicsImpostor = null;
  60397. }
  60398. }
  60399. })*/
  60400. }
  60401. this._isDisposed = true;
  60402. };
  60403. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  60404. this._deltaPosition.copyFrom(position);
  60405. };
  60406. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  60407. if (!this._deltaRotation) {
  60408. this._deltaRotation = new BABYLON.Quaternion();
  60409. }
  60410. this._deltaRotation.copyFrom(rotation);
  60411. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  60412. };
  60413. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  60414. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  60415. };
  60416. PhysicsImpostor.prototype.getRadius = function () {
  60417. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  60418. };
  60419. /**
  60420. * Sync a bone with this impostor
  60421. * @param bone The bone to sync to the impostor.
  60422. * @param boneMesh The mesh that the bone is influencing.
  60423. * @param jointPivot The pivot of the joint / bone in local space.
  60424. * @param distToJoint Optional distance from the impostor to the joint.
  60425. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  60426. */
  60427. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  60428. var tempVec = PhysicsImpostor._tmpVecs[0];
  60429. var mesh = this.object;
  60430. if (adjustRotation) {
  60431. var tempQuat = PhysicsImpostor._tmpQuat;
  60432. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  60433. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  60434. }
  60435. else {
  60436. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  60437. }
  60438. tempVec.x = 0;
  60439. tempVec.y = 0;
  60440. tempVec.z = 0;
  60441. if (jointPivot) {
  60442. tempVec.x = jointPivot.x;
  60443. tempVec.y = jointPivot.y;
  60444. tempVec.z = jointPivot.z;
  60445. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  60446. if (distToJoint === undefined || distToJoint === null) {
  60447. distToJoint = jointPivot.length();
  60448. }
  60449. tempVec.x *= distToJoint;
  60450. tempVec.y *= distToJoint;
  60451. tempVec.z *= distToJoint;
  60452. }
  60453. if (bone.getParent()) {
  60454. tempVec.addInPlace(mesh.getAbsolutePosition());
  60455. bone.setAbsolutePosition(tempVec, boneMesh);
  60456. }
  60457. else {
  60458. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  60459. boneMesh.position.x -= tempVec.x;
  60460. boneMesh.position.y -= tempVec.y;
  60461. boneMesh.position.z -= tempVec.z;
  60462. }
  60463. };
  60464. /**
  60465. * Sync impostor to a bone
  60466. * @param bone The bone that the impostor will be synced to.
  60467. * @param boneMesh The mesh that the bone is influencing.
  60468. * @param jointPivot The pivot of the joint / bone in local space.
  60469. * @param distToJoint Optional distance from the impostor to the joint.
  60470. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  60471. * @param boneAxis Optional vector3 axis the bone is aligned with
  60472. */
  60473. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  60474. var mesh = this.object;
  60475. if (adjustRotation) {
  60476. var tempQuat = PhysicsImpostor._tmpQuat;
  60477. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  60478. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  60479. }
  60480. else {
  60481. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  60482. }
  60483. var pos = PhysicsImpostor._tmpVecs[0];
  60484. var boneDir = PhysicsImpostor._tmpVecs[1];
  60485. if (!boneAxis) {
  60486. boneAxis = PhysicsImpostor._tmpVecs[2];
  60487. boneAxis.x = 0;
  60488. boneAxis.y = 1;
  60489. boneAxis.z = 0;
  60490. }
  60491. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  60492. bone.getAbsolutePositionToRef(boneMesh, pos);
  60493. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  60494. distToJoint = jointPivot.length();
  60495. }
  60496. if (distToJoint !== undefined && distToJoint !== null) {
  60497. pos.x += boneDir.x * distToJoint;
  60498. pos.y += boneDir.y * distToJoint;
  60499. pos.z += boneDir.z * distToJoint;
  60500. }
  60501. mesh.setAbsolutePosition(pos);
  60502. };
  60503. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  60504. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  60505. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60506. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  60507. //Impostor types
  60508. PhysicsImpostor.NoImpostor = 0;
  60509. PhysicsImpostor.SphereImpostor = 1;
  60510. PhysicsImpostor.BoxImpostor = 2;
  60511. PhysicsImpostor.PlaneImpostor = 3;
  60512. PhysicsImpostor.MeshImpostor = 4;
  60513. PhysicsImpostor.CylinderImpostor = 7;
  60514. PhysicsImpostor.ParticleImpostor = 8;
  60515. PhysicsImpostor.HeightmapImpostor = 9;
  60516. return PhysicsImpostor;
  60517. }());
  60518. BABYLON.PhysicsImpostor = PhysicsImpostor;
  60519. })(BABYLON || (BABYLON = {}));
  60520. //# sourceMappingURL=babylon.physicsImpostor.js.map
  60521. var BABYLON;
  60522. (function (BABYLON) {
  60523. var PhysicsEngine = (function () {
  60524. function PhysicsEngine(gravity, _physicsPlugin) {
  60525. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  60526. this._physicsPlugin = _physicsPlugin;
  60527. //new methods and parameters
  60528. this._impostors = [];
  60529. this._joints = [];
  60530. if (!this._physicsPlugin.isSupported()) {
  60531. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  60532. + "Please make sure it is included.");
  60533. }
  60534. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  60535. this.setGravity(gravity);
  60536. this.setTimeStep();
  60537. }
  60538. PhysicsEngine.prototype.setGravity = function (gravity) {
  60539. this.gravity = gravity;
  60540. this._physicsPlugin.setGravity(this.gravity);
  60541. };
  60542. /**
  60543. * Set the time step of the physics engine.
  60544. * default is 1/60.
  60545. * To slow it down, enter 1/600 for example.
  60546. * To speed it up, 1/30
  60547. * @param {number} newTimeStep the new timestep to apply to this world.
  60548. */
  60549. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  60550. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  60551. this._physicsPlugin.setTimeStep(newTimeStep);
  60552. };
  60553. /**
  60554. * Get the time step of the physics engine.
  60555. */
  60556. PhysicsEngine.prototype.getTimeStep = function () {
  60557. return this._physicsPlugin.getTimeStep();
  60558. };
  60559. PhysicsEngine.prototype.dispose = function () {
  60560. this._impostors.forEach(function (impostor) {
  60561. impostor.dispose();
  60562. });
  60563. this._physicsPlugin.dispose();
  60564. };
  60565. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  60566. return this._physicsPlugin.name;
  60567. };
  60568. /**
  60569. * Adding a new impostor for the impostor tracking.
  60570. * This will be done by the impostor itself.
  60571. * @param {PhysicsImpostor} impostor the impostor to add
  60572. */
  60573. PhysicsEngine.prototype.addImpostor = function (impostor) {
  60574. impostor.uniqueId = this._impostors.push(impostor);
  60575. //if no parent, generate the body
  60576. if (!impostor.parent) {
  60577. this._physicsPlugin.generatePhysicsBody(impostor);
  60578. }
  60579. };
  60580. /**
  60581. * Remove an impostor from the engine.
  60582. * This impostor and its mesh will not longer be updated by the physics engine.
  60583. * @param {PhysicsImpostor} impostor the impostor to remove
  60584. */
  60585. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  60586. var index = this._impostors.indexOf(impostor);
  60587. if (index > -1) {
  60588. var removed = this._impostors.splice(index, 1);
  60589. //Is it needed?
  60590. if (removed.length) {
  60591. //this will also remove it from the world.
  60592. removed[0].physicsBody = null;
  60593. }
  60594. }
  60595. };
  60596. /**
  60597. * Add a joint to the physics engine
  60598. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  60599. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  60600. * @param {PhysicsJoint} the joint that will connect both impostors.
  60601. */
  60602. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  60603. var impostorJoint = {
  60604. mainImpostor: mainImpostor,
  60605. connectedImpostor: connectedImpostor,
  60606. joint: joint
  60607. };
  60608. joint.physicsPlugin = this._physicsPlugin;
  60609. this._joints.push(impostorJoint);
  60610. this._physicsPlugin.generateJoint(impostorJoint);
  60611. };
  60612. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  60613. var matchingJoints = this._joints.filter(function (impostorJoint) {
  60614. return (impostorJoint.connectedImpostor === connectedImpostor
  60615. && impostorJoint.joint === joint
  60616. && impostorJoint.mainImpostor === mainImpostor);
  60617. });
  60618. if (matchingJoints.length) {
  60619. this._physicsPlugin.removeJoint(matchingJoints[0]);
  60620. //TODO remove it from the list as well
  60621. }
  60622. };
  60623. /**
  60624. * Called by the scene. no need to call it.
  60625. */
  60626. PhysicsEngine.prototype._step = function (delta) {
  60627. var _this = this;
  60628. //check if any mesh has no body / requires an update
  60629. this._impostors.forEach(function (impostor) {
  60630. if (impostor.isBodyInitRequired()) {
  60631. _this._physicsPlugin.generatePhysicsBody(impostor);
  60632. }
  60633. });
  60634. if (delta > 0.1) {
  60635. delta = 0.1;
  60636. }
  60637. else if (delta <= 0) {
  60638. delta = 1.0 / 60.0;
  60639. }
  60640. this._physicsPlugin.executeStep(delta, this._impostors);
  60641. };
  60642. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  60643. return this._physicsPlugin;
  60644. };
  60645. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  60646. for (var i = 0; i < this._impostors.length; ++i) {
  60647. if (this._impostors[i].object === object) {
  60648. return this._impostors[i];
  60649. }
  60650. }
  60651. };
  60652. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  60653. for (var i = 0; i < this._impostors.length; ++i) {
  60654. if (this._impostors[i].physicsBody === body) {
  60655. return this._impostors[i];
  60656. }
  60657. }
  60658. };
  60659. // Statics
  60660. PhysicsEngine.Epsilon = 0.001;
  60661. return PhysicsEngine;
  60662. }());
  60663. BABYLON.PhysicsEngine = PhysicsEngine;
  60664. })(BABYLON || (BABYLON = {}));
  60665. //# sourceMappingURL=babylon.physicsEngine.js.map
  60666. var BABYLON;
  60667. (function (BABYLON) {
  60668. var CannonJSPlugin = (function () {
  60669. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  60670. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  60671. if (iterations === void 0) { iterations = 10; }
  60672. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  60673. this.name = "CannonJSPlugin";
  60674. this._physicsMaterials = [];
  60675. this._fixedTimeStep = 1 / 60;
  60676. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60677. this._currentCollisionGroup = 2;
  60678. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  60679. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  60680. this._tmpPosition = BABYLON.Vector3.Zero();
  60681. this._tmpQuaternion = new BABYLON.Quaternion();
  60682. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  60683. this._tmpDeltaRotation = new BABYLON.Quaternion();
  60684. this._tmpUnityRotation = new BABYLON.Quaternion();
  60685. if (!this.isSupported()) {
  60686. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  60687. return;
  60688. }
  60689. this.world = new CANNON.World();
  60690. this.world.broadphase = new CANNON.NaiveBroadphase();
  60691. this.world.solver.iterations = iterations;
  60692. }
  60693. CannonJSPlugin.prototype.setGravity = function (gravity) {
  60694. this.world.gravity.copy(gravity);
  60695. };
  60696. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  60697. this._fixedTimeStep = timeStep;
  60698. };
  60699. CannonJSPlugin.prototype.getTimeStep = function () {
  60700. return this._fixedTimeStep;
  60701. };
  60702. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  60703. // Delta is in seconds, should be provided in milliseconds
  60704. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  60705. };
  60706. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  60707. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60708. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  60709. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  60710. };
  60711. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  60712. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60713. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  60714. impostor.physicsBody.applyForce(impulse, worldPoint);
  60715. };
  60716. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  60717. //parent-child relationship. Does this impostor has a parent impostor?
  60718. if (impostor.parent) {
  60719. if (impostor.physicsBody) {
  60720. this.removePhysicsBody(impostor);
  60721. //TODO is that needed?
  60722. impostor.forceUpdate();
  60723. }
  60724. return;
  60725. }
  60726. //should a new body be created for this impostor?
  60727. if (impostor.isBodyInitRequired()) {
  60728. var shape = this._createShape(impostor);
  60729. //unregister events, if body is being changed
  60730. var oldBody = impostor.physicsBody;
  60731. if (oldBody) {
  60732. this.removePhysicsBody(impostor);
  60733. }
  60734. //create the body and material
  60735. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  60736. var bodyCreationObject = {
  60737. mass: impostor.getParam("mass"),
  60738. material: material
  60739. };
  60740. // A simple extend, in case native options were used.
  60741. var nativeOptions = impostor.getParam("nativeOptions");
  60742. for (var key in nativeOptions) {
  60743. if (nativeOptions.hasOwnProperty(key)) {
  60744. bodyCreationObject[key] = nativeOptions[key];
  60745. }
  60746. }
  60747. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  60748. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  60749. this.world.addEventListener("preStep", impostor.beforeStep);
  60750. this.world.addEventListener("postStep", impostor.afterStep);
  60751. impostor.physicsBody.addShape(shape);
  60752. this.world.add(impostor.physicsBody);
  60753. //try to keep the body moving in the right direction by taking old properties.
  60754. //Should be tested!
  60755. if (oldBody) {
  60756. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  60757. impostor.physicsBody[param].copy(oldBody[param]);
  60758. });
  60759. }
  60760. this._processChildMeshes(impostor);
  60761. }
  60762. //now update the body's transformation
  60763. this._updatePhysicsBodyTransformation(impostor);
  60764. };
  60765. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  60766. var _this = this;
  60767. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  60768. if (meshChildren.length) {
  60769. var processMesh = function (localPosition, mesh) {
  60770. var childImpostor = mesh.getPhysicsImpostor();
  60771. if (childImpostor) {
  60772. var parent = childImpostor.parent;
  60773. if (parent !== mainImpostor) {
  60774. var localPosition = mesh.position;
  60775. if (childImpostor.physicsBody) {
  60776. _this.removePhysicsBody(childImpostor);
  60777. childImpostor.physicsBody = null;
  60778. }
  60779. childImpostor.parent = mainImpostor;
  60780. childImpostor.resetUpdateFlags();
  60781. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  60782. //Add the mass of the children.
  60783. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  60784. }
  60785. }
  60786. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  60787. };
  60788. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  60789. }
  60790. };
  60791. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  60792. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  60793. this.world.removeEventListener("preStep", impostor.beforeStep);
  60794. this.world.removeEventListener("postStep", impostor.afterStep);
  60795. this.world.remove(impostor.physicsBody);
  60796. };
  60797. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  60798. var mainBody = impostorJoint.mainImpostor.physicsBody;
  60799. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  60800. if (!mainBody || !connectedBody) {
  60801. return;
  60802. }
  60803. var constraint;
  60804. var jointData = impostorJoint.joint.jointData;
  60805. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60806. var constraintData = {
  60807. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  60808. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  60809. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  60810. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  60811. maxForce: jointData.nativeParams.maxForce,
  60812. collideConnected: !!jointData.collision
  60813. };
  60814. switch (impostorJoint.joint.type) {
  60815. case BABYLON.PhysicsJoint.HingeJoint:
  60816. case BABYLON.PhysicsJoint.Hinge2Joint:
  60817. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  60818. break;
  60819. case BABYLON.PhysicsJoint.DistanceJoint:
  60820. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  60821. break;
  60822. case BABYLON.PhysicsJoint.SpringJoint:
  60823. var springData = jointData;
  60824. constraint = new CANNON.Spring(mainBody, connectedBody, {
  60825. restLength: springData.length,
  60826. stiffness: springData.stiffness,
  60827. damping: springData.damping,
  60828. localAnchorA: constraintData.pivotA,
  60829. localAnchorB: constraintData.pivotB
  60830. });
  60831. break;
  60832. case BABYLON.PhysicsJoint.LockJoint:
  60833. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  60834. break;
  60835. case BABYLON.PhysicsJoint.PointToPointJoint:
  60836. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  60837. default:
  60838. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  60839. break;
  60840. }
  60841. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  60842. constraint.collideConnected = !!jointData.collision;
  60843. impostorJoint.joint.physicsJoint = constraint;
  60844. //don't add spring as constraint, as it is not one.
  60845. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  60846. this.world.addConstraint(constraint);
  60847. }
  60848. else {
  60849. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  60850. constraint.applyForce();
  60851. });
  60852. }
  60853. };
  60854. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  60855. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  60856. };
  60857. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  60858. var index;
  60859. var mat;
  60860. for (index = 0; index < this._physicsMaterials.length; index++) {
  60861. mat = this._physicsMaterials[index];
  60862. if (mat.friction === friction && mat.restitution === restitution) {
  60863. return mat;
  60864. }
  60865. }
  60866. var currentMat = new CANNON.Material(name);
  60867. currentMat.friction = friction;
  60868. currentMat.restitution = restitution;
  60869. this._physicsMaterials.push(currentMat);
  60870. return currentMat;
  60871. };
  60872. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  60873. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  60874. };
  60875. CannonJSPlugin.prototype._createShape = function (impostor) {
  60876. var object = impostor.object;
  60877. var returnValue;
  60878. var extendSize = impostor.getObjectExtendSize();
  60879. switch (impostor.type) {
  60880. case BABYLON.PhysicsImpostor.SphereImpostor:
  60881. var radiusX = extendSize.x;
  60882. var radiusY = extendSize.y;
  60883. var radiusZ = extendSize.z;
  60884. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  60885. break;
  60886. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  60887. case BABYLON.PhysicsImpostor.CylinderImpostor:
  60888. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  60889. break;
  60890. case BABYLON.PhysicsImpostor.BoxImpostor:
  60891. var box = extendSize.scale(0.5);
  60892. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  60893. break;
  60894. case BABYLON.PhysicsImpostor.PlaneImpostor:
  60895. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  60896. returnValue = new CANNON.Plane();
  60897. break;
  60898. case BABYLON.PhysicsImpostor.MeshImpostor:
  60899. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  60900. var rawFaces = object.getIndices ? object.getIndices() : [];
  60901. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  60902. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  60903. break;
  60904. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  60905. returnValue = this._createHeightmap(object);
  60906. break;
  60907. case BABYLON.PhysicsImpostor.ParticleImpostor:
  60908. returnValue = new CANNON.Particle();
  60909. break;
  60910. }
  60911. return returnValue;
  60912. };
  60913. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  60914. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60915. var matrix = [];
  60916. //For now pointDepth will not be used and will be automatically calculated.
  60917. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  60918. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  60919. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  60920. var elementSize = dim * 2 / arraySize;
  60921. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  60922. for (var i = 0; i < pos.length; i = i + 3) {
  60923. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  60924. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  60925. var y = pos[i + 1] + minY;
  60926. if (!matrix[x]) {
  60927. matrix[x] = [];
  60928. }
  60929. if (!matrix[x][z]) {
  60930. matrix[x][z] = y;
  60931. }
  60932. matrix[x][z] = Math.max(y, matrix[x][z]);
  60933. }
  60934. for (var x = 0; x <= arraySize; ++x) {
  60935. if (!matrix[x]) {
  60936. var loc = 1;
  60937. while (!matrix[(x + loc) % arraySize]) {
  60938. loc++;
  60939. }
  60940. matrix[x] = matrix[(x + loc) % arraySize].slice();
  60941. //console.log("missing x", x);
  60942. }
  60943. for (var z = 0; z <= arraySize; ++z) {
  60944. if (!matrix[x][z]) {
  60945. var loc = 1;
  60946. var newValue;
  60947. while (newValue === undefined) {
  60948. newValue = matrix[x][(z + loc++) % arraySize];
  60949. }
  60950. matrix[x][z] = newValue;
  60951. }
  60952. }
  60953. }
  60954. var shape = new CANNON.Heightfield(matrix, {
  60955. elementSize: elementSize
  60956. });
  60957. //For future reference, needed for body transformation
  60958. shape.minY = minY;
  60959. return shape;
  60960. };
  60961. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  60962. var object = impostor.object;
  60963. //make sure it is updated...
  60964. object.computeWorldMatrix && object.computeWorldMatrix(true);
  60965. // The delta between the mesh position and the mesh bounding box center
  60966. var center = impostor.getObjectCenter();
  60967. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  60968. this._tmpPosition.copyFrom(center);
  60969. var quaternion = object.rotationQuaternion;
  60970. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  60971. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  60972. //-90 DEG in X, precalculated
  60973. quaternion = quaternion.multiply(this._minus90X);
  60974. //Invert! (Precalculated, 90 deg in X)
  60975. //No need to clone. this will never change.
  60976. impostor.setDeltaRotation(this._plus90X);
  60977. }
  60978. //If it is a heightfield, if should be centered.
  60979. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  60980. var mesh = object;
  60981. //calculate the correct body position:
  60982. var rotationQuaternion = mesh.rotationQuaternion;
  60983. mesh.rotationQuaternion = this._tmpUnityRotation;
  60984. mesh.computeWorldMatrix(true);
  60985. //get original center with no rotation
  60986. var c = center.clone();
  60987. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  60988. //rotation is back
  60989. mesh.rotationQuaternion = rotationQuaternion;
  60990. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  60991. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  60992. mesh.setPivotMatrix(p);
  60993. mesh.computeWorldMatrix(true);
  60994. //calculate the translation
  60995. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  60996. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  60997. //add it inverted to the delta
  60998. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  60999. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  61000. mesh.setPivotMatrix(oldPivot);
  61001. mesh.computeWorldMatrix(true);
  61002. }
  61003. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  61004. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  61005. this._tmpPosition.copyFrom(object.position);
  61006. }
  61007. impostor.setDeltaPosition(this._tmpDeltaPosition);
  61008. //Now update the impostor object
  61009. impostor.physicsBody.position.copy(this._tmpPosition);
  61010. impostor.physicsBody.quaternion.copy(quaternion);
  61011. };
  61012. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  61013. impostor.object.position.copyFrom(impostor.physicsBody.position);
  61014. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  61015. };
  61016. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  61017. impostor.physicsBody.position.copy(newPosition);
  61018. impostor.physicsBody.quaternion.copy(newRotation);
  61019. };
  61020. CannonJSPlugin.prototype.isSupported = function () {
  61021. return window.CANNON !== undefined;
  61022. };
  61023. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  61024. impostor.physicsBody.velocity.copy(velocity);
  61025. };
  61026. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  61027. impostor.physicsBody.angularVelocity.copy(velocity);
  61028. };
  61029. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  61030. var v = impostor.physicsBody.velocity;
  61031. if (!v)
  61032. return null;
  61033. return new BABYLON.Vector3(v.x, v.y, v.z);
  61034. };
  61035. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61036. var v = impostor.physicsBody.angularVelocity;
  61037. if (!v)
  61038. return null;
  61039. return new BABYLON.Vector3(v.x, v.y, v.z);
  61040. };
  61041. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  61042. impostor.physicsBody.mass = mass;
  61043. impostor.physicsBody.updateMassProperties();
  61044. };
  61045. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  61046. return impostor.physicsBody.mass;
  61047. };
  61048. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  61049. return impostor.physicsBody.material.friction;
  61050. };
  61051. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  61052. impostor.physicsBody.material.friction = friction;
  61053. };
  61054. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  61055. return impostor.physicsBody.material.restitution;
  61056. };
  61057. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  61058. impostor.physicsBody.material.restitution = restitution;
  61059. };
  61060. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  61061. impostor.physicsBody.sleep();
  61062. };
  61063. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  61064. impostor.physicsBody.wakeUp();
  61065. };
  61066. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  61067. joint.physicsJoint.distance = maxDistance;
  61068. };
  61069. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  61070. if (!motorIndex) {
  61071. joint.physicsJoint.enableMotor();
  61072. }
  61073. };
  61074. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  61075. if (!motorIndex) {
  61076. joint.physicsJoint.disableMotor();
  61077. }
  61078. };
  61079. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  61080. if (!motorIndex) {
  61081. joint.physicsJoint.enableMotor();
  61082. joint.physicsJoint.setMotorSpeed(speed);
  61083. if (maxForce) {
  61084. this.setLimit(joint, maxForce);
  61085. }
  61086. }
  61087. };
  61088. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  61089. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  61090. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  61091. };
  61092. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  61093. var body = impostor.physicsBody;
  61094. mesh.position.x = body.position.x;
  61095. mesh.position.y = body.position.y;
  61096. mesh.position.z = body.position.z;
  61097. mesh.rotationQuaternion.x = body.quaternion.x;
  61098. mesh.rotationQuaternion.y = body.quaternion.y;
  61099. mesh.rotationQuaternion.z = body.quaternion.z;
  61100. mesh.rotationQuaternion.w = body.quaternion.w;
  61101. };
  61102. CannonJSPlugin.prototype.getRadius = function (impostor) {
  61103. var shape = impostor.physicsBody.shapes[0];
  61104. return shape.boundingSphereRadius;
  61105. };
  61106. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  61107. var shape = impostor.physicsBody.shapes[0];
  61108. result.x = shape.halfExtents.x * 2;
  61109. result.y = shape.halfExtents.y * 2;
  61110. result.z = shape.halfExtents.z * 2;
  61111. };
  61112. CannonJSPlugin.prototype.dispose = function () {
  61113. };
  61114. return CannonJSPlugin;
  61115. }());
  61116. BABYLON.CannonJSPlugin = CannonJSPlugin;
  61117. })(BABYLON || (BABYLON = {}));
  61118. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  61119. var BABYLON;
  61120. (function (BABYLON) {
  61121. var OimoJSPlugin = (function () {
  61122. function OimoJSPlugin(iterations) {
  61123. this.name = "OimoJSPlugin";
  61124. this._tmpImpostorsArray = [];
  61125. this._tmpPositionVector = BABYLON.Vector3.Zero();
  61126. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  61127. this.world.worldscale(1);
  61128. this.world.clear();
  61129. //making sure no stats are calculated
  61130. this.world.isNoStat = true;
  61131. }
  61132. OimoJSPlugin.prototype.setGravity = function (gravity) {
  61133. this.world.gravity.copy(gravity);
  61134. };
  61135. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  61136. this.world.timeStep = timeStep;
  61137. };
  61138. OimoJSPlugin.prototype.getTimeStep = function () {
  61139. return this.world.timeStep;
  61140. };
  61141. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  61142. var _this = this;
  61143. impostors.forEach(function (impostor) {
  61144. impostor.beforeStep();
  61145. });
  61146. this.world.step();
  61147. impostors.forEach(function (impostor) {
  61148. impostor.afterStep();
  61149. //update the ordered impostors array
  61150. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  61151. });
  61152. //check for collisions
  61153. var contact = this.world.contacts;
  61154. while (contact !== null) {
  61155. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  61156. contact = contact.next;
  61157. continue;
  61158. }
  61159. //is this body colliding with any other? get the impostor
  61160. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  61161. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  61162. if (!mainImpostor || !collidingImpostor) {
  61163. contact = contact.next;
  61164. continue;
  61165. }
  61166. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  61167. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  61168. contact = contact.next;
  61169. }
  61170. };
  61171. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  61172. var mass = impostor.physicsBody.massInfo.mass;
  61173. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  61174. };
  61175. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  61176. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  61177. this.applyImpulse(impostor, force, contactPoint);
  61178. };
  61179. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  61180. var _this = this;
  61181. //parent-child relationship. Does this impostor has a parent impostor?
  61182. if (impostor.parent) {
  61183. if (impostor.physicsBody) {
  61184. this.removePhysicsBody(impostor);
  61185. //TODO is that needed?
  61186. impostor.forceUpdate();
  61187. }
  61188. return;
  61189. }
  61190. if (impostor.isBodyInitRequired()) {
  61191. var bodyConfig = {
  61192. name: impostor.uniqueId,
  61193. //Oimo must have mass, also for static objects.
  61194. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  61195. size: [],
  61196. type: [],
  61197. pos: [],
  61198. rot: [],
  61199. move: impostor.getParam("mass") !== 0,
  61200. //Supporting older versions of Oimo
  61201. world: this.world
  61202. };
  61203. var impostors = [impostor];
  61204. var addToArray = function (parent) {
  61205. if (!parent.getChildMeshes)
  61206. return;
  61207. parent.getChildMeshes().forEach(function (m) {
  61208. if (m.physicsImpostor) {
  61209. impostors.push(m.physicsImpostor);
  61210. m.physicsImpostor._init();
  61211. }
  61212. });
  61213. };
  61214. addToArray(impostor.object);
  61215. var checkWithEpsilon_1 = function (value) {
  61216. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  61217. };
  61218. impostors.forEach(function (i) {
  61219. //get the correct bounding box
  61220. var oldQuaternion = i.object.rotationQuaternion;
  61221. var rot = new OIMO.Euler().setFromQuaternion({
  61222. x: impostor.object.rotationQuaternion.x,
  61223. y: impostor.object.rotationQuaternion.y,
  61224. z: impostor.object.rotationQuaternion.z,
  61225. s: impostor.object.rotationQuaternion.w
  61226. });
  61227. var extendSize = i.getObjectExtendSize();
  61228. if (i === impostor) {
  61229. var center = impostor.getObjectCenter();
  61230. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  61231. //Can also use Array.prototype.push.apply
  61232. bodyConfig.pos.push(center.x);
  61233. bodyConfig.pos.push(center.y);
  61234. bodyConfig.pos.push(center.z);
  61235. //tmp solution
  61236. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  61237. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  61238. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  61239. }
  61240. else {
  61241. bodyConfig.pos.push(i.object.position.x);
  61242. bodyConfig.pos.push(i.object.position.y);
  61243. bodyConfig.pos.push(i.object.position.z);
  61244. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  61245. bodyConfig.rot.push(0);
  61246. bodyConfig.rot.push(0);
  61247. bodyConfig.rot.push(0);
  61248. }
  61249. // register mesh
  61250. switch (i.type) {
  61251. case BABYLON.PhysicsImpostor.ParticleImpostor:
  61252. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  61253. case BABYLON.PhysicsImpostor.SphereImpostor:
  61254. var radiusX = extendSize.x;
  61255. var radiusY = extendSize.y;
  61256. var radiusZ = extendSize.z;
  61257. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  61258. bodyConfig.type.push('sphere');
  61259. //due to the way oimo works with compounds, add 3 times
  61260. bodyConfig.size.push(size);
  61261. bodyConfig.size.push(size);
  61262. bodyConfig.size.push(size);
  61263. break;
  61264. case BABYLON.PhysicsImpostor.CylinderImpostor:
  61265. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  61266. var sizeY = checkWithEpsilon_1(extendSize.y);
  61267. bodyConfig.type.push('cylinder');
  61268. bodyConfig.size.push(sizeX);
  61269. bodyConfig.size.push(sizeY);
  61270. //due to the way oimo works with compounds, add one more value.
  61271. bodyConfig.size.push(sizeY);
  61272. break;
  61273. case BABYLON.PhysicsImpostor.PlaneImpostor:
  61274. case BABYLON.PhysicsImpostor.BoxImpostor:
  61275. default:
  61276. var sizeX = checkWithEpsilon_1(extendSize.x);
  61277. var sizeY = checkWithEpsilon_1(extendSize.y);
  61278. var sizeZ = checkWithEpsilon_1(extendSize.z);
  61279. bodyConfig.type.push('box');
  61280. bodyConfig.size.push(sizeX);
  61281. bodyConfig.size.push(sizeY);
  61282. bodyConfig.size.push(sizeZ);
  61283. break;
  61284. }
  61285. //actually not needed, but hey...
  61286. i.object.rotationQuaternion = oldQuaternion;
  61287. });
  61288. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  61289. }
  61290. else {
  61291. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  61292. }
  61293. impostor.setDeltaPosition(this._tmpPositionVector);
  61294. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  61295. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  61296. };
  61297. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  61298. //impostor.physicsBody.dispose();
  61299. //Same as : (older oimo versions)
  61300. this.world.removeRigidBody(impostor.physicsBody);
  61301. };
  61302. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  61303. var mainBody = impostorJoint.mainImpostor.physicsBody;
  61304. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  61305. if (!mainBody || !connectedBody) {
  61306. return;
  61307. }
  61308. var jointData = impostorJoint.joint.jointData;
  61309. var options = jointData.nativeParams || {};
  61310. var type;
  61311. var nativeJointData = {
  61312. body1: mainBody,
  61313. body2: connectedBody,
  61314. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  61315. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  61316. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  61317. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  61318. min: options.min,
  61319. max: options.max,
  61320. collision: options.collision || jointData.collision,
  61321. spring: options.spring,
  61322. //supporting older version of Oimo
  61323. world: this.world
  61324. };
  61325. switch (impostorJoint.joint.type) {
  61326. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  61327. type = "jointBall";
  61328. break;
  61329. case BABYLON.PhysicsJoint.SpringJoint:
  61330. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  61331. var springData = jointData;
  61332. nativeJointData.min = springData.length || nativeJointData.min;
  61333. //Max should also be set, just make sure it is at least min
  61334. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  61335. case BABYLON.PhysicsJoint.DistanceJoint:
  61336. type = "jointDistance";
  61337. nativeJointData.max = jointData.maxDistance;
  61338. break;
  61339. case BABYLON.PhysicsJoint.PrismaticJoint:
  61340. type = "jointPrisme";
  61341. break;
  61342. case BABYLON.PhysicsJoint.SliderJoint:
  61343. type = "jointSlide";
  61344. break;
  61345. case BABYLON.PhysicsJoint.WheelJoint:
  61346. type = "jointWheel";
  61347. break;
  61348. case BABYLON.PhysicsJoint.HingeJoint:
  61349. default:
  61350. type = "jointHinge";
  61351. break;
  61352. }
  61353. nativeJointData.type = type;
  61354. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  61355. };
  61356. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  61357. //Bug in Oimo prevents us from disposing a joint in the playground
  61358. //joint.joint.physicsJoint.dispose();
  61359. //So we will bruteforce it!
  61360. try {
  61361. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  61362. }
  61363. catch (e) {
  61364. BABYLON.Tools.Warn(e);
  61365. }
  61366. };
  61367. OimoJSPlugin.prototype.isSupported = function () {
  61368. return OIMO !== undefined;
  61369. };
  61370. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  61371. if (!impostor.physicsBody.sleeping) {
  61372. //TODO check that
  61373. if (impostor.physicsBody.shapes.next) {
  61374. var parentShape = this._getLastShape(impostor.physicsBody);
  61375. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  61376. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  61377. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  61378. }
  61379. else {
  61380. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  61381. }
  61382. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  61383. impostor.object.rotationQuaternion.normalize();
  61384. }
  61385. };
  61386. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  61387. var body = impostor.physicsBody;
  61388. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  61389. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  61390. body.syncShapes();
  61391. body.awake();
  61392. };
  61393. OimoJSPlugin.prototype._getLastShape = function (body) {
  61394. var lastShape = body.shapes;
  61395. while (lastShape.next) {
  61396. lastShape = lastShape.next;
  61397. }
  61398. return lastShape;
  61399. };
  61400. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  61401. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  61402. };
  61403. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  61404. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  61405. };
  61406. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  61407. var v = impostor.physicsBody.linearVelocity;
  61408. if (!v)
  61409. return null;
  61410. return new BABYLON.Vector3(v.x, v.y, v.z);
  61411. };
  61412. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61413. var v = impostor.physicsBody.angularVelocity;
  61414. if (!v)
  61415. return null;
  61416. return new BABYLON.Vector3(v.x, v.y, v.z);
  61417. };
  61418. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  61419. var staticBody = mass === 0;
  61420. //this will actually set the body's density and not its mass.
  61421. //But this is how oimo treats the mass variable.
  61422. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  61423. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  61424. };
  61425. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  61426. return impostor.physicsBody.shapes.density;
  61427. };
  61428. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  61429. return impostor.physicsBody.shapes.friction;
  61430. };
  61431. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  61432. impostor.physicsBody.shapes.friction = friction;
  61433. };
  61434. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  61435. return impostor.physicsBody.shapes.restitution;
  61436. };
  61437. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  61438. impostor.physicsBody.shapes.restitution = restitution;
  61439. };
  61440. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  61441. impostor.physicsBody.sleep();
  61442. };
  61443. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  61444. impostor.physicsBody.awake();
  61445. };
  61446. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  61447. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  61448. if (minDistance !== void 0) {
  61449. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  61450. }
  61451. };
  61452. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  61453. //TODO separate rotational and transational motors.
  61454. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  61455. if (motor) {
  61456. motor.setMotor(speed, maxForce);
  61457. }
  61458. };
  61459. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  61460. //TODO separate rotational and transational motors.
  61461. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  61462. if (motor) {
  61463. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  61464. }
  61465. };
  61466. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  61467. var body = impostor.physicsBody;
  61468. mesh.position.x = body.position.x;
  61469. mesh.position.y = body.position.y;
  61470. mesh.position.z = body.position.z;
  61471. mesh.rotationQuaternion.x = body.orientation.x;
  61472. mesh.rotationQuaternion.y = body.orientation.y;
  61473. mesh.rotationQuaternion.z = body.orientation.z;
  61474. mesh.rotationQuaternion.w = body.orientation.s;
  61475. };
  61476. OimoJSPlugin.prototype.getRadius = function (impostor) {
  61477. return impostor.physicsBody.shapes.radius;
  61478. };
  61479. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  61480. var shape = impostor.physicsBody.shapes;
  61481. result.x = shape.halfWidth * 2;
  61482. result.y = shape.halfHeight * 2;
  61483. result.z = shape.halfDepth * 2;
  61484. };
  61485. OimoJSPlugin.prototype.dispose = function () {
  61486. this.world.clear();
  61487. };
  61488. return OimoJSPlugin;
  61489. }());
  61490. BABYLON.OimoJSPlugin = OimoJSPlugin;
  61491. })(BABYLON || (BABYLON = {}));
  61492. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  61493. var BABYLON;
  61494. (function (BABYLON) {
  61495. var Internals;
  61496. (function (Internals) {
  61497. /*
  61498. * Based on jsTGALoader - Javascript loader for TGA file
  61499. * By Vincent Thibault
  61500. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  61501. */
  61502. var TGATools = (function () {
  61503. function TGATools() {
  61504. }
  61505. TGATools.GetTGAHeader = function (data) {
  61506. var offset = 0;
  61507. var header = {
  61508. id_length: data[offset++],
  61509. colormap_type: data[offset++],
  61510. image_type: data[offset++],
  61511. colormap_index: data[offset++] | data[offset++] << 8,
  61512. colormap_length: data[offset++] | data[offset++] << 8,
  61513. colormap_size: data[offset++],
  61514. origin: [
  61515. data[offset++] | data[offset++] << 8,
  61516. data[offset++] | data[offset++] << 8
  61517. ],
  61518. width: data[offset++] | data[offset++] << 8,
  61519. height: data[offset++] | data[offset++] << 8,
  61520. pixel_size: data[offset++],
  61521. flags: data[offset++]
  61522. };
  61523. return header;
  61524. };
  61525. TGATools.UploadContent = function (gl, data) {
  61526. // Not enough data to contain header ?
  61527. if (data.length < 19) {
  61528. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  61529. return;
  61530. }
  61531. // Read Header
  61532. var offset = 18;
  61533. var header = TGATools.GetTGAHeader(data);
  61534. // Assume it's a valid Targa file.
  61535. if (header.id_length + offset > data.length) {
  61536. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  61537. return;
  61538. }
  61539. // Skip not needed data
  61540. offset += header.id_length;
  61541. var use_rle = false;
  61542. var use_pal = false;
  61543. var use_rgb = false;
  61544. var use_grey = false;
  61545. // Get some informations.
  61546. switch (header.image_type) {
  61547. case TGATools._TYPE_RLE_INDEXED:
  61548. use_rle = true;
  61549. case TGATools._TYPE_INDEXED:
  61550. use_pal = true;
  61551. break;
  61552. case TGATools._TYPE_RLE_RGB:
  61553. use_rle = true;
  61554. case TGATools._TYPE_RGB:
  61555. use_rgb = true;
  61556. break;
  61557. case TGATools._TYPE_RLE_GREY:
  61558. use_rle = true;
  61559. case TGATools._TYPE_GREY:
  61560. use_grey = true;
  61561. break;
  61562. }
  61563. var pixel_data;
  61564. var numAlphaBits = header.flags & 0xf;
  61565. var pixel_size = header.pixel_size >> 3;
  61566. var pixel_total = header.width * header.height * pixel_size;
  61567. // Read palettes
  61568. var palettes;
  61569. if (use_pal) {
  61570. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  61571. }
  61572. // Read LRE
  61573. if (use_rle) {
  61574. pixel_data = new Uint8Array(pixel_total);
  61575. var c, count, i;
  61576. var localOffset = 0;
  61577. var pixels = new Uint8Array(pixel_size);
  61578. while (offset < pixel_total && localOffset < pixel_total) {
  61579. c = data[offset++];
  61580. count = (c & 0x7f) + 1;
  61581. // RLE pixels
  61582. if (c & 0x80) {
  61583. // Bind pixel tmp array
  61584. for (i = 0; i < pixel_size; ++i) {
  61585. pixels[i] = data[offset++];
  61586. }
  61587. // Copy pixel array
  61588. for (i = 0; i < count; ++i) {
  61589. pixel_data.set(pixels, localOffset + i * pixel_size);
  61590. }
  61591. localOffset += pixel_size * count;
  61592. }
  61593. else {
  61594. count *= pixel_size;
  61595. for (i = 0; i < count; ++i) {
  61596. pixel_data[localOffset + i] = data[offset++];
  61597. }
  61598. localOffset += count;
  61599. }
  61600. }
  61601. }
  61602. else {
  61603. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  61604. }
  61605. // Load to texture
  61606. var x_start, y_start, x_step, y_step, y_end, x_end;
  61607. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  61608. default:
  61609. case TGATools._ORIGIN_UL:
  61610. x_start = 0;
  61611. x_step = 1;
  61612. x_end = header.width;
  61613. y_start = 0;
  61614. y_step = 1;
  61615. y_end = header.height;
  61616. break;
  61617. case TGATools._ORIGIN_BL:
  61618. x_start = 0;
  61619. x_step = 1;
  61620. x_end = header.width;
  61621. y_start = header.height - 1;
  61622. y_step = -1;
  61623. y_end = -1;
  61624. break;
  61625. case TGATools._ORIGIN_UR:
  61626. x_start = header.width - 1;
  61627. x_step = -1;
  61628. x_end = -1;
  61629. y_start = 0;
  61630. y_step = 1;
  61631. y_end = header.height;
  61632. break;
  61633. case TGATools._ORIGIN_BR:
  61634. x_start = header.width - 1;
  61635. x_step = -1;
  61636. x_end = -1;
  61637. y_start = header.height - 1;
  61638. y_step = -1;
  61639. y_end = -1;
  61640. break;
  61641. }
  61642. // Load the specify method
  61643. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  61644. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  61645. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  61646. };
  61647. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61648. var image = pixel_data, colormap = palettes;
  61649. var width = header.width, height = header.height;
  61650. var color, i = 0, x, y;
  61651. var imageData = new Uint8Array(width * height * 4);
  61652. for (y = y_start; y !== y_end; y += y_step) {
  61653. for (x = x_start; x !== x_end; x += x_step, i++) {
  61654. color = image[i];
  61655. imageData[(x + width * y) * 4 + 3] = 255;
  61656. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  61657. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  61658. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  61659. }
  61660. }
  61661. return imageData;
  61662. };
  61663. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61664. var image = pixel_data;
  61665. var width = header.width, height = header.height;
  61666. var color, i = 0, x, y;
  61667. var imageData = new Uint8Array(width * height * 4);
  61668. for (y = y_start; y !== y_end; y += y_step) {
  61669. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  61670. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  61671. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  61672. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  61673. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  61674. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  61675. }
  61676. }
  61677. return imageData;
  61678. };
  61679. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61680. var image = pixel_data;
  61681. var width = header.width, height = header.height;
  61682. var i = 0, x, y;
  61683. var imageData = new Uint8Array(width * height * 4);
  61684. for (y = y_start; y !== y_end; y += y_step) {
  61685. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  61686. imageData[(x + width * y) * 4 + 3] = 255;
  61687. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61688. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  61689. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  61690. }
  61691. }
  61692. return imageData;
  61693. };
  61694. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61695. var image = pixel_data;
  61696. var width = header.width, height = header.height;
  61697. var i = 0, x, y;
  61698. var imageData = new Uint8Array(width * height * 4);
  61699. for (y = y_start; y !== y_end; y += y_step) {
  61700. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  61701. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61702. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  61703. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  61704. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  61705. }
  61706. }
  61707. return imageData;
  61708. };
  61709. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61710. var image = pixel_data;
  61711. var width = header.width, height = header.height;
  61712. var color, i = 0, x, y;
  61713. var imageData = new Uint8Array(width * height * 4);
  61714. for (y = y_start; y !== y_end; y += y_step) {
  61715. for (x = x_start; x !== x_end; x += x_step, i++) {
  61716. color = image[i];
  61717. imageData[(x + width * y) * 4 + 0] = color;
  61718. imageData[(x + width * y) * 4 + 1] = color;
  61719. imageData[(x + width * y) * 4 + 2] = color;
  61720. imageData[(x + width * y) * 4 + 3] = 255;
  61721. }
  61722. }
  61723. return imageData;
  61724. };
  61725. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61726. var image = pixel_data;
  61727. var width = header.width, height = header.height;
  61728. var i = 0, x, y;
  61729. var imageData = new Uint8Array(width * height * 4);
  61730. for (y = y_start; y !== y_end; y += y_step) {
  61731. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  61732. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  61733. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  61734. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61735. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  61736. }
  61737. }
  61738. return imageData;
  61739. };
  61740. TGATools._TYPE_NO_DATA = 0;
  61741. TGATools._TYPE_INDEXED = 1;
  61742. TGATools._TYPE_RGB = 2;
  61743. TGATools._TYPE_GREY = 3;
  61744. TGATools._TYPE_RLE_INDEXED = 9;
  61745. TGATools._TYPE_RLE_RGB = 10;
  61746. TGATools._TYPE_RLE_GREY = 11;
  61747. TGATools._ORIGIN_MASK = 0x30;
  61748. TGATools._ORIGIN_SHIFT = 0x04;
  61749. TGATools._ORIGIN_BL = 0x00;
  61750. TGATools._ORIGIN_BR = 0x01;
  61751. TGATools._ORIGIN_UL = 0x02;
  61752. TGATools._ORIGIN_UR = 0x03;
  61753. return TGATools;
  61754. }());
  61755. Internals.TGATools = TGATools;
  61756. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61757. })(BABYLON || (BABYLON = {}));
  61758. //# sourceMappingURL=babylon.tga.js.map
  61759. var BABYLON;
  61760. (function (BABYLON) {
  61761. var Internals;
  61762. (function (Internals) {
  61763. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  61764. // All values and structures referenced from:
  61765. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  61766. var DDS_MAGIC = 0x20534444;
  61767. 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;
  61768. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  61769. 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;
  61770. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  61771. function FourCCToInt32(value) {
  61772. return value.charCodeAt(0) +
  61773. (value.charCodeAt(1) << 8) +
  61774. (value.charCodeAt(2) << 16) +
  61775. (value.charCodeAt(3) << 24);
  61776. }
  61777. function Int32ToFourCC(value) {
  61778. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  61779. }
  61780. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  61781. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  61782. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  61783. var FOURCC_DX10 = FourCCToInt32("DX10");
  61784. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  61785. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  61786. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  61787. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  61788. var headerLengthInt = 31; // The header length in 32 bit ints
  61789. // Offsets into the header array
  61790. var off_magic = 0;
  61791. var off_size = 1;
  61792. var off_flags = 2;
  61793. var off_height = 3;
  61794. var off_width = 4;
  61795. var off_mipmapCount = 7;
  61796. var off_pfFlags = 20;
  61797. var off_pfFourCC = 21;
  61798. var off_RGBbpp = 22;
  61799. var off_RMask = 23;
  61800. var off_GMask = 24;
  61801. var off_BMask = 25;
  61802. var off_AMask = 26;
  61803. var off_caps1 = 27;
  61804. var off_caps2 = 28;
  61805. var off_caps3 = 29;
  61806. var off_caps4 = 30;
  61807. var off_dxgiFormat = 32;
  61808. ;
  61809. var DDSTools = (function () {
  61810. function DDSTools() {
  61811. }
  61812. DDSTools.GetDDSInfo = function (arrayBuffer) {
  61813. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  61814. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  61815. var mipmapCount = 1;
  61816. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  61817. mipmapCount = Math.max(1, header[off_mipmapCount]);
  61818. }
  61819. var fourCC = header[off_pfFourCC];
  61820. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  61821. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61822. switch (fourCC) {
  61823. case FOURCC_D3DFMT_R16G16B16A16F:
  61824. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61825. break;
  61826. case FOURCC_D3DFMT_R32G32B32A32F:
  61827. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61828. break;
  61829. case FOURCC_DX10:
  61830. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  61831. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61832. break;
  61833. }
  61834. }
  61835. return {
  61836. width: header[off_width],
  61837. height: header[off_height],
  61838. mipmapCount: mipmapCount,
  61839. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  61840. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  61841. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  61842. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  61843. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  61844. dxgiFormat: dxgiFormat,
  61845. textureType: textureType
  61846. };
  61847. };
  61848. DDSTools._ToHalfFloat = function (value) {
  61849. if (!DDSTools._FloatView) {
  61850. DDSTools._FloatView = new Float32Array(1);
  61851. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  61852. }
  61853. DDSTools._FloatView[0] = value;
  61854. var x = DDSTools._Int32View[0];
  61855. var bits = (x >> 16) & 0x8000; /* Get the sign */
  61856. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  61857. var e = (x >> 23) & 0xff; /* Using int is faster here */
  61858. /* If zero, or denormal, or exponent underflows too much for a denormal
  61859. * half, return signed zero. */
  61860. if (e < 103) {
  61861. return bits;
  61862. }
  61863. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  61864. if (e > 142) {
  61865. bits |= 0x7c00;
  61866. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  61867. * not Inf, so make sure we set one mantissa bit too. */
  61868. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  61869. return bits;
  61870. }
  61871. /* If exponent underflows but not too much, return a denormal */
  61872. if (e < 113) {
  61873. m |= 0x0800;
  61874. /* Extra rounding may overflow and set mantissa to 0 and exponent
  61875. * to 1, which is OK. */
  61876. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  61877. return bits;
  61878. }
  61879. bits |= ((e - 112) << 10) | (m >> 1);
  61880. bits += m & 1;
  61881. return bits;
  61882. };
  61883. DDSTools._FromHalfFloat = function (value) {
  61884. var s = (value & 0x8000) >> 15;
  61885. var e = (value & 0x7C00) >> 10;
  61886. var f = value & 0x03FF;
  61887. if (e === 0) {
  61888. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  61889. }
  61890. else if (e == 0x1F) {
  61891. return f ? NaN : ((s ? -1 : 1) * Infinity);
  61892. }
  61893. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  61894. };
  61895. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61896. var destArray = new Float32Array(dataLength);
  61897. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61898. var index = 0;
  61899. for (var y = 0; y < height; y++) {
  61900. for (var x = 0; x < width; x++) {
  61901. var srcPos = (x + y * width) * 4;
  61902. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  61903. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  61904. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  61905. if (DDSTools.StoreLODInAlphaChannel) {
  61906. destArray[index + 3] = lod;
  61907. }
  61908. else {
  61909. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  61910. }
  61911. index += 4;
  61912. }
  61913. }
  61914. return destArray;
  61915. };
  61916. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61917. if (DDSTools.StoreLODInAlphaChannel) {
  61918. var destArray = new Uint16Array(dataLength);
  61919. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61920. var index = 0;
  61921. for (var y = 0; y < height; y++) {
  61922. for (var x = 0; x < width; x++) {
  61923. var srcPos = (x + y * width) * 4;
  61924. destArray[index] = srcData[srcPos];
  61925. destArray[index + 1] = srcData[srcPos + 1];
  61926. destArray[index + 2] = srcData[srcPos + 2];
  61927. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  61928. index += 4;
  61929. }
  61930. }
  61931. return destArray;
  61932. }
  61933. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  61934. };
  61935. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61936. if (DDSTools.StoreLODInAlphaChannel) {
  61937. var destArray = new Float32Array(dataLength);
  61938. var srcData = new Float32Array(arrayBuffer, dataOffset);
  61939. var index = 0;
  61940. for (var y = 0; y < height; y++) {
  61941. for (var x = 0; x < width; x++) {
  61942. var srcPos = (x + y * width) * 4;
  61943. destArray[index] = srcData[srcPos];
  61944. destArray[index + 1] = srcData[srcPos + 1];
  61945. destArray[index + 2] = srcData[srcPos + 2];
  61946. destArray[index + 3] = lod;
  61947. index += 4;
  61948. }
  61949. }
  61950. return destArray;
  61951. }
  61952. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  61953. };
  61954. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61955. var destArray = new Uint8Array(dataLength);
  61956. var srcData = new Float32Array(arrayBuffer, dataOffset);
  61957. var index = 0;
  61958. for (var y = 0; y < height; y++) {
  61959. for (var x = 0; x < width; x++) {
  61960. var srcPos = (x + y * width) * 4;
  61961. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  61962. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  61963. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  61964. if (DDSTools.StoreLODInAlphaChannel) {
  61965. destArray[index + 3] = lod;
  61966. }
  61967. else {
  61968. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  61969. }
  61970. index += 4;
  61971. }
  61972. }
  61973. return destArray;
  61974. };
  61975. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61976. var destArray = new Uint8Array(dataLength);
  61977. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61978. var index = 0;
  61979. for (var y = 0; y < height; y++) {
  61980. for (var x = 0; x < width; x++) {
  61981. var srcPos = (x + y * width) * 4;
  61982. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  61983. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  61984. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  61985. if (DDSTools.StoreLODInAlphaChannel) {
  61986. destArray[index + 3] = lod;
  61987. }
  61988. else {
  61989. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  61990. }
  61991. index += 4;
  61992. }
  61993. }
  61994. return destArray;
  61995. };
  61996. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61997. var byteArray = new Uint8Array(dataLength);
  61998. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61999. var index = 0;
  62000. for (var y = 0; y < height; y++) {
  62001. for (var x = 0; x < width; x++) {
  62002. var srcPos = (x + y * width) * 4;
  62003. byteArray[index] = srcData[srcPos + 2];
  62004. byteArray[index + 1] = srcData[srcPos + 1];
  62005. byteArray[index + 2] = srcData[srcPos];
  62006. byteArray[index + 3] = srcData[srcPos + 3];
  62007. index += 4;
  62008. }
  62009. }
  62010. return byteArray;
  62011. };
  62012. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62013. var byteArray = new Uint8Array(dataLength);
  62014. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62015. var index = 0;
  62016. for (var y = 0; y < height; y++) {
  62017. for (var x = 0; x < width; x++) {
  62018. var srcPos = (x + y * width) * 3;
  62019. byteArray[index] = srcData[srcPos + 2];
  62020. byteArray[index + 1] = srcData[srcPos + 1];
  62021. byteArray[index + 2] = srcData[srcPos];
  62022. index += 3;
  62023. }
  62024. }
  62025. return byteArray;
  62026. };
  62027. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62028. var byteArray = new Uint8Array(dataLength);
  62029. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62030. var index = 0;
  62031. for (var y = 0; y < height; y++) {
  62032. for (var x = 0; x < width; x++) {
  62033. var srcPos = (x + y * width);
  62034. byteArray[index] = srcData[srcPos];
  62035. index++;
  62036. }
  62037. }
  62038. return byteArray;
  62039. };
  62040. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  62041. if (lodIndex === void 0) { lodIndex = -1; }
  62042. var ext = engine.getCaps().s3tc;
  62043. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  62044. if (header[off_magic] != DDS_MAGIC) {
  62045. BABYLON.Tools.Error("Invalid magic number in DDS header");
  62046. return;
  62047. }
  62048. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  62049. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  62050. return;
  62051. }
  62052. if (info.isCompressed && !ext) {
  62053. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  62054. return;
  62055. }
  62056. var bpp = header[off_RGBbpp];
  62057. dataOffset = header[off_size] + 4;
  62058. var computeFormats = false;
  62059. if (info.isFourCC) {
  62060. fourCC = header[off_pfFourCC];
  62061. switch (fourCC) {
  62062. case FOURCC_DXT1:
  62063. blockBytes = 8;
  62064. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  62065. break;
  62066. case FOURCC_DXT3:
  62067. blockBytes = 16;
  62068. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  62069. break;
  62070. case FOURCC_DXT5:
  62071. blockBytes = 16;
  62072. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  62073. break;
  62074. case FOURCC_D3DFMT_R16G16B16A16F:
  62075. computeFormats = true;
  62076. break;
  62077. case FOURCC_D3DFMT_R32G32B32A32F:
  62078. computeFormats = true;
  62079. break;
  62080. case FOURCC_DX10:
  62081. // There is an additionnal header so dataOffset need to be changed
  62082. dataOffset += 5 * 4; // 5 uints
  62083. var supported = false;
  62084. switch (info.dxgiFormat) {
  62085. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  62086. computeFormats = true;
  62087. supported = true;
  62088. break;
  62089. case DXGI_FORMAT_B8G8R8X8_UNORM:
  62090. info.isRGB = true;
  62091. info.isFourCC = false;
  62092. bpp = 32;
  62093. supported = true;
  62094. break;
  62095. }
  62096. if (supported) {
  62097. break;
  62098. }
  62099. default:
  62100. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  62101. return;
  62102. }
  62103. }
  62104. if (computeFormats) {
  62105. format = engine._getWebGLTextureType(info.textureType);
  62106. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62107. }
  62108. mipmapCount = 1;
  62109. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  62110. mipmapCount = Math.max(1, header[off_mipmapCount]);
  62111. }
  62112. for (var face = 0; face < faces; face++) {
  62113. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62114. width = header[off_width];
  62115. height = header[off_height];
  62116. for (mip = 0; mip < mipmapCount; ++mip) {
  62117. if (lodIndex === -1 || lodIndex === mip) {
  62118. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  62119. var i = (lodIndex === -1) ? mip : 0;
  62120. if (!info.isCompressed && info.isFourCC) {
  62121. dataLength = width * height * 4;
  62122. var floatArray;
  62123. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  62124. if (bpp === 128) {
  62125. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62126. }
  62127. else if (bpp === 64) {
  62128. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62129. }
  62130. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62131. format = engine._getWebGLTextureType(info.textureType);
  62132. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62133. }
  62134. else {
  62135. if (bpp === 128) {
  62136. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62137. }
  62138. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  62139. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62140. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62141. format = engine._getWebGLTextureType(info.textureType);
  62142. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62143. }
  62144. else {
  62145. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62146. }
  62147. }
  62148. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  62149. }
  62150. else if (info.isRGB) {
  62151. if (bpp === 24) {
  62152. dataLength = width * height * 3;
  62153. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62154. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  62155. }
  62156. else {
  62157. dataLength = width * height * 4;
  62158. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62159. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  62160. }
  62161. }
  62162. else if (info.isLuminance) {
  62163. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  62164. var unpaddedRowSize = width;
  62165. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  62166. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  62167. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62168. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  62169. }
  62170. else {
  62171. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  62172. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  62173. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  62174. }
  62175. }
  62176. dataOffset += width * height * (bpp / 8);
  62177. width *= 0.5;
  62178. height *= 0.5;
  62179. width = Math.max(1.0, width);
  62180. height = Math.max(1.0, height);
  62181. }
  62182. }
  62183. };
  62184. DDSTools.StoreLODInAlphaChannel = false;
  62185. return DDSTools;
  62186. }());
  62187. Internals.DDSTools = DDSTools;
  62188. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62189. })(BABYLON || (BABYLON = {}));
  62190. //# sourceMappingURL=babylon.dds.js.map
  62191. var BABYLON;
  62192. (function (BABYLON) {
  62193. var Internals;
  62194. (function (Internals) {
  62195. /**
  62196. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  62197. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  62198. */
  62199. var KhronosTextureContainer = (function () {
  62200. /**
  62201. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  62202. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  62203. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  62204. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  62205. */
  62206. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  62207. this.arrayBuffer = arrayBuffer;
  62208. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  62209. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  62210. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  62211. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  62212. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  62213. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  62214. BABYLON.Tools.Error("texture missing KTX identifier");
  62215. return;
  62216. }
  62217. // load the reset of the header in native 32 bit int
  62218. var header = new Int32Array(this.arrayBuffer, 12, 13);
  62219. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  62220. var oppositeEndianess = header[0] === 0x01020304;
  62221. // read all the header elements in order they exist in the file, without modification (sans endainness)
  62222. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  62223. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  62224. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  62225. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  62226. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  62227. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  62228. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  62229. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  62230. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  62231. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  62232. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  62233. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  62234. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  62235. if (this.glType !== 0) {
  62236. BABYLON.Tools.Error("only compressed formats currently supported");
  62237. return;
  62238. }
  62239. else {
  62240. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  62241. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  62242. }
  62243. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  62244. BABYLON.Tools.Error("only 2D textures currently supported");
  62245. return;
  62246. }
  62247. if (this.numberOfArrayElements !== 0) {
  62248. BABYLON.Tools.Error("texture arrays not currently supported");
  62249. return;
  62250. }
  62251. if (this.numberOfFaces !== facesExpected) {
  62252. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  62253. return;
  62254. }
  62255. // we now have a completely validated file, so could use existence of loadType as success
  62256. // would need to make this more elaborate & adjust checks above to support more than one load type
  62257. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  62258. }
  62259. // not as fast hardware based, but will probably never need to use
  62260. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  62261. return ((val & 0xFF) << 24)
  62262. | ((val & 0xFF00) << 8)
  62263. | ((val >> 8) & 0xFF00)
  62264. | ((val >> 24) & 0xFF);
  62265. };
  62266. /**
  62267. * It is assumed that the texture has already been created & is currently bound
  62268. */
  62269. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  62270. switch (this.loadType) {
  62271. case KhronosTextureContainer.COMPRESSED_2D:
  62272. this._upload2DCompressedLevels(gl, loadMipmaps);
  62273. break;
  62274. case KhronosTextureContainer.TEX_2D:
  62275. case KhronosTextureContainer.COMPRESSED_3D:
  62276. case KhronosTextureContainer.TEX_3D:
  62277. }
  62278. };
  62279. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  62280. // initialize width & height for level 1
  62281. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  62282. var width = this.pixelWidth;
  62283. var height = this.pixelHeight;
  62284. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  62285. for (var level = 0; level < mipmapCount; level++) {
  62286. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  62287. for (var face = 0; face < this.numberOfFaces; face++) {
  62288. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62289. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  62290. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  62291. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  62292. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  62293. }
  62294. width = Math.max(1.0, width * 0.5);
  62295. height = Math.max(1.0, height * 0.5);
  62296. }
  62297. };
  62298. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  62299. // load types
  62300. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  62301. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  62302. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  62303. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  62304. return KhronosTextureContainer;
  62305. }());
  62306. Internals.KhronosTextureContainer = KhronosTextureContainer;
  62307. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62308. })(BABYLON || (BABYLON = {}));
  62309. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  62310. var BABYLON;
  62311. (function (BABYLON) {
  62312. var DynamicFloatArrayElementInfo = (function () {
  62313. function DynamicFloatArrayElementInfo() {
  62314. }
  62315. return DynamicFloatArrayElementInfo;
  62316. }());
  62317. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  62318. /**
  62319. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  62320. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  62321. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  62322. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  62323. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  62324. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  62325. */
  62326. var DynamicFloatArray = (function () {
  62327. /**
  62328. * Construct an instance of the dynamic float array
  62329. * @param stride size of one element in float (i.e. not bytes!)
  62330. * @param initialElementCount the number of available entries at construction
  62331. */
  62332. function DynamicFloatArray(stride, initialElementCount) {
  62333. this.compareValueOffset = null;
  62334. this.sortingAscending = true;
  62335. this._stride = stride;
  62336. this.buffer = new Float32Array(stride * initialElementCount);
  62337. this._lastUsed = 0;
  62338. this._firstFree = 0;
  62339. this._allEntries = new Array(initialElementCount);
  62340. this._freeEntries = new Array(initialElementCount);
  62341. for (var i = 0; i < initialElementCount; i++) {
  62342. var element = new DynamicFloatArrayElementInfo();
  62343. element.offset = i * stride;
  62344. this._allEntries[i] = element;
  62345. this._freeEntries[initialElementCount - i - 1] = element;
  62346. }
  62347. }
  62348. /**
  62349. * Allocate an element in the array.
  62350. * @return the element info instance that contains the offset into the main buffer of the element's location.
  62351. * Beware, this offset may change when you call pack()
  62352. */
  62353. DynamicFloatArray.prototype.allocElement = function () {
  62354. if (this._freeEntries.length === 0) {
  62355. this._growBuffer();
  62356. }
  62357. var el = this._freeEntries.pop();
  62358. this._lastUsed = Math.max(el.offset, this._lastUsed);
  62359. if (el.offset === this._firstFree) {
  62360. if (this._freeEntries.length > 0) {
  62361. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  62362. }
  62363. else {
  62364. this._firstFree += this._stride;
  62365. }
  62366. }
  62367. return el;
  62368. };
  62369. /**
  62370. * Free the element corresponding to the given element info
  62371. * @param elInfo the element that describe the allocated element
  62372. */
  62373. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  62374. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  62375. this._freeEntries.push(elInfo);
  62376. };
  62377. /**
  62378. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  62379. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  62380. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  62381. */
  62382. DynamicFloatArray.prototype.pack = function () {
  62383. // no free slot? no need to pack
  62384. if (this._freeEntries.length === 0) {
  62385. return this.buffer;
  62386. }
  62387. // If the buffer is already packed the last used will always be lower than the first free
  62388. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  62389. if (this._lastUsed < this._firstFree) {
  62390. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  62391. return elementsBuffer_1;
  62392. }
  62393. var s = this._stride;
  62394. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  62395. var lastFree = new DynamicFloatArrayElementInfo();
  62396. lastFree.offset = this.totalElementCount * s;
  62397. this._freeEntries.push(lastFree);
  62398. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  62399. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62400. var firstFreeSlotOffset = sortedFree[0].offset;
  62401. var freeZoneSize = 1;
  62402. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  62403. var prevOffset = sortedFree[0].offset;
  62404. for (var i = 1; i < sortedFree.length; i++) {
  62405. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  62406. if (firstFreeSlotOffset >= occupiedZoneSize) {
  62407. break;
  62408. }
  62409. var curFree = sortedFree[i];
  62410. var curOffset = curFree.offset;
  62411. // Compute the distance between this offset and the previous
  62412. var distance = curOffset - prevOffset;
  62413. // If the distance is the stride size, they are adjacent, it good, move to the next
  62414. if (distance === s) {
  62415. // Free zone is one element bigger
  62416. ++freeZoneSize;
  62417. // as we're about to iterate to the next, the cur becomes the previous...
  62418. prevOffset = curOffset;
  62419. continue;
  62420. }
  62421. // Distance is bigger, which means there's x element between the previous free and this one
  62422. var usedRange = (distance / s) - 1;
  62423. // Two cases the free zone is smaller than the data to move or bigger
  62424. // Copy what can fit in the free zone
  62425. var curMoveOffset = curOffset - s;
  62426. var copyCount = Math.min(freeZoneSize, usedRange);
  62427. for (var j = 0; j < copyCount; j++) {
  62428. var freeI = firstFreeSlotOffset / s;
  62429. var curI = curMoveOffset / s;
  62430. var moveEl = sortedAll[curI];
  62431. this._moveElement(moveEl, firstFreeSlotOffset);
  62432. var replacedEl = sortedAll[freeI];
  62433. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  62434. replacedEl.offset = curMoveOffset;
  62435. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  62436. sortedAll[freeI] = moveEl;
  62437. sortedAll[curI] = replacedEl;
  62438. curMoveOffset -= s;
  62439. firstFreeSlotOffset += s;
  62440. }
  62441. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  62442. if (freeZoneSize <= usedRange) {
  62443. firstFreeSlotOffset = curMoveOffset + s;
  62444. freeZoneSize = 1 + copyCount;
  62445. }
  62446. else {
  62447. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  62448. }
  62449. // as we're about to iterate to the next, the cur becomes the previous...
  62450. prevOffset = curOffset;
  62451. }
  62452. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  62453. this._lastUsed = firstFreeSlotOffset - s;
  62454. this._firstFree = firstFreeSlotOffset;
  62455. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  62456. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  62457. this._allEntries = sortedAll;
  62458. return elementsBuffer;
  62459. };
  62460. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  62461. for (var i = 0; i < this._stride; i++) {
  62462. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  62463. }
  62464. element.offset = destOffset;
  62465. };
  62466. DynamicFloatArray.prototype._growBuffer = function () {
  62467. // Allocate the new buffer with 50% more entries, copy the content of the current one
  62468. var newElCount = Math.floor(this.totalElementCount * 1.5);
  62469. var newBuffer = new Float32Array(newElCount * this._stride);
  62470. newBuffer.set(this.buffer);
  62471. var curCount = this.totalElementCount;
  62472. var addedCount = newElCount - this.totalElementCount;
  62473. for (var i = 0; i < addedCount; i++) {
  62474. var element = new DynamicFloatArrayElementInfo();
  62475. element.offset = (curCount + i) * this.stride;
  62476. this._allEntries.push(element);
  62477. this._freeEntries[addedCount - i - 1] = element;
  62478. }
  62479. this._firstFree = curCount * this.stride;
  62480. this.buffer = newBuffer;
  62481. };
  62482. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  62483. /**
  62484. * Get the total count of entries that can fit in the current buffer
  62485. * @returns the elements count
  62486. */
  62487. get: function () {
  62488. return this._allEntries.length;
  62489. },
  62490. enumerable: true,
  62491. configurable: true
  62492. });
  62493. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  62494. /**
  62495. * Get the count of free entries that can still be allocated without resizing the buffer
  62496. * @returns the free elements count
  62497. */
  62498. get: function () {
  62499. return this._freeEntries.length;
  62500. },
  62501. enumerable: true,
  62502. configurable: true
  62503. });
  62504. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  62505. /**
  62506. * Get the count of allocated elements
  62507. * @returns the allocated elements count
  62508. */
  62509. get: function () {
  62510. return this._allEntries.length - this._freeEntries.length;
  62511. },
  62512. enumerable: true,
  62513. configurable: true
  62514. });
  62515. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  62516. /**
  62517. * Return the size of one element in float
  62518. * @returns the size in float
  62519. */
  62520. get: function () {
  62521. return this._stride;
  62522. },
  62523. enumerable: true,
  62524. configurable: true
  62525. });
  62526. DynamicFloatArray.prototype.sort = function () {
  62527. var _this = this;
  62528. if (!this.compareValueOffset) {
  62529. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  62530. }
  62531. var count = this.usedElementCount;
  62532. // Do we have to (re)create the sort table?
  62533. if (!this._sortTable || this._sortTable.length < count) {
  62534. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  62535. var newCount = Math.min(this.totalElementCount, count * 2);
  62536. this._sortTable = new Array(newCount);
  62537. }
  62538. if (!this._sortedTable || this._sortedTable.length !== count) {
  62539. this._sortedTable = new Array(count);
  62540. }
  62541. // Because, you know...
  62542. this.pack();
  62543. //let stride = this.stride;
  62544. //for (let i = 0; i < count; i++) {
  62545. // let si = this._sortTable[i];
  62546. // if (!si) {
  62547. // si = new SortInfo();
  62548. // this._sortTable[i] = si;
  62549. // }
  62550. // si.entry = this._allEntries[i];
  62551. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  62552. // si.swapedOffset = null;
  62553. // this._sortedTable[i] = si;
  62554. //}
  62555. var curOffset = 0;
  62556. var stride = this.stride;
  62557. for (var i = 0; i < count; i++, curOffset += stride) {
  62558. var si = this._sortTable[i];
  62559. if (!si) {
  62560. si = new SortInfo();
  62561. this._sortTable[i] = si;
  62562. }
  62563. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  62564. si.offset = curOffset;
  62565. si.swapedOffset = null;
  62566. this._sortedTable[i] = si;
  62567. }
  62568. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  62569. if (this.sortingAscending) {
  62570. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  62571. }
  62572. else {
  62573. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  62574. }
  62575. var swapElements = function (src, dst) {
  62576. for (var i = 0; i < stride; i++) {
  62577. var tps = _this.buffer[dst + i];
  62578. _this.buffer[dst + i] = _this.buffer[src + i];
  62579. _this.buffer[src + i] = tps;
  62580. }
  62581. };
  62582. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  62583. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  62584. // and I still want something with a good algorithm complexity.
  62585. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  62586. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  62587. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  62588. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  62589. // until we find a SortInfo object without a swapedOffset which means we got the right location
  62590. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  62591. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  62592. for (var i = 0; i < count; i++) {
  62593. // Get the element to move
  62594. var sourceSI = this._sortedTable[i];
  62595. var destSI = this._sortTable[i];
  62596. var sourceOff = sourceSI.offset;
  62597. // If the source changed location, find the new one
  62598. if (sourceSI.swapedOffset) {
  62599. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  62600. var curSI = sourceSI;
  62601. while (curSI.swapedOffset) {
  62602. curSI = this._sortTable[curSI.swapedOffset / stride];
  62603. }
  62604. // Finally get the right location
  62605. sourceOff = curSI.offset;
  62606. }
  62607. // Tag the element being replaced with its new location
  62608. destSI.swapedOffset = sourceOff;
  62609. // Swap elements (only if needed)
  62610. if (sourceOff !== destSI.offset) {
  62611. swapElements(sourceOff, destSI.offset);
  62612. }
  62613. // Update the offset in the corresponding DFAE
  62614. //sourceSI.entry.offset = destSI.entry.offset;
  62615. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  62616. }
  62617. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62618. return true;
  62619. };
  62620. return DynamicFloatArray;
  62621. }());
  62622. BABYLON.DynamicFloatArray = DynamicFloatArray;
  62623. var SortInfo = (function () {
  62624. function SortInfo() {
  62625. this.compareData = this.offset = this.swapedOffset = null;
  62626. }
  62627. return SortInfo;
  62628. }());
  62629. })(BABYLON || (BABYLON = {}));
  62630. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  62631. var BABYLON;
  62632. (function (BABYLON) {
  62633. var Debug;
  62634. (function (Debug) {
  62635. /**
  62636. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  62637. */
  62638. var SkeletonViewer = (function () {
  62639. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  62640. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62641. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62642. this.skeleton = skeleton;
  62643. this.mesh = mesh;
  62644. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62645. this.renderingGroupId = renderingGroupId;
  62646. this.color = BABYLON.Color3.White();
  62647. this._debugLines = [];
  62648. this._isEnabled = false;
  62649. this._scene = scene;
  62650. this.update();
  62651. this._renderFunction = this.update.bind(this);
  62652. }
  62653. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62654. get: function () {
  62655. return this._isEnabled;
  62656. },
  62657. set: function (value) {
  62658. if (this._isEnabled === value) {
  62659. return;
  62660. }
  62661. this._isEnabled = value;
  62662. if (value) {
  62663. this._scene.registerBeforeRender(this._renderFunction);
  62664. }
  62665. else {
  62666. this._scene.unregisterBeforeRender(this._renderFunction);
  62667. }
  62668. },
  62669. enumerable: true,
  62670. configurable: true
  62671. });
  62672. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62673. if (x === void 0) { x = 0; }
  62674. if (y === void 0) { y = 0; }
  62675. if (z === void 0) { z = 0; }
  62676. var tmat = BABYLON.Tmp.Matrix[0];
  62677. var parentBone = bone.getParent();
  62678. tmat.copyFrom(bone.getLocalMatrix());
  62679. if (x !== 0 || y !== 0 || z !== 0) {
  62680. var tmat2 = BABYLON.Tmp.Matrix[1];
  62681. BABYLON.Matrix.IdentityToRef(tmat2);
  62682. tmat2.m[12] = x;
  62683. tmat2.m[13] = y;
  62684. tmat2.m[14] = z;
  62685. tmat2.multiplyToRef(tmat, tmat);
  62686. }
  62687. if (parentBone) {
  62688. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62689. }
  62690. tmat.multiplyToRef(meshMat, tmat);
  62691. position.x = tmat.m[12];
  62692. position.y = tmat.m[13];
  62693. position.z = tmat.m[14];
  62694. };
  62695. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62696. var len = bones.length;
  62697. var meshPos = this.mesh.position;
  62698. for (var i = 0; i < len; i++) {
  62699. var bone = bones[i];
  62700. var points = this._debugLines[i];
  62701. if (!points) {
  62702. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62703. this._debugLines[i] = points;
  62704. }
  62705. this._getBonePosition(points[0], bone, meshMat);
  62706. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62707. points[0].subtractInPlace(meshPos);
  62708. points[1].subtractInPlace(meshPos);
  62709. }
  62710. };
  62711. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62712. var len = bones.length;
  62713. var boneNum = 0;
  62714. var meshPos = this.mesh.position;
  62715. for (var i = len - 1; i >= 0; i--) {
  62716. var childBone = bones[i];
  62717. var parentBone = childBone.getParent();
  62718. if (!parentBone) {
  62719. continue;
  62720. }
  62721. var points = this._debugLines[boneNum];
  62722. if (!points) {
  62723. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62724. this._debugLines[boneNum] = points;
  62725. }
  62726. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62727. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62728. points[0].subtractInPlace(meshPos);
  62729. points[1].subtractInPlace(meshPos);
  62730. boneNum++;
  62731. }
  62732. };
  62733. SkeletonViewer.prototype.update = function () {
  62734. if (this.autoUpdateBonesMatrices) {
  62735. this.skeleton.computeAbsoluteTransforms();
  62736. }
  62737. if (this.skeleton.bones[0].length === undefined) {
  62738. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62739. }
  62740. else {
  62741. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62742. }
  62743. if (!this._debugMesh) {
  62744. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  62745. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62746. }
  62747. else {
  62748. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62749. }
  62750. this._debugMesh.position.copyFrom(this.mesh.position);
  62751. this._debugMesh.color = this.color;
  62752. };
  62753. SkeletonViewer.prototype.dispose = function () {
  62754. if (this._debugMesh) {
  62755. this.isEnabled = false;
  62756. this._debugMesh.dispose();
  62757. this._debugMesh = null;
  62758. }
  62759. };
  62760. return SkeletonViewer;
  62761. }());
  62762. Debug.SkeletonViewer = SkeletonViewer;
  62763. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62764. })(BABYLON || (BABYLON = {}));
  62765. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62766. var BABYLON;
  62767. (function (BABYLON) {
  62768. var Debug;
  62769. (function (Debug) {
  62770. var AxesViewer = (function () {
  62771. function AxesViewer(scene, scaleLines) {
  62772. if (scaleLines === void 0) { scaleLines = 1; }
  62773. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62774. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62775. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62776. this.scaleLines = 1;
  62777. this.scaleLines = scaleLines;
  62778. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62779. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62780. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62781. this._xmesh.renderingGroupId = 2;
  62782. this._ymesh.renderingGroupId = 2;
  62783. this._zmesh.renderingGroupId = 2;
  62784. this._xmesh.material.checkReadyOnlyOnce = true;
  62785. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62786. this._ymesh.material.checkReadyOnlyOnce = true;
  62787. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62788. this._zmesh.material.checkReadyOnlyOnce = true;
  62789. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62790. this.scene = scene;
  62791. }
  62792. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62793. var scaleLines = this.scaleLines;
  62794. this._xmesh.position.copyFrom(position);
  62795. this._ymesh.position.copyFrom(position);
  62796. this._zmesh.position.copyFrom(position);
  62797. var point2 = this._xline[1];
  62798. point2.x = xaxis.x * scaleLines;
  62799. point2.y = xaxis.y * scaleLines;
  62800. point2.z = xaxis.z * scaleLines;
  62801. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  62802. point2 = this._yline[1];
  62803. point2.x = yaxis.x * scaleLines;
  62804. point2.y = yaxis.y * scaleLines;
  62805. point2.z = yaxis.z * scaleLines;
  62806. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  62807. point2 = this._zline[1];
  62808. point2.x = zaxis.x * scaleLines;
  62809. point2.y = zaxis.y * scaleLines;
  62810. point2.z = zaxis.z * scaleLines;
  62811. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  62812. };
  62813. AxesViewer.prototype.dispose = function () {
  62814. if (this._xmesh) {
  62815. this._xmesh.dispose();
  62816. this._ymesh.dispose();
  62817. this._zmesh.dispose();
  62818. this._xmesh = null;
  62819. this._ymesh = null;
  62820. this._zmesh = null;
  62821. this._xline = null;
  62822. this._yline = null;
  62823. this._zline = null;
  62824. this.scene = null;
  62825. }
  62826. };
  62827. return AxesViewer;
  62828. }());
  62829. Debug.AxesViewer = AxesViewer;
  62830. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62831. })(BABYLON || (BABYLON = {}));
  62832. //# sourceMappingURL=babylon.axesViewer.js.map
  62833. var BABYLON;
  62834. (function (BABYLON) {
  62835. var Debug;
  62836. (function (Debug) {
  62837. var BoneAxesViewer = (function (_super) {
  62838. __extends(BoneAxesViewer, _super);
  62839. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62840. if (scaleLines === void 0) { scaleLines = 1; }
  62841. var _this = _super.call(this, scene, scaleLines) || this;
  62842. _this.pos = BABYLON.Vector3.Zero();
  62843. _this.xaxis = BABYLON.Vector3.Zero();
  62844. _this.yaxis = BABYLON.Vector3.Zero();
  62845. _this.zaxis = BABYLON.Vector3.Zero();
  62846. _this.mesh = mesh;
  62847. _this.bone = bone;
  62848. return _this;
  62849. }
  62850. BoneAxesViewer.prototype.update = function () {
  62851. var bone = this.bone;
  62852. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62853. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62854. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62855. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62856. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62857. };
  62858. BoneAxesViewer.prototype.dispose = function () {
  62859. if (this.pos) {
  62860. this.pos = null;
  62861. this.xaxis = null;
  62862. this.yaxis = null;
  62863. this.zaxis = null;
  62864. this.mesh = null;
  62865. this.bone = null;
  62866. _super.prototype.dispose.call(this);
  62867. }
  62868. };
  62869. return BoneAxesViewer;
  62870. }(Debug.AxesViewer));
  62871. Debug.BoneAxesViewer = BoneAxesViewer;
  62872. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62873. })(BABYLON || (BABYLON = {}));
  62874. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62875. var BABYLON;
  62876. (function (BABYLON) {
  62877. var RayHelper = (function () {
  62878. function RayHelper(ray) {
  62879. this.ray = ray;
  62880. }
  62881. RayHelper.CreateAndShow = function (ray, scene, color) {
  62882. var helper = new RayHelper(ray);
  62883. helper.show(scene, color);
  62884. return helper;
  62885. };
  62886. RayHelper.prototype.show = function (scene, color) {
  62887. if (!this._renderFunction) {
  62888. var ray = this.ray;
  62889. this._renderFunction = this._render.bind(this);
  62890. this._scene = scene;
  62891. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62892. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62893. this._scene.registerBeforeRender(this._renderFunction);
  62894. }
  62895. if (color) {
  62896. this._renderLine.color.copyFrom(color);
  62897. }
  62898. };
  62899. RayHelper.prototype.hide = function () {
  62900. if (this._renderFunction) {
  62901. this._scene.unregisterBeforeRender(this._renderFunction);
  62902. this._scene = null;
  62903. this._renderFunction = null;
  62904. this._renderLine.dispose();
  62905. this._renderLine = null;
  62906. this._renderPoints = null;
  62907. }
  62908. };
  62909. RayHelper.prototype._render = function () {
  62910. var ray = this.ray;
  62911. var point = this._renderPoints[1];
  62912. var len = Math.min(ray.length, 1000000);
  62913. point.copyFrom(ray.direction);
  62914. point.scaleInPlace(len);
  62915. point.addInPlace(ray.origin);
  62916. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62917. };
  62918. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62919. this._attachedToMesh = mesh;
  62920. var ray = this.ray;
  62921. if (!ray.direction) {
  62922. ray.direction = BABYLON.Vector3.Zero();
  62923. }
  62924. if (!ray.origin) {
  62925. ray.origin = BABYLON.Vector3.Zero();
  62926. }
  62927. if (length) {
  62928. ray.length = length;
  62929. }
  62930. if (!meshSpaceOrigin) {
  62931. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62932. }
  62933. if (!meshSpaceDirection) {
  62934. // -1 so that this will work with Mesh.lookAt
  62935. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62936. }
  62937. if (!this._meshSpaceDirection) {
  62938. this._meshSpaceDirection = meshSpaceDirection.clone();
  62939. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62940. }
  62941. else {
  62942. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62943. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62944. }
  62945. if (!this._updateToMeshFunction) {
  62946. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62947. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62948. }
  62949. this._updateToMesh();
  62950. };
  62951. RayHelper.prototype.detachFromMesh = function () {
  62952. if (this._attachedToMesh) {
  62953. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62954. this._attachedToMesh = null;
  62955. this._updateToMeshFunction = null;
  62956. }
  62957. };
  62958. RayHelper.prototype._updateToMesh = function () {
  62959. var ray = this.ray;
  62960. if (this._attachedToMesh._isDisposed) {
  62961. this.detachFromMesh();
  62962. return;
  62963. }
  62964. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62965. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62966. };
  62967. RayHelper.prototype.dispose = function () {
  62968. this.hide();
  62969. this.detachFromMesh();
  62970. this.ray = null;
  62971. };
  62972. return RayHelper;
  62973. }());
  62974. BABYLON.RayHelper = RayHelper;
  62975. })(BABYLON || (BABYLON = {}));
  62976. //# sourceMappingURL=babylon.rayHelper.js.map
  62977. var BABYLON;
  62978. (function (BABYLON) {
  62979. var DebugLayer = (function () {
  62980. function DebugLayer(scene) {
  62981. this._scene = scene;
  62982. }
  62983. /** Creates the inspector window. */
  62984. DebugLayer.prototype._createInspector = function (config) {
  62985. if (config === void 0) { config = {}; }
  62986. var popup = config.popup || false;
  62987. var initialTab = config.initialTab || 0;
  62988. var parentElement = config.parentElement || null;
  62989. if (!this._inspector) {
  62990. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62991. } // else nothing to do,; instance is already existing
  62992. };
  62993. DebugLayer.prototype.isVisible = function () {
  62994. if (!this._inspector) {
  62995. return false;
  62996. }
  62997. return true;
  62998. };
  62999. DebugLayer.prototype.hide = function () {
  63000. if (this._inspector) {
  63001. try {
  63002. this._inspector.dispose();
  63003. }
  63004. catch (e) {
  63005. // If the inspector has been removed directly from the inspector tool
  63006. }
  63007. this._inspector = null;
  63008. }
  63009. };
  63010. DebugLayer.prototype.show = function (config) {
  63011. if (config === void 0) { config = {}; }
  63012. if (typeof INSPECTOR == 'undefined') {
  63013. // Load inspector and add it to the DOM
  63014. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63015. }
  63016. else {
  63017. // Otherwise creates the inspector
  63018. this._createInspector(config);
  63019. }
  63020. };
  63021. // Get protocol used - http or https
  63022. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63023. return DebugLayer;
  63024. }());
  63025. BABYLON.DebugLayer = DebugLayer;
  63026. })(BABYLON || (BABYLON = {}));
  63027. //# sourceMappingURL=babylon.debugLayer.js.map
  63028. var BABYLON;
  63029. (function (BABYLON) {
  63030. var Debug;
  63031. (function (Debug) {
  63032. var PhysicsViewer = (function () {
  63033. function PhysicsViewer(scene) {
  63034. this._impostors = [];
  63035. this._meshes = [];
  63036. this._numMeshes = 0;
  63037. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63038. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  63039. }
  63040. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63041. var plugin = this._physicsEnginePlugin;
  63042. for (var i = 0; i < this._numMeshes; i++) {
  63043. if (this._impostors[i].isDisposed) {
  63044. this.hideImpostor(this._impostors[i--]);
  63045. }
  63046. else {
  63047. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  63048. }
  63049. }
  63050. };
  63051. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63052. for (var i = 0; i < this._numMeshes; i++) {
  63053. if (this._impostors[i] == impostor) {
  63054. return;
  63055. }
  63056. }
  63057. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63058. if (debugMesh) {
  63059. this._impostors[this._numMeshes] = impostor;
  63060. this._meshes[this._numMeshes] = debugMesh;
  63061. if (this._numMeshes === 0) {
  63062. this._renderFunction = this._updateDebugMeshes.bind(this);
  63063. this._scene.registerBeforeRender(this._renderFunction);
  63064. }
  63065. this._numMeshes++;
  63066. }
  63067. };
  63068. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63069. var removed = false;
  63070. for (var i = 0; i < this._numMeshes; i++) {
  63071. if (this._impostors[i] == impostor) {
  63072. this._scene.removeMesh(this._meshes[i]);
  63073. this._meshes[i].dispose();
  63074. this._numMeshes--;
  63075. if (this._numMeshes > 0) {
  63076. this._meshes[i] = this._meshes[this._numMeshes];
  63077. this._impostors[i] = this._impostors[this._numMeshes];
  63078. this._meshes[this._numMeshes] = null;
  63079. this._impostors[this._numMeshes] = null;
  63080. }
  63081. else {
  63082. this._meshes[0] = null;
  63083. this._impostors[0] = null;
  63084. }
  63085. removed = true;
  63086. break;
  63087. }
  63088. }
  63089. if (removed && this._numMeshes === 0) {
  63090. this._scene.unregisterBeforeRender(this._renderFunction);
  63091. }
  63092. };
  63093. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63094. if (!this._debugMaterial) {
  63095. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63096. this._debugMaterial.wireframe = true;
  63097. }
  63098. return this._debugMaterial;
  63099. };
  63100. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63101. if (!this._debugBoxMesh) {
  63102. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63103. this._debugBoxMesh.renderingGroupId = 1;
  63104. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63105. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63106. scene.removeMesh(this._debugBoxMesh);
  63107. }
  63108. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63109. };
  63110. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63111. if (!this._debugSphereMesh) {
  63112. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63113. this._debugSphereMesh.renderingGroupId = 1;
  63114. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63115. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63116. scene.removeMesh(this._debugSphereMesh);
  63117. }
  63118. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63119. };
  63120. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63121. var body = impostor.physicsBody;
  63122. var shape = body.shapes[0];
  63123. var mesh;
  63124. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63125. mesh = this._getDebugBoxMesh(scene);
  63126. impostor.getBoxSizeToRef(mesh.scaling);
  63127. }
  63128. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63129. mesh = this._getDebugSphereMesh(scene);
  63130. var radius = impostor.getRadius();
  63131. mesh.scaling.x = radius * 2;
  63132. mesh.scaling.y = radius * 2;
  63133. mesh.scaling.z = radius * 2;
  63134. }
  63135. return mesh;
  63136. };
  63137. PhysicsViewer.prototype.dispose = function () {
  63138. for (var i = 0; i < this._numMeshes; i++) {
  63139. this.hideImpostor(this._impostors[i]);
  63140. }
  63141. if (this._debugBoxMesh) {
  63142. this._debugBoxMesh.dispose();
  63143. }
  63144. if (this._debugSphereMesh) {
  63145. this._debugSphereMesh.dispose();
  63146. }
  63147. if (this._debugMaterial) {
  63148. this._debugMaterial.dispose();
  63149. }
  63150. this._impostors.length = 0;
  63151. this._scene = null;
  63152. this._physicsEnginePlugin = null;
  63153. };
  63154. return PhysicsViewer;
  63155. }());
  63156. Debug.PhysicsViewer = PhysicsViewer;
  63157. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63158. })(BABYLON || (BABYLON = {}));
  63159. //# sourceMappingURL=babylon.physicsViewer.js.map
  63160. var BABYLON;
  63161. (function (BABYLON) {
  63162. var BoundingBoxRenderer = (function () {
  63163. function BoundingBoxRenderer(scene) {
  63164. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63165. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63166. this.showBackLines = true;
  63167. this.renderList = new BABYLON.SmartArray(32);
  63168. this._vertexBuffers = {};
  63169. this._scene = scene;
  63170. }
  63171. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63172. if (this._colorShader) {
  63173. return;
  63174. }
  63175. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  63176. attributes: [BABYLON.VertexBuffer.PositionKind],
  63177. uniforms: ["world", "viewProjection", "color"]
  63178. });
  63179. var engine = this._scene.getEngine();
  63180. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63181. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63182. this._indexBuffer = 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]);
  63183. };
  63184. BoundingBoxRenderer.prototype.reset = function () {
  63185. this.renderList.reset();
  63186. };
  63187. BoundingBoxRenderer.prototype.render = function () {
  63188. if (this.renderList.length === 0) {
  63189. return;
  63190. }
  63191. this._prepareRessources();
  63192. if (!this._colorShader.isReady()) {
  63193. return;
  63194. }
  63195. var engine = this._scene.getEngine();
  63196. engine.setDepthWrite(false);
  63197. this._colorShader._preBind();
  63198. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63199. var boundingBox = this.renderList.data[boundingBoxIndex];
  63200. var min = boundingBox.minimum;
  63201. var max = boundingBox.maximum;
  63202. var diff = max.subtract(min);
  63203. var median = min.add(diff.scale(0.5));
  63204. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63205. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63206. .multiply(boundingBox.getWorldMatrix());
  63207. // VBOs
  63208. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63209. if (this.showBackLines) {
  63210. // Back
  63211. engine.setDepthFunctionToGreaterOrEqual();
  63212. this._scene.resetCachedMaterial();
  63213. this._colorShader.setColor4("color", this.backColor.toColor4());
  63214. this._colorShader.bind(worldMatrix);
  63215. // Draw order
  63216. engine.draw(false, 0, 24);
  63217. }
  63218. // Front
  63219. engine.setDepthFunctionToLess();
  63220. this._scene.resetCachedMaterial();
  63221. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63222. this._colorShader.bind(worldMatrix);
  63223. // Draw order
  63224. engine.draw(false, 0, 24);
  63225. }
  63226. this._colorShader.unbind();
  63227. engine.setDepthFunctionToLessOrEqual();
  63228. engine.setDepthWrite(true);
  63229. };
  63230. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63231. this._prepareRessources();
  63232. if (!this._colorShader.isReady()) {
  63233. return;
  63234. }
  63235. var engine = this._scene.getEngine();
  63236. engine.setDepthWrite(false);
  63237. engine.setColorWrite(false);
  63238. this._colorShader._preBind();
  63239. var boundingBox = mesh._boundingInfo.boundingBox;
  63240. var min = boundingBox.minimum;
  63241. var max = boundingBox.maximum;
  63242. var diff = max.subtract(min);
  63243. var median = min.add(diff.scale(0.5));
  63244. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63245. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63246. .multiply(boundingBox.getWorldMatrix());
  63247. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63248. engine.setDepthFunctionToLess();
  63249. this._scene.resetCachedMaterial();
  63250. this._colorShader.bind(worldMatrix);
  63251. engine.draw(false, 0, 24);
  63252. this._colorShader.unbind();
  63253. engine.setDepthFunctionToLessOrEqual();
  63254. engine.setDepthWrite(true);
  63255. engine.setColorWrite(true);
  63256. };
  63257. BoundingBoxRenderer.prototype.dispose = function () {
  63258. if (!this._colorShader) {
  63259. return;
  63260. }
  63261. this.renderList.dispose();
  63262. this._colorShader.dispose();
  63263. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63264. if (buffer) {
  63265. buffer.dispose();
  63266. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63267. }
  63268. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63269. };
  63270. return BoundingBoxRenderer;
  63271. }());
  63272. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63273. })(BABYLON || (BABYLON = {}));
  63274. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63275. var BABYLON;
  63276. (function (BABYLON) {
  63277. var MorphTarget = (function () {
  63278. function MorphTarget(name, influence) {
  63279. if (influence === void 0) { influence = 0; }
  63280. this.name = name;
  63281. this.animations = new Array();
  63282. this.onInfluenceChanged = new BABYLON.Observable();
  63283. this.influence = influence;
  63284. }
  63285. Object.defineProperty(MorphTarget.prototype, "influence", {
  63286. get: function () {
  63287. return this._influence;
  63288. },
  63289. set: function (influence) {
  63290. if (this._influence === influence) {
  63291. return;
  63292. }
  63293. var previous = this._influence;
  63294. this._influence = influence;
  63295. if (this.onInfluenceChanged.hasObservers) {
  63296. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  63297. }
  63298. },
  63299. enumerable: true,
  63300. configurable: true
  63301. });
  63302. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  63303. get: function () {
  63304. return this._normals !== undefined;
  63305. },
  63306. enumerable: true,
  63307. configurable: true
  63308. });
  63309. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  63310. get: function () {
  63311. return this._tangents !== undefined;
  63312. },
  63313. enumerable: true,
  63314. configurable: true
  63315. });
  63316. MorphTarget.prototype.setPositions = function (data) {
  63317. this._positions = new Float32Array(data);
  63318. };
  63319. MorphTarget.prototype.getPositions = function () {
  63320. return this._positions;
  63321. };
  63322. MorphTarget.prototype.setNormals = function (data) {
  63323. this._normals = new Float32Array(data);
  63324. };
  63325. MorphTarget.prototype.getNormals = function () {
  63326. return this._normals;
  63327. };
  63328. MorphTarget.prototype.setTangents = function (data) {
  63329. this._tangents = new Float32Array(data);
  63330. };
  63331. MorphTarget.prototype.getTangents = function () {
  63332. return this._tangents;
  63333. };
  63334. /**
  63335. * Serializes the current target into a Serialization object.
  63336. * Returns the serialized object.
  63337. */
  63338. MorphTarget.prototype.serialize = function () {
  63339. var serializationObject = {};
  63340. serializationObject.name = this.name;
  63341. serializationObject.influence = this.influence;
  63342. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  63343. if (this.hasNormals) {
  63344. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  63345. }
  63346. if (this.hasTangents) {
  63347. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  63348. }
  63349. return serializationObject;
  63350. };
  63351. // Statics
  63352. MorphTarget.Parse = function (serializationObject) {
  63353. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  63354. result.setPositions(serializationObject.positions);
  63355. if (serializationObject.normals) {
  63356. result.setNormals(serializationObject.normals);
  63357. }
  63358. if (serializationObject.tangents) {
  63359. result.setTangents(serializationObject.tangents);
  63360. }
  63361. return result;
  63362. };
  63363. MorphTarget.FromMesh = function (mesh, name, influence) {
  63364. if (!name) {
  63365. name = mesh.name;
  63366. }
  63367. var result = new MorphTarget(name, influence);
  63368. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  63369. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  63370. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  63371. }
  63372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  63373. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  63374. }
  63375. return result;
  63376. };
  63377. return MorphTarget;
  63378. }());
  63379. BABYLON.MorphTarget = MorphTarget;
  63380. })(BABYLON || (BABYLON = {}));
  63381. //# sourceMappingURL=babylon.morphTarget.js.map
  63382. var BABYLON;
  63383. (function (BABYLON) {
  63384. var MorphTargetManager = (function () {
  63385. function MorphTargetManager(scene) {
  63386. this._targets = new Array();
  63387. this._targetObservable = new Array();
  63388. this._activeTargets = new BABYLON.SmartArray(16);
  63389. this._supportsNormals = false;
  63390. this._supportsTangents = false;
  63391. this._vertexCount = 0;
  63392. this._uniqueId = 0;
  63393. this._tempInfluences = new Array();
  63394. if (!scene) {
  63395. scene = BABYLON.Engine.LastCreatedScene;
  63396. }
  63397. this._scene = scene;
  63398. this._scene.morphTargetManagers.push(this);
  63399. this._uniqueId = scene.getUniqueId();
  63400. }
  63401. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  63402. get: function () {
  63403. return this._uniqueId;
  63404. },
  63405. enumerable: true,
  63406. configurable: true
  63407. });
  63408. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  63409. get: function () {
  63410. return this._vertexCount;
  63411. },
  63412. enumerable: true,
  63413. configurable: true
  63414. });
  63415. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  63416. get: function () {
  63417. return this._supportsNormals;
  63418. },
  63419. enumerable: true,
  63420. configurable: true
  63421. });
  63422. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  63423. get: function () {
  63424. return this._supportsTangents;
  63425. },
  63426. enumerable: true,
  63427. configurable: true
  63428. });
  63429. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  63430. get: function () {
  63431. return this._targets.length;
  63432. },
  63433. enumerable: true,
  63434. configurable: true
  63435. });
  63436. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  63437. get: function () {
  63438. return this._activeTargets.length;
  63439. },
  63440. enumerable: true,
  63441. configurable: true
  63442. });
  63443. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  63444. get: function () {
  63445. return this._influences;
  63446. },
  63447. enumerable: true,
  63448. configurable: true
  63449. });
  63450. MorphTargetManager.prototype.getActiveTarget = function (index) {
  63451. return this._activeTargets.data[index];
  63452. };
  63453. MorphTargetManager.prototype.getTarget = function (index) {
  63454. return this._targets[index];
  63455. };
  63456. MorphTargetManager.prototype.addTarget = function (target) {
  63457. var _this = this;
  63458. if (this._vertexCount) {
  63459. if (this._vertexCount !== target.getPositions().length / 3) {
  63460. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  63461. return;
  63462. }
  63463. }
  63464. this._targets.push(target);
  63465. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  63466. _this._syncActiveTargets(needUpdate);
  63467. }));
  63468. this._syncActiveTargets(true);
  63469. };
  63470. MorphTargetManager.prototype.removeTarget = function (target) {
  63471. var index = this._targets.indexOf(target);
  63472. if (index >= 0) {
  63473. this._targets.splice(index, 1);
  63474. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  63475. this._vertexCount = 0;
  63476. this._syncActiveTargets(true);
  63477. }
  63478. };
  63479. /**
  63480. * Serializes the current manager into a Serialization object.
  63481. * Returns the serialized object.
  63482. */
  63483. MorphTargetManager.prototype.serialize = function () {
  63484. var serializationObject = {};
  63485. serializationObject.id = this.uniqueId;
  63486. serializationObject.targets = [];
  63487. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  63488. var target = _a[_i];
  63489. serializationObject.targets.push(target.serialize());
  63490. }
  63491. return serializationObject;
  63492. };
  63493. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  63494. this._syncActiveTargets(needUpdate);
  63495. };
  63496. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  63497. var influenceCount = 0;
  63498. this._activeTargets.reset();
  63499. this._supportsNormals = true;
  63500. this._supportsTangents = true;
  63501. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  63502. var target = _a[_i];
  63503. if (target.influence > 0) {
  63504. this._activeTargets.push(target);
  63505. this._tempInfluences[influenceCount++] = target.influence;
  63506. this._supportsNormals = this._supportsNormals && target.hasNormals;
  63507. this._supportsTangents = this._supportsTangents && target.hasTangents;
  63508. if (this._vertexCount === 0) {
  63509. this._vertexCount = target.getPositions().length / 3;
  63510. }
  63511. }
  63512. }
  63513. if (!this._influences || this._influences.length !== influenceCount) {
  63514. this._influences = new Float32Array(influenceCount);
  63515. }
  63516. for (var index = 0; index < influenceCount; index++) {
  63517. this._influences[index] = this._tempInfluences[index];
  63518. }
  63519. if (needUpdate) {
  63520. // Flag meshes as dirty to resync with the active targets
  63521. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  63522. var mesh = _c[_b];
  63523. if (mesh.morphTargetManager === this) {
  63524. mesh._syncGeometryWithMorphTargetManager();
  63525. }
  63526. }
  63527. }
  63528. };
  63529. // Statics
  63530. MorphTargetManager.Parse = function (serializationObject, scene) {
  63531. var result = new MorphTargetManager(scene);
  63532. result._uniqueId = serializationObject.id;
  63533. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  63534. var targetData = _a[_i];
  63535. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  63536. }
  63537. return result;
  63538. };
  63539. return MorphTargetManager;
  63540. }());
  63541. BABYLON.MorphTargetManager = MorphTargetManager;
  63542. })(BABYLON || (BABYLON = {}));
  63543. //# sourceMappingURL=babylon.morphTargetManager.js.map
  63544. var BABYLON;
  63545. (function (BABYLON) {
  63546. /**
  63547. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  63548. * It can help converting any input color in a desired output one. This can then be used to create effects
  63549. * from sepia, black and white to sixties or futuristic rendering...
  63550. *
  63551. * The only supported format is currently 3dl.
  63552. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  63553. */
  63554. var ColorGradingTexture = (function (_super) {
  63555. __extends(ColorGradingTexture, _super);
  63556. /**
  63557. * Instantiates a ColorGradingTexture from the following parameters.
  63558. *
  63559. * @param url The location of the color gradind data (currently only supporting 3dl)
  63560. * @param scene The scene the texture will be used in
  63561. */
  63562. function ColorGradingTexture(url, scene) {
  63563. var _this = _super.call(this, scene) || this;
  63564. if (!url) {
  63565. return _this;
  63566. }
  63567. _this._textureMatrix = BABYLON.Matrix.Identity();
  63568. _this.name = url;
  63569. _this.url = url;
  63570. _this.hasAlpha = false;
  63571. _this.isCube = false;
  63572. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63573. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63574. _this.anisotropicFilteringLevel = 1;
  63575. _this._texture = _this._getFromCache(url, true);
  63576. if (!_this._texture) {
  63577. if (!scene.useDelayedTextureLoading) {
  63578. _this.loadTexture();
  63579. }
  63580. else {
  63581. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63582. }
  63583. }
  63584. return _this;
  63585. }
  63586. /**
  63587. * Returns the texture matrix used in most of the material.
  63588. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  63589. */
  63590. ColorGradingTexture.prototype.getTextureMatrix = function () {
  63591. return this._textureMatrix;
  63592. };
  63593. /**
  63594. * Occurs when the file being loaded is a .3dl LUT file.
  63595. */
  63596. ColorGradingTexture.prototype.load3dlTexture = function () {
  63597. var _this = this;
  63598. var mipLevels = 0;
  63599. var floatArrayView = null;
  63600. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63601. this._texture = texture;
  63602. var callback = function (text) {
  63603. var data;
  63604. var tempData;
  63605. var line;
  63606. var lines = text.split('\n');
  63607. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  63608. var maxColor = 0;
  63609. for (var i = 0; i < lines.length; i++) {
  63610. line = lines[i];
  63611. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  63612. continue;
  63613. if (line.indexOf('#') === 0)
  63614. continue;
  63615. var words = line.split(" ");
  63616. if (size === 0) {
  63617. // Number of space + one
  63618. size = words.length;
  63619. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  63620. tempData = new Float32Array(size * size * size * 4);
  63621. continue;
  63622. }
  63623. if (size != 0) {
  63624. var r = Math.max(parseInt(words[0]), 0);
  63625. var g = Math.max(parseInt(words[1]), 0);
  63626. var b = Math.max(parseInt(words[2]), 0);
  63627. maxColor = Math.max(r, maxColor);
  63628. maxColor = Math.max(g, maxColor);
  63629. maxColor = Math.max(b, maxColor);
  63630. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  63631. tempData[pixelStorageIndex + 0] = r;
  63632. tempData[pixelStorageIndex + 1] = g;
  63633. tempData[pixelStorageIndex + 2] = b;
  63634. pixelIndexSlice++;
  63635. if (pixelIndexSlice % size == 0) {
  63636. pixelIndexH++;
  63637. pixelIndexSlice = 0;
  63638. if (pixelIndexH % size == 0) {
  63639. pixelIndexW++;
  63640. pixelIndexH = 0;
  63641. }
  63642. }
  63643. }
  63644. }
  63645. for (var i = 0; i < tempData.length; i++) {
  63646. if (i > 0 && (i + 1) % 4 === 0) {
  63647. data[i] = 255;
  63648. }
  63649. else {
  63650. var value = tempData[i];
  63651. data[i] = (value / maxColor * 255);
  63652. }
  63653. }
  63654. texture.updateSize(size * size, size);
  63655. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  63656. };
  63657. BABYLON.Tools.LoadFile(this.url, callback);
  63658. return this._texture;
  63659. };
  63660. /**
  63661. * Starts the loading process of the texture.
  63662. */
  63663. ColorGradingTexture.prototype.loadTexture = function () {
  63664. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  63665. this.load3dlTexture();
  63666. }
  63667. };
  63668. /**
  63669. * Clones the color gradind texture.
  63670. */
  63671. ColorGradingTexture.prototype.clone = function () {
  63672. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  63673. // Base texture
  63674. newTexture.level = this.level;
  63675. return newTexture;
  63676. };
  63677. /**
  63678. * Called during delayed load for textures.
  63679. */
  63680. ColorGradingTexture.prototype.delayLoad = function () {
  63681. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63682. return;
  63683. }
  63684. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63685. this._texture = this._getFromCache(this.url, true);
  63686. if (!this._texture) {
  63687. this.loadTexture();
  63688. }
  63689. };
  63690. /**
  63691. * Parses a color grading texture serialized by Babylon.
  63692. * @param parsedTexture The texture information being parsedTexture
  63693. * @param scene The scene to load the texture in
  63694. * @param rootUrl The root url of the data assets to load
  63695. * @return A color gradind texture
  63696. */
  63697. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63698. var texture = null;
  63699. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63700. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  63701. texture.name = parsedTexture.name;
  63702. texture.level = parsedTexture.level;
  63703. }
  63704. return texture;
  63705. };
  63706. /**
  63707. * Serializes the LUT texture to json format.
  63708. */
  63709. ColorGradingTexture.prototype.serialize = function () {
  63710. if (!this.name) {
  63711. return null;
  63712. }
  63713. var serializationObject = {};
  63714. serializationObject.name = this.name;
  63715. serializationObject.level = this.level;
  63716. serializationObject.customType = "BABYLON.ColorGradingTexture";
  63717. return serializationObject;
  63718. };
  63719. /**
  63720. * Empty line regex stored for GC.
  63721. */
  63722. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  63723. return ColorGradingTexture;
  63724. }(BABYLON.BaseTexture));
  63725. BABYLON.ColorGradingTexture = ColorGradingTexture;
  63726. })(BABYLON || (BABYLON = {}));
  63727. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  63728. var BABYLON;
  63729. (function (BABYLON) {
  63730. /**
  63731. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  63732. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  63733. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  63734. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  63735. */
  63736. var ColorCurves = (function () {
  63737. function ColorCurves() {
  63738. this._dirty = true;
  63739. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  63740. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  63741. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  63742. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  63743. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  63744. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  63745. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  63746. this._globalHue = 30;
  63747. this._globalDensity = 0;
  63748. this._globalSaturation = 0;
  63749. this._globalExposure = 0;
  63750. this._highlightsHue = 30;
  63751. this._highlightsDensity = 0;
  63752. this._highlightsSaturation = 0;
  63753. this._highlightsExposure = 0;
  63754. this._midtonesHue = 30;
  63755. this._midtonesDensity = 0;
  63756. this._midtonesSaturation = 0;
  63757. this._midtonesExposure = 0;
  63758. this._shadowsHue = 30;
  63759. this._shadowsDensity = 0;
  63760. this._shadowsSaturation = 0;
  63761. this._shadowsExposure = 0;
  63762. }
  63763. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  63764. /**
  63765. * Gets the global Hue value.
  63766. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  63767. */
  63768. get: function () {
  63769. return this._globalHue;
  63770. },
  63771. /**
  63772. * Sets the global Hue value.
  63773. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  63774. */
  63775. set: function (value) {
  63776. this._globalHue = value;
  63777. this._dirty = true;
  63778. },
  63779. enumerable: true,
  63780. configurable: true
  63781. });
  63782. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  63783. /**
  63784. * Gets the global Density value.
  63785. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  63786. * Values less than zero provide a filter of opposite hue.
  63787. */
  63788. get: function () {
  63789. return this._globalDensity;
  63790. },
  63791. /**
  63792. * Sets the global Density value.
  63793. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  63794. * Values less than zero provide a filter of opposite hue.
  63795. */
  63796. set: function (value) {
  63797. this._globalDensity = value;
  63798. this._dirty = true;
  63799. },
  63800. enumerable: true,
  63801. configurable: true
  63802. });
  63803. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  63804. /**
  63805. * Gets the global Saturation value.
  63806. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  63807. */
  63808. get: function () {
  63809. return this._globalSaturation;
  63810. },
  63811. /**
  63812. * Sets the global Saturation value.
  63813. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  63814. */
  63815. set: function (value) {
  63816. this._globalSaturation = value;
  63817. this._dirty = true;
  63818. },
  63819. enumerable: true,
  63820. configurable: true
  63821. });
  63822. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  63823. /**
  63824. * Gets the highlights Hue value.
  63825. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  63826. */
  63827. get: function () {
  63828. return this._highlightsHue;
  63829. },
  63830. /**
  63831. * Sets the highlights Hue value.
  63832. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  63833. */
  63834. set: function (value) {
  63835. this._highlightsHue = value;
  63836. this._dirty = true;
  63837. },
  63838. enumerable: true,
  63839. configurable: true
  63840. });
  63841. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  63842. /**
  63843. * Gets the highlights Density value.
  63844. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  63845. * Values less than zero provide a filter of opposite hue.
  63846. */
  63847. get: function () {
  63848. return this._highlightsDensity;
  63849. },
  63850. /**
  63851. * Sets the highlights Density value.
  63852. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  63853. * Values less than zero provide a filter of opposite hue.
  63854. */
  63855. set: function (value) {
  63856. this._highlightsDensity = value;
  63857. this._dirty = true;
  63858. },
  63859. enumerable: true,
  63860. configurable: true
  63861. });
  63862. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  63863. /**
  63864. * Gets the highlights Saturation value.
  63865. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  63866. */
  63867. get: function () {
  63868. return this._highlightsSaturation;
  63869. },
  63870. /**
  63871. * Sets the highlights Saturation value.
  63872. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  63873. */
  63874. set: function (value) {
  63875. this._highlightsSaturation = value;
  63876. this._dirty = true;
  63877. },
  63878. enumerable: true,
  63879. configurable: true
  63880. });
  63881. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  63882. /**
  63883. * Gets the highlights Exposure value.
  63884. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  63885. */
  63886. get: function () {
  63887. return this._highlightsExposure;
  63888. },
  63889. /**
  63890. * Sets the highlights Exposure value.
  63891. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  63892. */
  63893. set: function (value) {
  63894. this._highlightsExposure = value;
  63895. this._dirty = true;
  63896. },
  63897. enumerable: true,
  63898. configurable: true
  63899. });
  63900. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  63901. /**
  63902. * Gets the midtones Hue value.
  63903. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  63904. */
  63905. get: function () {
  63906. return this._midtonesHue;
  63907. },
  63908. /**
  63909. * Sets the midtones Hue value.
  63910. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  63911. */
  63912. set: function (value) {
  63913. this._midtonesHue = value;
  63914. this._dirty = true;
  63915. },
  63916. enumerable: true,
  63917. configurable: true
  63918. });
  63919. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  63920. /**
  63921. * Gets the midtones Density value.
  63922. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  63923. * Values less than zero provide a filter of opposite hue.
  63924. */
  63925. get: function () {
  63926. return this._midtonesDensity;
  63927. },
  63928. /**
  63929. * Sets the midtones Density value.
  63930. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  63931. * Values less than zero provide a filter of opposite hue.
  63932. */
  63933. set: function (value) {
  63934. this._midtonesDensity = value;
  63935. this._dirty = true;
  63936. },
  63937. enumerable: true,
  63938. configurable: true
  63939. });
  63940. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  63941. /**
  63942. * Gets the midtones Saturation value.
  63943. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  63944. */
  63945. get: function () {
  63946. return this._midtonesSaturation;
  63947. },
  63948. /**
  63949. * Sets the midtones Saturation value.
  63950. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  63951. */
  63952. set: function (value) {
  63953. this._midtonesSaturation = value;
  63954. this._dirty = true;
  63955. },
  63956. enumerable: true,
  63957. configurable: true
  63958. });
  63959. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  63960. /**
  63961. * Gets the midtones Exposure value.
  63962. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  63963. */
  63964. get: function () {
  63965. return this._midtonesExposure;
  63966. },
  63967. /**
  63968. * Sets the midtones Exposure value.
  63969. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  63970. */
  63971. set: function (value) {
  63972. this._midtonesExposure = value;
  63973. this._dirty = true;
  63974. },
  63975. enumerable: true,
  63976. configurable: true
  63977. });
  63978. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  63979. /**
  63980. * Gets the shadows Hue value.
  63981. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  63982. */
  63983. get: function () {
  63984. return this._shadowsHue;
  63985. },
  63986. /**
  63987. * Sets the shadows Hue value.
  63988. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  63989. */
  63990. set: function (value) {
  63991. this._shadowsHue = value;
  63992. this._dirty = true;
  63993. },
  63994. enumerable: true,
  63995. configurable: true
  63996. });
  63997. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  63998. /**
  63999. * Gets the shadows Density value.
  64000. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  64001. * Values less than zero provide a filter of opposite hue.
  64002. */
  64003. get: function () {
  64004. return this._shadowsDensity;
  64005. },
  64006. /**
  64007. * Sets the shadows Density value.
  64008. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  64009. * Values less than zero provide a filter of opposite hue.
  64010. */
  64011. set: function (value) {
  64012. this._shadowsDensity = value;
  64013. this._dirty = true;
  64014. },
  64015. enumerable: true,
  64016. configurable: true
  64017. });
  64018. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  64019. /**
  64020. * Gets the shadows Saturation value.
  64021. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  64022. */
  64023. get: function () {
  64024. return this._shadowsSaturation;
  64025. },
  64026. /**
  64027. * Sets the shadows Saturation value.
  64028. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  64029. */
  64030. set: function (value) {
  64031. this._shadowsSaturation = value;
  64032. this._dirty = true;
  64033. },
  64034. enumerable: true,
  64035. configurable: true
  64036. });
  64037. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  64038. /**
  64039. * Gets the shadows Exposure value.
  64040. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  64041. */
  64042. get: function () {
  64043. return this._shadowsExposure;
  64044. },
  64045. /**
  64046. * Sets the shadows Exposure value.
  64047. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  64048. */
  64049. set: function (value) {
  64050. this._shadowsExposure = value;
  64051. this._dirty = true;
  64052. },
  64053. enumerable: true,
  64054. configurable: true
  64055. });
  64056. ColorCurves.prototype.getClassName = function () {
  64057. return "ColorCurves";
  64058. };
  64059. /**
  64060. * Binds the color curves to the shader.
  64061. * @param colorCurves The color curve to bind
  64062. * @param effect The effect to bind to
  64063. */
  64064. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  64065. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  64066. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  64067. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  64068. if (colorCurves._dirty) {
  64069. colorCurves._dirty = false;
  64070. // Fill in global info.
  64071. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  64072. // Compute highlights info.
  64073. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  64074. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  64075. // Compute midtones info.
  64076. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  64077. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  64078. // Compute shadows info.
  64079. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  64080. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  64081. // Compute deltas (neutral is midtones).
  64082. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  64083. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  64084. }
  64085. if (effect) {
  64086. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  64087. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  64088. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  64089. }
  64090. };
  64091. /**
  64092. * Prepare the list of uniforms associated with the ColorCurves effects.
  64093. * @param uniformsList The list of uniforms used in the effect
  64094. */
  64095. ColorCurves.PrepareUniforms = function (uniformsList) {
  64096. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  64097. };
  64098. /**
  64099. * Returns color grading data based on a hue, density, saturation and exposure value.
  64100. * @param filterHue The hue of the color filter.
  64101. * @param filterDensity The density of the color filter.
  64102. * @param saturation The saturation.
  64103. * @param exposure The exposure.
  64104. * @param result The result data container.
  64105. */
  64106. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  64107. if (hue == null) {
  64108. return;
  64109. }
  64110. hue = ColorCurves.clamp(hue, 0, 360);
  64111. density = ColorCurves.clamp(density, -100, 100);
  64112. saturation = ColorCurves.clamp(saturation, -100, 100);
  64113. exposure = ColorCurves.clamp(exposure, -100, 100);
  64114. // Remap the slider/config filter density with non-linear mapping and also scale by half
  64115. // so that the maximum filter density is only 50% control. This provides fine control
  64116. // for small values and reasonable range.
  64117. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  64118. density *= 0.5;
  64119. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  64120. if (density < 0) {
  64121. density *= -1;
  64122. hue = (hue + 180) % 360;
  64123. }
  64124. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  64125. result.scaleToRef(2, result);
  64126. result.a = 1 + 0.01 * saturation;
  64127. };
  64128. /**
  64129. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  64130. * @param value The input slider value in range [-100,100].
  64131. * @returns Adjusted value.
  64132. */
  64133. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  64134. value /= 100;
  64135. var x = Math.abs(value);
  64136. x = Math.pow(x, 2);
  64137. if (value < 0) {
  64138. x *= -1;
  64139. }
  64140. x *= 100;
  64141. return x;
  64142. };
  64143. /**
  64144. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  64145. * @param hue The hue (H) input.
  64146. * @param saturation The saturation (S) input.
  64147. * @param brightness The brightness (B) input.
  64148. * @result An RGBA color represented as Vector4.
  64149. */
  64150. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  64151. var h = ColorCurves.clamp(hue, 0, 360);
  64152. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  64153. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  64154. if (s === 0) {
  64155. result.r = v;
  64156. result.g = v;
  64157. result.b = v;
  64158. }
  64159. else {
  64160. // sector 0 to 5
  64161. h /= 60;
  64162. var i = Math.floor(h);
  64163. // fractional part of h
  64164. var f = h - i;
  64165. var p = v * (1 - s);
  64166. var q = v * (1 - s * f);
  64167. var t = v * (1 - s * (1 - f));
  64168. switch (i) {
  64169. case 0:
  64170. result.r = v;
  64171. result.g = t;
  64172. result.b = p;
  64173. break;
  64174. case 1:
  64175. result.r = q;
  64176. result.g = v;
  64177. result.b = p;
  64178. break;
  64179. case 2:
  64180. result.r = p;
  64181. result.g = v;
  64182. result.b = t;
  64183. break;
  64184. case 3:
  64185. result.r = p;
  64186. result.g = q;
  64187. result.b = v;
  64188. break;
  64189. case 4:
  64190. result.r = t;
  64191. result.g = p;
  64192. result.b = v;
  64193. break;
  64194. default:// case 5:
  64195. result.r = v;
  64196. result.g = p;
  64197. result.b = q;
  64198. break;
  64199. }
  64200. }
  64201. result.a = 1;
  64202. };
  64203. /**
  64204. * Returns a value clamped between min and max
  64205. * @param value The value to clamp
  64206. * @param min The minimum of value
  64207. * @param max The maximum of value
  64208. * @returns The clamped value.
  64209. */
  64210. ColorCurves.clamp = function (value, min, max) {
  64211. return Math.min(Math.max(value, min), max);
  64212. };
  64213. /**
  64214. * Clones the current color curve instance.
  64215. * @return The cloned curves
  64216. */
  64217. ColorCurves.prototype.clone = function () {
  64218. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  64219. };
  64220. /**
  64221. * Serializes the current color curve instance to a json representation.
  64222. * @return a JSON representation
  64223. */
  64224. ColorCurves.prototype.serialize = function () {
  64225. return BABYLON.SerializationHelper.Serialize(this);
  64226. };
  64227. /**
  64228. * Parses the color curve from a json representation.
  64229. * @param source the JSON source to parse
  64230. * @return The parsed curves
  64231. */
  64232. ColorCurves.Parse = function (source) {
  64233. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  64234. };
  64235. __decorate([
  64236. BABYLON.serialize()
  64237. ], ColorCurves.prototype, "_globalHue", void 0);
  64238. __decorate([
  64239. BABYLON.serialize()
  64240. ], ColorCurves.prototype, "_globalDensity", void 0);
  64241. __decorate([
  64242. BABYLON.serialize()
  64243. ], ColorCurves.prototype, "_globalSaturation", void 0);
  64244. __decorate([
  64245. BABYLON.serialize()
  64246. ], ColorCurves.prototype, "_globalExposure", void 0);
  64247. __decorate([
  64248. BABYLON.serialize()
  64249. ], ColorCurves.prototype, "_highlightsHue", void 0);
  64250. __decorate([
  64251. BABYLON.serialize()
  64252. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  64253. __decorate([
  64254. BABYLON.serialize()
  64255. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  64256. __decorate([
  64257. BABYLON.serialize()
  64258. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  64259. __decorate([
  64260. BABYLON.serialize()
  64261. ], ColorCurves.prototype, "_midtonesHue", void 0);
  64262. __decorate([
  64263. BABYLON.serialize()
  64264. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  64265. __decorate([
  64266. BABYLON.serialize()
  64267. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  64268. __decorate([
  64269. BABYLON.serialize()
  64270. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  64271. return ColorCurves;
  64272. }());
  64273. BABYLON.ColorCurves = ColorCurves;
  64274. })(BABYLON || (BABYLON = {}));
  64275. //# sourceMappingURL=babylon.colorCurves.js.map
  64276. var BABYLON;
  64277. (function (BABYLON) {
  64278. var Octree = (function () {
  64279. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  64280. if (maxDepth === void 0) { maxDepth = 2; }
  64281. this.maxDepth = maxDepth;
  64282. this.dynamicContent = new Array();
  64283. this._maxBlockCapacity = maxBlockCapacity || 64;
  64284. this._selectionContent = new BABYLON.SmartArray(1024);
  64285. this._creationFunc = creationFunc;
  64286. }
  64287. // Methods
  64288. Octree.prototype.update = function (worldMin, worldMax, entries) {
  64289. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  64290. };
  64291. Octree.prototype.addMesh = function (entry) {
  64292. for (var index = 0; index < this.blocks.length; index++) {
  64293. var block = this.blocks[index];
  64294. block.addEntry(entry);
  64295. }
  64296. };
  64297. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  64298. this._selectionContent.reset();
  64299. for (var index = 0; index < this.blocks.length; index++) {
  64300. var block = this.blocks[index];
  64301. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  64302. }
  64303. if (allowDuplicate) {
  64304. this._selectionContent.concat(this.dynamicContent);
  64305. }
  64306. else {
  64307. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64308. }
  64309. return this._selectionContent;
  64310. };
  64311. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  64312. this._selectionContent.reset();
  64313. for (var index = 0; index < this.blocks.length; index++) {
  64314. var block = this.blocks[index];
  64315. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  64316. }
  64317. if (allowDuplicate) {
  64318. this._selectionContent.concat(this.dynamicContent);
  64319. }
  64320. else {
  64321. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64322. }
  64323. return this._selectionContent;
  64324. };
  64325. Octree.prototype.intersectsRay = function (ray) {
  64326. this._selectionContent.reset();
  64327. for (var index = 0; index < this.blocks.length; index++) {
  64328. var block = this.blocks[index];
  64329. block.intersectsRay(ray, this._selectionContent);
  64330. }
  64331. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64332. return this._selectionContent;
  64333. };
  64334. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  64335. target.blocks = new Array();
  64336. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  64337. // Segmenting space
  64338. for (var x = 0; x < 2; x++) {
  64339. for (var y = 0; y < 2; y++) {
  64340. for (var z = 0; z < 2; z++) {
  64341. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  64342. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  64343. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  64344. block.addEntries(entries);
  64345. target.blocks.push(block);
  64346. }
  64347. }
  64348. }
  64349. };
  64350. Octree.CreationFuncForMeshes = function (entry, block) {
  64351. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  64352. block.entries.push(entry);
  64353. }
  64354. };
  64355. Octree.CreationFuncForSubMeshes = function (entry, block) {
  64356. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  64357. block.entries.push(entry);
  64358. }
  64359. };
  64360. return Octree;
  64361. }());
  64362. BABYLON.Octree = Octree;
  64363. })(BABYLON || (BABYLON = {}));
  64364. //# sourceMappingURL=babylon.octree.js.map
  64365. var BABYLON;
  64366. (function (BABYLON) {
  64367. var OctreeBlock = (function () {
  64368. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  64369. this.entries = new Array();
  64370. this._boundingVectors = new Array();
  64371. this._capacity = capacity;
  64372. this._depth = depth;
  64373. this._maxDepth = maxDepth;
  64374. this._creationFunc = creationFunc;
  64375. this._minPoint = minPoint;
  64376. this._maxPoint = maxPoint;
  64377. this._boundingVectors.push(minPoint.clone());
  64378. this._boundingVectors.push(maxPoint.clone());
  64379. this._boundingVectors.push(minPoint.clone());
  64380. this._boundingVectors[2].x = maxPoint.x;
  64381. this._boundingVectors.push(minPoint.clone());
  64382. this._boundingVectors[3].y = maxPoint.y;
  64383. this._boundingVectors.push(minPoint.clone());
  64384. this._boundingVectors[4].z = maxPoint.z;
  64385. this._boundingVectors.push(maxPoint.clone());
  64386. this._boundingVectors[5].z = minPoint.z;
  64387. this._boundingVectors.push(maxPoint.clone());
  64388. this._boundingVectors[6].x = minPoint.x;
  64389. this._boundingVectors.push(maxPoint.clone());
  64390. this._boundingVectors[7].y = minPoint.y;
  64391. }
  64392. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  64393. // Property
  64394. get: function () {
  64395. return this._capacity;
  64396. },
  64397. enumerable: true,
  64398. configurable: true
  64399. });
  64400. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  64401. get: function () {
  64402. return this._minPoint;
  64403. },
  64404. enumerable: true,
  64405. configurable: true
  64406. });
  64407. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  64408. get: function () {
  64409. return this._maxPoint;
  64410. },
  64411. enumerable: true,
  64412. configurable: true
  64413. });
  64414. // Methods
  64415. OctreeBlock.prototype.addEntry = function (entry) {
  64416. if (this.blocks) {
  64417. for (var index = 0; index < this.blocks.length; index++) {
  64418. var block = this.blocks[index];
  64419. block.addEntry(entry);
  64420. }
  64421. return;
  64422. }
  64423. this._creationFunc(entry, this);
  64424. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  64425. this.createInnerBlocks();
  64426. }
  64427. };
  64428. OctreeBlock.prototype.addEntries = function (entries) {
  64429. for (var index = 0; index < entries.length; index++) {
  64430. var mesh = entries[index];
  64431. this.addEntry(mesh);
  64432. }
  64433. };
  64434. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  64435. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  64436. if (this.blocks) {
  64437. for (var index = 0; index < this.blocks.length; index++) {
  64438. var block = this.blocks[index];
  64439. block.select(frustumPlanes, selection, allowDuplicate);
  64440. }
  64441. return;
  64442. }
  64443. if (allowDuplicate) {
  64444. selection.concat(this.entries);
  64445. }
  64446. else {
  64447. selection.concatWithNoDuplicate(this.entries);
  64448. }
  64449. }
  64450. };
  64451. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  64452. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  64453. if (this.blocks) {
  64454. for (var index = 0; index < this.blocks.length; index++) {
  64455. var block = this.blocks[index];
  64456. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  64457. }
  64458. return;
  64459. }
  64460. if (allowDuplicate) {
  64461. selection.concat(this.entries);
  64462. }
  64463. else {
  64464. selection.concatWithNoDuplicate(this.entries);
  64465. }
  64466. }
  64467. };
  64468. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  64469. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  64470. if (this.blocks) {
  64471. for (var index = 0; index < this.blocks.length; index++) {
  64472. var block = this.blocks[index];
  64473. block.intersectsRay(ray, selection);
  64474. }
  64475. return;
  64476. }
  64477. selection.concatWithNoDuplicate(this.entries);
  64478. }
  64479. };
  64480. OctreeBlock.prototype.createInnerBlocks = function () {
  64481. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  64482. };
  64483. return OctreeBlock;
  64484. }());
  64485. BABYLON.OctreeBlock = OctreeBlock;
  64486. })(BABYLON || (BABYLON = {}));
  64487. //# sourceMappingURL=babylon.octreeBlock.js.map
  64488. var BABYLON;
  64489. (function (BABYLON) {
  64490. var SIMDVector3 = (function () {
  64491. function SIMDVector3() {
  64492. }
  64493. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  64494. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  64495. };
  64496. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  64497. var m = transformation.m;
  64498. var m0 = SIMD.Float32x4.load(m, 0);
  64499. var m1 = SIMD.Float32x4.load(m, 4);
  64500. var m2 = SIMD.Float32x4.load(m, 8);
  64501. var m3 = SIMD.Float32x4.load(m, 12);
  64502. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  64503. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  64504. result.x = SIMD.Float32x4.extractLane(r, 0);
  64505. result.y = SIMD.Float32x4.extractLane(r, 1);
  64506. result.z = SIMD.Float32x4.extractLane(r, 2);
  64507. };
  64508. return SIMDVector3;
  64509. }());
  64510. var SIMDMatrix = (function () {
  64511. function SIMDMatrix() {
  64512. }
  64513. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  64514. var tm = this.m;
  64515. var om = other.m;
  64516. var m0 = SIMD.Float32x4.load(om, 0);
  64517. var m1 = SIMD.Float32x4.load(om, 4);
  64518. var m2 = SIMD.Float32x4.load(om, 8);
  64519. var m3 = SIMD.Float32x4.load(om, 12);
  64520. for (var i = 0; i < 16; i += 4) {
  64521. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  64522. }
  64523. return this;
  64524. };
  64525. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  64526. var src = this.m;
  64527. var dest = other.m;
  64528. // Load the 4 rows
  64529. var src0 = SIMD.Float32x4.load(src, 0);
  64530. var src1 = SIMD.Float32x4.load(src, 4);
  64531. var src2 = SIMD.Float32x4.load(src, 8);
  64532. var src3 = SIMD.Float32x4.load(src, 12);
  64533. // Transpose the source matrix. Sort of. Not a true transpose operation
  64534. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  64535. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  64536. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  64537. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  64538. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  64539. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  64540. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  64541. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  64542. // This is a true transposition, but it will lead to an incorrect result
  64543. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  64544. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  64545. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  64546. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  64547. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  64548. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  64549. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  64550. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  64551. // ----
  64552. tmp1 = SIMD.Float32x4.mul(row2, row3);
  64553. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64554. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  64555. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  64556. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64557. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  64558. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  64559. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  64560. // ----
  64561. tmp1 = SIMD.Float32x4.mul(row1, row2);
  64562. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64563. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  64564. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  64565. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64566. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  64567. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  64568. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  64569. // ----
  64570. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  64571. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64572. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  64573. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  64574. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  64575. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64576. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  64577. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  64578. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  64579. // ----
  64580. tmp1 = SIMD.Float32x4.mul(row0, row1);
  64581. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64582. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  64583. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  64584. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64585. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  64586. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  64587. // ----
  64588. tmp1 = SIMD.Float32x4.mul(row0, row3);
  64589. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64590. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  64591. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  64592. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64593. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  64594. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  64595. // ----
  64596. tmp1 = SIMD.Float32x4.mul(row0, row2);
  64597. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64598. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  64599. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  64600. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64601. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  64602. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  64603. // Compute determinant
  64604. var det = SIMD.Float32x4.mul(row0, minor0);
  64605. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  64606. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  64607. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  64608. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  64609. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  64610. // These shuffles aren't necessary if the faulty transposition is done
  64611. // up at the top of this function.
  64612. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  64613. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  64614. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  64615. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  64616. // Compute final values by multiplying with 1/det
  64617. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  64618. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  64619. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  64620. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  64621. return this;
  64622. };
  64623. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  64624. var out = result.m;
  64625. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  64626. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  64627. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  64628. // cc.kmVec3Subtract(f, pCenter, pEye);
  64629. var f = SIMD.Float32x4.sub(center, eye);
  64630. // cc.kmVec3Normalize(f, f);
  64631. var tmp = SIMD.Float32x4.mul(f, f);
  64632. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64633. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64634. // cc.kmVec3Assign(up, pUp);
  64635. // cc.kmVec3Normalize(up, up);
  64636. tmp = SIMD.Float32x4.mul(up, up);
  64637. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64638. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64639. // cc.kmVec3Cross(s, f, up);
  64640. 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)));
  64641. // cc.kmVec3Normalize(s, s);
  64642. tmp = SIMD.Float32x4.mul(s, s);
  64643. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64644. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64645. // cc.kmVec3Cross(u, s, f);
  64646. 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)));
  64647. // cc.kmVec3Normalize(s, s);
  64648. tmp = SIMD.Float32x4.mul(s, s);
  64649. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64650. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64651. var zero = SIMD.Float32x4.splat(0.0);
  64652. s = SIMD.Float32x4.neg(s);
  64653. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  64654. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  64655. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  64656. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  64657. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  64658. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  64659. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  64660. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  64661. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  64662. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  64663. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  64664. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  64665. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  64666. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  64667. };
  64668. return SIMDMatrix;
  64669. }());
  64670. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  64671. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  64672. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  64673. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  64674. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  64675. var SIMDHelper = (function () {
  64676. function SIMDHelper() {
  64677. }
  64678. Object.defineProperty(SIMDHelper, "IsEnabled", {
  64679. get: function () {
  64680. return SIMDHelper._isEnabled;
  64681. },
  64682. enumerable: true,
  64683. configurable: true
  64684. });
  64685. SIMDHelper.DisableSIMD = function () {
  64686. // Replace functions
  64687. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  64688. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  64689. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  64690. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  64691. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  64692. SIMDHelper._isEnabled = false;
  64693. };
  64694. SIMDHelper.EnableSIMD = function () {
  64695. if (self.SIMD === undefined) {
  64696. return;
  64697. }
  64698. // check if polyfills needed
  64699. if (!self.Math.fround) {
  64700. self.Math.fround = (function (array) { return function (x) {
  64701. return array[0] = x, array[0];
  64702. }; })(new Float32Array(1));
  64703. }
  64704. if (!self.Math.imul) {
  64705. self.Math.imul = function (a, b) {
  64706. var ah = (a >>> 16) & 0xffff;
  64707. var al = a & 0xffff;
  64708. var bh = (b >>> 16) & 0xffff;
  64709. var bl = b & 0xffff;
  64710. // the shift by 0 fixes the sign on the high part
  64711. // the final |0 converts the unsigned value into a signed value
  64712. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  64713. };
  64714. }
  64715. // Replace functions
  64716. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  64717. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  64718. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  64719. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  64720. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  64721. SIMDHelper._isEnabled = true;
  64722. };
  64723. SIMDHelper._isEnabled = false;
  64724. return SIMDHelper;
  64725. }());
  64726. BABYLON.SIMDHelper = SIMDHelper;
  64727. })(BABYLON || (BABYLON = {}));
  64728. //# sourceMappingURL=babylon.math.SIMD.js.map
  64729. var BABYLON;
  64730. (function (BABYLON) {
  64731. var VRDistortionCorrectionPostProcess = (function (_super) {
  64732. __extends(VRDistortionCorrectionPostProcess, _super);
  64733. //ANY
  64734. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  64735. var _this = _super.call(this, name, "vrDistortionCorrection", [
  64736. 'LensCenter',
  64737. 'Scale',
  64738. 'ScaleIn',
  64739. 'HmdWarpParam'
  64740. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  64741. _this._isRightEye = isRightEye;
  64742. _this._distortionFactors = vrMetrics.distortionK;
  64743. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  64744. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  64745. _this.onSizeChangedObservable.add(function () {
  64746. _this.aspectRatio = _this.width * .5 / _this.height;
  64747. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  64748. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  64749. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  64750. });
  64751. _this.onApplyObservable.add(function (effect) {
  64752. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  64753. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  64754. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  64755. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  64756. });
  64757. return _this;
  64758. }
  64759. return VRDistortionCorrectionPostProcess;
  64760. }(BABYLON.PostProcess));
  64761. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  64762. })(BABYLON || (BABYLON = {}));
  64763. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  64764. var BABYLON;
  64765. (function (BABYLON) {
  64766. var AnaglyphPostProcess = (function (_super) {
  64767. __extends(AnaglyphPostProcess, _super);
  64768. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  64769. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  64770. _this._passedProcess = rigCameras[0]._rigPostProcess;
  64771. _this.onApplyObservable.add(function (effect) {
  64772. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  64773. });
  64774. return _this;
  64775. }
  64776. return AnaglyphPostProcess;
  64777. }(BABYLON.PostProcess));
  64778. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  64779. })(BABYLON || (BABYLON = {}));
  64780. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  64781. var BABYLON;
  64782. (function (BABYLON) {
  64783. var StereoscopicInterlacePostProcess = (function (_super) {
  64784. __extends(StereoscopicInterlacePostProcess, _super);
  64785. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  64786. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  64787. _this._passedProcess = rigCameras[0]._rigPostProcess;
  64788. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  64789. _this.onSizeChangedObservable.add(function () {
  64790. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  64791. });
  64792. _this.onApplyObservable.add(function (effect) {
  64793. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  64794. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  64795. });
  64796. return _this;
  64797. }
  64798. return StereoscopicInterlacePostProcess;
  64799. }(BABYLON.PostProcess));
  64800. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  64801. })(BABYLON || (BABYLON = {}));
  64802. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  64803. var BABYLON;
  64804. (function (BABYLON) {
  64805. var FreeCameraDeviceOrientationInput = (function () {
  64806. function FreeCameraDeviceOrientationInput() {
  64807. var _this = this;
  64808. this._screenOrientationAngle = 0;
  64809. this._screenQuaternion = new BABYLON.Quaternion();
  64810. this._alpha = 0;
  64811. this._beta = 0;
  64812. this._gamma = 0;
  64813. this._orientationChanged = function () {
  64814. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  64815. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  64816. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  64817. };
  64818. this._deviceOrientation = function (evt) {
  64819. _this._alpha = evt.alpha;
  64820. _this._beta = evt.beta;
  64821. _this._gamma = evt.gamma;
  64822. };
  64823. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  64824. this._orientationChanged();
  64825. }
  64826. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  64827. get: function () {
  64828. return this._camera;
  64829. },
  64830. set: function (camera) {
  64831. this._camera = camera;
  64832. if (this._camera != null && !this._camera.rotationQuaternion) {
  64833. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  64834. }
  64835. },
  64836. enumerable: true,
  64837. configurable: true
  64838. });
  64839. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  64840. window.addEventListener("orientationchange", this._orientationChanged);
  64841. window.addEventListener("deviceorientation", this._deviceOrientation);
  64842. //In certain cases, the attach control is called AFTER orientation was changed,
  64843. //So this is needed.
  64844. this._orientationChanged();
  64845. };
  64846. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  64847. window.removeEventListener("orientationchange", this._orientationChanged);
  64848. window.removeEventListener("deviceorientation", this._deviceOrientation);
  64849. };
  64850. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  64851. //if no device orientation provided, don't update the rotation.
  64852. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  64853. if (!this._alpha)
  64854. return;
  64855. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  64856. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  64857. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  64858. //Mirror on XY Plane
  64859. this._camera.rotationQuaternion.z *= -1;
  64860. this._camera.rotationQuaternion.w *= -1;
  64861. };
  64862. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  64863. return "FreeCameraDeviceOrientationInput";
  64864. };
  64865. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  64866. return "deviceOrientation";
  64867. };
  64868. return FreeCameraDeviceOrientationInput;
  64869. }());
  64870. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  64871. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  64872. })(BABYLON || (BABYLON = {}));
  64873. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  64874. var BABYLON;
  64875. (function (BABYLON) {
  64876. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  64877. function ArcRotateCameraVRDeviceOrientationInput() {
  64878. this.alphaCorrection = 1;
  64879. this.betaCorrection = 1;
  64880. this.gammaCorrection = 1;
  64881. this._alpha = 0;
  64882. this._beta = 0;
  64883. this._gamma = 0;
  64884. this._dirty = false;
  64885. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  64886. }
  64887. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  64888. this.camera.attachControl(element, noPreventDefault);
  64889. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  64890. };
  64891. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  64892. var camera = this.camera;
  64893. this._alpha = +evt.alpha | 0;
  64894. this._beta = +evt.beta | 0;
  64895. this._gamma = +evt.gamma | 0;
  64896. this._dirty = true;
  64897. };
  64898. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  64899. if (this._dirty) {
  64900. this._dirty = false;
  64901. if (this._gamma < 0) {
  64902. this._gamma = 180 + this._gamma;
  64903. }
  64904. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  64905. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  64906. }
  64907. };
  64908. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  64909. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  64910. };
  64911. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  64912. return "ArcRotateCameraVRDeviceOrientationInput";
  64913. };
  64914. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  64915. return "VRDeviceOrientation";
  64916. };
  64917. return ArcRotateCameraVRDeviceOrientationInput;
  64918. }());
  64919. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  64920. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  64921. })(BABYLON || (BABYLON = {}));
  64922. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  64923. var BABYLON;
  64924. (function (BABYLON) {
  64925. var VRCameraMetrics = (function () {
  64926. function VRCameraMetrics() {
  64927. this.compensateDistortion = true;
  64928. }
  64929. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  64930. get: function () {
  64931. return this.hResolution / (2 * this.vResolution);
  64932. },
  64933. enumerable: true,
  64934. configurable: true
  64935. });
  64936. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  64937. get: function () {
  64938. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  64939. },
  64940. enumerable: true,
  64941. configurable: true
  64942. });
  64943. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  64944. get: function () {
  64945. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  64946. var h = (4 * meters) / this.hScreenSize;
  64947. return BABYLON.Matrix.Translation(h, 0, 0);
  64948. },
  64949. enumerable: true,
  64950. configurable: true
  64951. });
  64952. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  64953. get: function () {
  64954. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  64955. var h = (4 * meters) / this.hScreenSize;
  64956. return BABYLON.Matrix.Translation(-h, 0, 0);
  64957. },
  64958. enumerable: true,
  64959. configurable: true
  64960. });
  64961. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  64962. get: function () {
  64963. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  64964. },
  64965. enumerable: true,
  64966. configurable: true
  64967. });
  64968. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  64969. get: function () {
  64970. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  64971. },
  64972. enumerable: true,
  64973. configurable: true
  64974. });
  64975. VRCameraMetrics.GetDefault = function () {
  64976. var result = new VRCameraMetrics();
  64977. result.hResolution = 1280;
  64978. result.vResolution = 800;
  64979. result.hScreenSize = 0.149759993;
  64980. result.vScreenSize = 0.0935999975;
  64981. result.vScreenCenter = 0.0467999987;
  64982. result.eyeToScreenDistance = 0.0410000011;
  64983. result.lensSeparationDistance = 0.0635000020;
  64984. result.interpupillaryDistance = 0.0640000030;
  64985. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  64986. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  64987. result.postProcessScaleFactor = 1.714605507808412;
  64988. result.lensCenterOffset = 0.151976421;
  64989. return result;
  64990. };
  64991. return VRCameraMetrics;
  64992. }());
  64993. BABYLON.VRCameraMetrics = VRCameraMetrics;
  64994. })(BABYLON || (BABYLON = {}));
  64995. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  64996. var BABYLON;
  64997. (function (BABYLON) {
  64998. var WebVRFreeCamera = (function (_super) {
  64999. __extends(WebVRFreeCamera, _super);
  65000. function WebVRFreeCamera(name, position, scene, webVROptions) {
  65001. if (webVROptions === void 0) { webVROptions = {}; }
  65002. var _this = _super.call(this, name, position, scene) || this;
  65003. _this.webVROptions = webVROptions;
  65004. _this._vrDevice = null;
  65005. _this.rawPose = null;
  65006. _this._vrEnabled = false;
  65007. _this._specsVersion = 1.1;
  65008. _this._attached = false;
  65009. _this._positionOffset = BABYLON.Vector3.Zero();
  65010. _this._descendants = [];
  65011. _this.devicePosition = BABYLON.Vector3.Zero();
  65012. _this.deviceScaleFactor = 1;
  65013. _this.controllers = [];
  65014. _this.onControllersAttachedObservable = new BABYLON.Observable();
  65015. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  65016. _this.minZ = 0.1;
  65017. //legacy support - the compensation boolean was removed.
  65018. if (arguments.length === 5) {
  65019. _this.webVROptions = arguments[4];
  65020. }
  65021. // default webVR options
  65022. if (_this.webVROptions.trackPosition == undefined) {
  65023. _this.webVROptions.trackPosition = true;
  65024. }
  65025. if (_this.webVROptions.controllerMeshes == undefined) {
  65026. _this.webVROptions.controllerMeshes = true;
  65027. }
  65028. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  65029. _this.webVROptions.defaultLightingOnControllers = true;
  65030. }
  65031. _this.rotationQuaternion = new BABYLON.Quaternion();
  65032. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65033. if (_this.webVROptions && _this.webVROptions.positionScale) {
  65034. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  65035. }
  65036. //enable VR
  65037. _this.getEngine().initWebVR();
  65038. //check specs version
  65039. if (!window.VRFrameData) {
  65040. _this._specsVersion = 1.0;
  65041. _this._frameData = {};
  65042. }
  65043. else {
  65044. _this._frameData = new VRFrameData();
  65045. }
  65046. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  65047. if (!device) {
  65048. return;
  65049. }
  65050. _this._vrEnabled = true;
  65051. _this._vrDevice = device;
  65052. //reset the rig parameters.
  65053. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  65054. if (_this._attached) {
  65055. _this.getEngine().enableVR(_this._vrDevice);
  65056. }
  65057. });
  65058. /**
  65059. * The idea behind the following lines:
  65060. * objects that have the camera as parent should actually have the rig cameras as a parent.
  65061. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  65062. * the second will not show it correctly.
  65063. *
  65064. * To solve this - each object that has the camera as parent will be added to a protected array.
  65065. * When the rig camera renders, it will take this array and set all of those to be its children.
  65066. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  65067. * Amazing!
  65068. */
  65069. scene.onBeforeCameraRenderObservable.add(function (camera) {
  65070. if (camera.parent === _this && _this.rigParenting) {
  65071. _this._descendants = _this.getDescendants(true, function (n) {
  65072. // don't take the cameras or the controllers!
  65073. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  65074. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  65075. return !isController && !isRigCamera;
  65076. });
  65077. _this._descendants.forEach(function (node) {
  65078. node.parent = camera;
  65079. });
  65080. }
  65081. });
  65082. scene.onAfterCameraRenderObservable.add(function (camera) {
  65083. if (camera.parent === _this && _this.rigParenting) {
  65084. _this._descendants.forEach(function (node) {
  65085. node.parent = _this;
  65086. });
  65087. }
  65088. });
  65089. return _this;
  65090. }
  65091. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  65092. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  65093. var gp = _a[_i];
  65094. if (gp.hand === name) {
  65095. return gp;
  65096. }
  65097. }
  65098. return undefined;
  65099. };
  65100. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  65101. get: function () {
  65102. if (!this._leftController) {
  65103. this._leftController = this.getControllerByName("left");
  65104. }
  65105. return this._leftController;
  65106. },
  65107. enumerable: true,
  65108. configurable: true
  65109. });
  65110. ;
  65111. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  65112. get: function () {
  65113. if (!this._rightController) {
  65114. this._rightController = this.getControllerByName("right");
  65115. }
  65116. return this._rightController;
  65117. },
  65118. enumerable: true,
  65119. configurable: true
  65120. });
  65121. ;
  65122. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  65123. if (length === void 0) { length = 100; }
  65124. if (this.leftCamera) {
  65125. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  65126. }
  65127. else {
  65128. return _super.prototype.getForwardRay.call(this, length);
  65129. }
  65130. };
  65131. WebVRFreeCamera.prototype._checkInputs = function () {
  65132. if (this._vrEnabled) {
  65133. if (this._specsVersion === 1.1) {
  65134. this._vrDevice.getFrameData(this._frameData);
  65135. }
  65136. else {
  65137. //backwards comp
  65138. var pose = this._vrDevice.getPose();
  65139. this._frameData.pose = pose;
  65140. }
  65141. this.updateFromDevice(this._frameData.pose);
  65142. }
  65143. _super.prototype._checkInputs.call(this);
  65144. };
  65145. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  65146. if (poseData && poseData.orientation) {
  65147. this.rawPose = poseData;
  65148. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  65149. if (this.getScene().useRightHandedSystem) {
  65150. this.deviceRotationQuaternion.z *= -1;
  65151. this.deviceRotationQuaternion.w *= -1;
  65152. }
  65153. if (this.webVROptions.trackPosition && this.rawPose.position) {
  65154. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  65155. if (this.getScene().useRightHandedSystem) {
  65156. this.devicePosition.z *= -1;
  65157. }
  65158. }
  65159. }
  65160. };
  65161. /**
  65162. * WebVR's attach control will start broadcasting frames to the device.
  65163. * Note that in certain browsers (chrome for example) this function must be called
  65164. * within a user-interaction callback. Example:
  65165. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  65166. *
  65167. * @param {HTMLElement} element
  65168. * @param {boolean} [noPreventDefault]
  65169. *
  65170. * @memberOf WebVRFreeCamera
  65171. */
  65172. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  65173. _super.prototype.attachControl.call(this, element, noPreventDefault);
  65174. this._attached = true;
  65175. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  65176. if (this._vrEnabled) {
  65177. this.getEngine().enableVR(this._vrDevice);
  65178. }
  65179. // try to attach the controllers, if found.
  65180. this.initControllers();
  65181. };
  65182. WebVRFreeCamera.prototype.detachControl = function (element) {
  65183. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65184. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65185. _super.prototype.detachControl.call(this, element);
  65186. this._vrEnabled = false;
  65187. this._attached = false;
  65188. this.getEngine().disableVR();
  65189. };
  65190. WebVRFreeCamera.prototype.getClassName = function () {
  65191. return "WebVRFreeCamera";
  65192. };
  65193. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  65194. //uses the vrDisplay's "resetPose()".
  65195. //pitch and roll won't be affected.
  65196. this._vrDevice.resetPose();
  65197. };
  65198. WebVRFreeCamera.prototype._updateRigCameras = function () {
  65199. var camLeft = this._rigCameras[0];
  65200. var camRight = this._rigCameras[1];
  65201. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65202. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65203. camLeft.position.copyFrom(this.devicePosition);
  65204. camRight.position.copyFrom(this.devicePosition);
  65205. };
  65206. /**
  65207. * This function is called by the two RIG cameras.
  65208. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  65209. */
  65210. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  65211. var _this = this;
  65212. //WebVR 1.0
  65213. if (this._cameraRigParams["specs"] === 1.0) {
  65214. this._updateCameraRotationMatrix();
  65215. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65216. // Computing target and final matrix
  65217. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65218. if (this.getScene().useRightHandedSystem) {
  65219. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65220. }
  65221. else {
  65222. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65223. }
  65224. //now move the eye in the right direction
  65225. var eyeParams = this._cameraRigParams["eyeParameters"];
  65226. var offset = eyeParams.offset;
  65227. // it will actually always be 0, but just in case
  65228. if (this.getScene().useRightHandedSystem) {
  65229. offset[2] *= -1;
  65230. }
  65231. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  65232. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  65233. }
  65234. else {
  65235. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  65236. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  65237. if (!this.getScene().useRightHandedSystem) {
  65238. [2, 6, 8, 9, 14].forEach(function (num) {
  65239. _this._webvrViewMatrix.m[num] *= -1;
  65240. });
  65241. }
  65242. // update the camera rotation matrix
  65243. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  65244. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65245. // Computing target and final matrix
  65246. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65247. }
  65248. var parentCamera = this._cameraRigParams["parentCamera"];
  65249. // should the view matrix be updated with scale and position offset?
  65250. if (parentCamera.deviceScaleFactor !== 1) {
  65251. this._webvrViewMatrix.invert();
  65252. // scale the position, if set
  65253. if (parentCamera.deviceScaleFactor) {
  65254. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  65255. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  65256. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  65257. }
  65258. this._webvrViewMatrix.invert();
  65259. }
  65260. return this._webvrViewMatrix;
  65261. };
  65262. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  65263. var _this = this;
  65264. if (this._cameraRigParams["specs"] === 1.0) {
  65265. var eyeParams = this._cameraRigParams["eyeParameters"];
  65266. // deprecated!!
  65267. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, this.minZ, this.maxZ, this._projectionMatrix, this.getScene().useRightHandedSystem);
  65268. }
  65269. else {
  65270. var parentCamera = this.parent;
  65271. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  65272. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  65273. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  65274. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  65275. //babylon compatible matrix
  65276. if (!this.getScene().useRightHandedSystem) {
  65277. [8, 9, 10, 11].forEach(function (num) {
  65278. _this._projectionMatrix.m[num] *= -1;
  65279. });
  65280. }
  65281. }
  65282. return this._projectionMatrix;
  65283. };
  65284. WebVRFreeCamera.prototype.initControllers = function () {
  65285. var _this = this;
  65286. this.controllers = [];
  65287. var manager = this.getScene().gamepadManager;
  65288. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65289. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  65290. var webVrController = gamepad;
  65291. var index = _this.controllers.indexOf(webVrController);
  65292. if (index === -1) {
  65293. // we are good
  65294. return;
  65295. }
  65296. _this.controllers.splice(index, 1);
  65297. }
  65298. });
  65299. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65300. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  65301. var webVrController = gamepad;
  65302. if (_this.webVROptions.controllerMeshes) {
  65303. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  65304. if (_this.webVROptions.defaultLightingOnControllers) {
  65305. if (!_this._lightOnControllers) {
  65306. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  65307. }
  65308. loadedMesh.getChildren().forEach(function (mesh) {
  65309. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  65310. });
  65311. }
  65312. });
  65313. }
  65314. webVrController.attachToPoseControlledCamera(_this);
  65315. // since this is async - sanity check. Is the controller already stored?
  65316. if (_this.controllers.indexOf(webVrController) === -1) {
  65317. //add to the controllers array
  65318. _this.controllers.push(webVrController);
  65319. //did we find enough controllers? Great! let the developer know.
  65320. if (_this.controllers.length >= 2) {
  65321. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  65322. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  65323. // So we're overriding setting left & right manually to be sure
  65324. var firstViveWandDetected = false;
  65325. for (var i = 0; i < _this.controllers.length; i++) {
  65326. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  65327. if (!firstViveWandDetected) {
  65328. firstViveWandDetected = true;
  65329. _this.controllers[i].hand = "left";
  65330. }
  65331. else {
  65332. _this.controllers[i].hand = "right";
  65333. }
  65334. }
  65335. }
  65336. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  65337. }
  65338. }
  65339. }
  65340. });
  65341. };
  65342. return WebVRFreeCamera;
  65343. }(BABYLON.FreeCamera));
  65344. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  65345. })(BABYLON || (BABYLON = {}));
  65346. //# sourceMappingURL=babylon.webVRCamera.js.map
  65347. /// <reference path="babylon.freeCamera.ts" />
  65348. var BABYLON;
  65349. (function (BABYLON) {
  65350. // We're mainly based on the logic defined into the FreeCamera code
  65351. var DeviceOrientationCamera = (function (_super) {
  65352. __extends(DeviceOrientationCamera, _super);
  65353. function DeviceOrientationCamera(name, position, scene) {
  65354. var _this = _super.call(this, name, position, scene) || this;
  65355. _this._quaternionCache = new BABYLON.Quaternion();
  65356. _this.inputs.addDeviceOrientation();
  65357. return _this;
  65358. }
  65359. DeviceOrientationCamera.prototype.getClassName = function () {
  65360. return "DeviceOrientationCamera";
  65361. };
  65362. DeviceOrientationCamera.prototype._checkInputs = function () {
  65363. _super.prototype._checkInputs.call(this);
  65364. this._quaternionCache.copyFrom(this.rotationQuaternion);
  65365. if (this._initialQuaternion) {
  65366. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  65367. }
  65368. };
  65369. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  65370. var _this = this;
  65371. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  65372. //can only work if this camera has a rotation quaternion already.
  65373. if (!this.rotationQuaternion)
  65374. return;
  65375. if (!this._initialQuaternion) {
  65376. this._initialQuaternion = new BABYLON.Quaternion();
  65377. }
  65378. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  65379. ['x', 'y', 'z'].forEach(function (axisName) {
  65380. if (!axis[axisName]) {
  65381. _this._initialQuaternion[axisName] = 0;
  65382. }
  65383. else {
  65384. _this._initialQuaternion[axisName] *= -1;
  65385. }
  65386. });
  65387. this._initialQuaternion.normalize();
  65388. //force rotation update
  65389. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  65390. };
  65391. return DeviceOrientationCamera;
  65392. }(BABYLON.FreeCamera));
  65393. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  65394. })(BABYLON || (BABYLON = {}));
  65395. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  65396. var BABYLON;
  65397. (function (BABYLON) {
  65398. var VRDeviceOrientationFreeCamera = (function (_super) {
  65399. __extends(VRDeviceOrientationFreeCamera, _super);
  65400. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  65401. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65402. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65403. var _this = _super.call(this, name, position, scene) || this;
  65404. vrCameraMetrics.compensateDistortion = compensateDistortion;
  65405. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  65406. return _this;
  65407. }
  65408. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  65409. return "VRDeviceOrientationFreeCamera";
  65410. };
  65411. return VRDeviceOrientationFreeCamera;
  65412. }(BABYLON.DeviceOrientationCamera));
  65413. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  65414. var VRDeviceOrientationGamepadCamera = (function (_super) {
  65415. __extends(VRDeviceOrientationGamepadCamera, _super);
  65416. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  65417. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65418. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65419. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  65420. _this.inputs.addGamepad();
  65421. return _this;
  65422. }
  65423. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  65424. return "VRDeviceOrientationGamepadCamera";
  65425. };
  65426. return VRDeviceOrientationGamepadCamera;
  65427. }(VRDeviceOrientationFreeCamera));
  65428. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  65429. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  65430. __extends(VRDeviceOrientationArcRotateCamera, _super);
  65431. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  65432. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65433. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65434. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65435. vrCameraMetrics.compensateDistortion = compensateDistortion;
  65436. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  65437. _this.inputs.addVRDeviceOrientation();
  65438. return _this;
  65439. }
  65440. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  65441. return "VRDeviceOrientationArcRotateCamera";
  65442. };
  65443. return VRDeviceOrientationArcRotateCamera;
  65444. }(BABYLON.ArcRotateCamera));
  65445. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  65446. })(BABYLON || (BABYLON = {}));
  65447. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  65448. /// <reference path="babylon.freeCamera.ts" />
  65449. /// <reference path="babylon.arcRotateCamera.ts" />
  65450. /// <reference path="babylon.gamepadCamera.ts" />
  65451. /// <reference path="babylon.universalCamera.ts" />
  65452. var BABYLON;
  65453. (function (BABYLON) {
  65454. var AnaglyphFreeCamera = (function (_super) {
  65455. __extends(AnaglyphFreeCamera, _super);
  65456. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  65457. var _this = _super.call(this, name, position, scene) || this;
  65458. _this.interaxialDistance = interaxialDistance;
  65459. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65460. return _this;
  65461. }
  65462. AnaglyphFreeCamera.prototype.getClassName = function () {
  65463. return "AnaglyphFreeCamera";
  65464. };
  65465. return AnaglyphFreeCamera;
  65466. }(BABYLON.FreeCamera));
  65467. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  65468. var AnaglyphArcRotateCamera = (function (_super) {
  65469. __extends(AnaglyphArcRotateCamera, _super);
  65470. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  65471. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65472. _this.interaxialDistance = interaxialDistance;
  65473. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65474. return _this;
  65475. }
  65476. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  65477. return "AnaglyphArcRotateCamera";
  65478. };
  65479. return AnaglyphArcRotateCamera;
  65480. }(BABYLON.ArcRotateCamera));
  65481. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  65482. var AnaglyphGamepadCamera = (function (_super) {
  65483. __extends(AnaglyphGamepadCamera, _super);
  65484. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  65485. var _this = _super.call(this, name, position, scene) || this;
  65486. _this.interaxialDistance = interaxialDistance;
  65487. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65488. return _this;
  65489. }
  65490. AnaglyphGamepadCamera.prototype.getClassName = function () {
  65491. return "AnaglyphGamepadCamera";
  65492. };
  65493. return AnaglyphGamepadCamera;
  65494. }(BABYLON.GamepadCamera));
  65495. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  65496. var AnaglyphUniversalCamera = (function (_super) {
  65497. __extends(AnaglyphUniversalCamera, _super);
  65498. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  65499. var _this = _super.call(this, name, position, scene) || this;
  65500. _this.interaxialDistance = interaxialDistance;
  65501. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65502. return _this;
  65503. }
  65504. AnaglyphUniversalCamera.prototype.getClassName = function () {
  65505. return "AnaglyphUniversalCamera";
  65506. };
  65507. return AnaglyphUniversalCamera;
  65508. }(BABYLON.UniversalCamera));
  65509. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  65510. var StereoscopicFreeCamera = (function (_super) {
  65511. __extends(StereoscopicFreeCamera, _super);
  65512. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65513. var _this = _super.call(this, name, position, scene) || this;
  65514. _this.interaxialDistance = interaxialDistance;
  65515. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65516. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65517. return _this;
  65518. }
  65519. StereoscopicFreeCamera.prototype.getClassName = function () {
  65520. return "StereoscopicFreeCamera";
  65521. };
  65522. return StereoscopicFreeCamera;
  65523. }(BABYLON.FreeCamera));
  65524. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  65525. var StereoscopicArcRotateCamera = (function (_super) {
  65526. __extends(StereoscopicArcRotateCamera, _super);
  65527. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  65528. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65529. _this.interaxialDistance = interaxialDistance;
  65530. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65531. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65532. return _this;
  65533. }
  65534. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  65535. return "StereoscopicArcRotateCamera";
  65536. };
  65537. return StereoscopicArcRotateCamera;
  65538. }(BABYLON.ArcRotateCamera));
  65539. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  65540. var StereoscopicGamepadCamera = (function (_super) {
  65541. __extends(StereoscopicGamepadCamera, _super);
  65542. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65543. var _this = _super.call(this, name, position, scene) || this;
  65544. _this.interaxialDistance = interaxialDistance;
  65545. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65546. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65547. return _this;
  65548. }
  65549. StereoscopicGamepadCamera.prototype.getClassName = function () {
  65550. return "StereoscopicGamepadCamera";
  65551. };
  65552. return StereoscopicGamepadCamera;
  65553. }(BABYLON.GamepadCamera));
  65554. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  65555. var StereoscopicUniversalCamera = (function (_super) {
  65556. __extends(StereoscopicUniversalCamera, _super);
  65557. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65558. var _this = _super.call(this, name, position, scene) || this;
  65559. _this.interaxialDistance = interaxialDistance;
  65560. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65561. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65562. return _this;
  65563. }
  65564. StereoscopicUniversalCamera.prototype.getClassName = function () {
  65565. return "StereoscopicUniversalCamera";
  65566. };
  65567. return StereoscopicUniversalCamera;
  65568. }(BABYLON.UniversalCamera));
  65569. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  65570. })(BABYLON || (BABYLON = {}));
  65571. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  65572. var BABYLON;
  65573. (function (BABYLON) {
  65574. var VRExperienceHelper = (function () {
  65575. function VRExperienceHelper(scene, webVROptions) {
  65576. if (webVROptions === void 0) { webVROptions = {}; }
  65577. var _this = this;
  65578. this.webVROptions = webVROptions;
  65579. this._webVRsupportedAndReady = false;
  65580. this._isInVRMode = false;
  65581. this._scene = scene;
  65582. if (!this._scene.activeCamera) {
  65583. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  65584. }
  65585. else {
  65586. var newCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  65587. if (scene.activeCamera.rotation) {
  65588. newCamera.rotation = scene.activeCamera.rotation.clone();
  65589. }
  65590. this._scene.activeCamera = newCamera;
  65591. }
  65592. this._position = this._scene.activeCamera.position;
  65593. this._canvas = scene.getEngine().getRenderingCanvas();
  65594. this._scene.activeCamera.attachControl(this._canvas);
  65595. this._btnVR = document.createElement("BUTTON");
  65596. this._btnVR.className = "babylonVRicon";
  65597. this._btnVR.id = "babylonVRiconbtn";
  65598. this._btnVR.title = "Click to switch to VR";
  65599. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  65600. var style = document.createElement('style');
  65601. style.appendChild(document.createTextNode(css));
  65602. document.getElementsByTagName('head')[0].appendChild(style);
  65603. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  65604. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  65605. window.addEventListener("resize", function () {
  65606. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  65607. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  65608. });
  65609. // Exiting VR mode using 'ESC' key on desktop
  65610. document.addEventListener("keydown", function (event) {
  65611. if (event.keyCode === 27 && _this._isInVRMode) {
  65612. _this.exitVR();
  65613. }
  65614. });
  65615. // Exiting VR mode double tapping the touch screen
  65616. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  65617. if (_this._isInVRMode) {
  65618. _this.exitVR();
  65619. }
  65620. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  65621. if (navigator.getVRDisplays) {
  65622. navigator.getVRDisplays().then(function (headsets) {
  65623. if (headsets.length > 0) {
  65624. scene.getEngine().initWebVR();
  65625. _this._webVRsupportedAndReady = true;
  65626. }
  65627. document.body.appendChild(_this._btnVR);
  65628. });
  65629. }
  65630. else {
  65631. document.body.appendChild(this._btnVR);
  65632. }
  65633. this._btnVR.addEventListener("click", function () {
  65634. _this.enterVR();
  65635. });
  65636. }
  65637. VRExperienceHelper.prototype.enterVR = function () {
  65638. this._scene.activeCamera.dispose();
  65639. // If WebVR is supported and a headset is connected
  65640. if (this._webVRsupportedAndReady) {
  65641. this._scene.activeCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  65642. }
  65643. else {
  65644. this._scene.activeCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  65645. this._scene.getEngine().switchFullscreen(true);
  65646. }
  65647. this._scene.activeCamera.attachControl(this._canvas);
  65648. this._isInVRMode = true;
  65649. this._btnVR.style.display = "none";
  65650. };
  65651. VRExperienceHelper.prototype.exitVR = function () {
  65652. if (this._webVRsupportedAndReady) {
  65653. this._scene.getEngine().disableVR();
  65654. }
  65655. if (this._scene.activeCamera) {
  65656. this._position = this._scene.activeCamera.position;
  65657. this._scene.activeCamera.dispose();
  65658. }
  65659. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, this._scene);
  65660. this._scene.activeCamera.attachControl(this._canvas);
  65661. this._isInVRMode = false;
  65662. this._btnVR.style.display = "";
  65663. };
  65664. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  65665. get: function () {
  65666. return this._position;
  65667. },
  65668. set: function (value) {
  65669. this._position = value;
  65670. this._scene.activeCamera.position = value;
  65671. },
  65672. enumerable: true,
  65673. configurable: true
  65674. });
  65675. VRExperienceHelper.prototype.dispose = function () {
  65676. if (this._isInVRMode) {
  65677. this.exitVR();
  65678. }
  65679. document.body.removeChild(this._btnVR);
  65680. };
  65681. VRExperienceHelper.prototype.getClassName = function () {
  65682. return "VRExperienceHelper";
  65683. };
  65684. return VRExperienceHelper;
  65685. }());
  65686. BABYLON.VRExperienceHelper = VRExperienceHelper;
  65687. })(BABYLON || (BABYLON = {}));
  65688. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  65689. // Mainly based on these 2 articles :
  65690. // 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
  65691. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  65692. var BABYLON;
  65693. (function (BABYLON) {
  65694. var JoystickAxis;
  65695. (function (JoystickAxis) {
  65696. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  65697. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  65698. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  65699. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  65700. var VirtualJoystick = (function () {
  65701. function VirtualJoystick(leftJoystick) {
  65702. var _this = this;
  65703. if (leftJoystick) {
  65704. this._leftJoystick = true;
  65705. }
  65706. else {
  65707. this._leftJoystick = false;
  65708. }
  65709. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  65710. VirtualJoystick._globalJoystickIndex++;
  65711. // By default left & right arrow keys are moving the X
  65712. // and up & down keys are moving the Y
  65713. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  65714. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  65715. this.reverseLeftRight = false;
  65716. this.reverseUpDown = false;
  65717. // collections of pointers
  65718. this._touches = new BABYLON.StringDictionary();
  65719. this.deltaPosition = BABYLON.Vector3.Zero();
  65720. this._joystickSensibility = 25;
  65721. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  65722. this._rotationSpeed = 25;
  65723. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  65724. this._rotateOnAxisRelativeToMesh = false;
  65725. this._onResize = function (evt) {
  65726. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  65727. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  65728. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  65729. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  65730. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  65731. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  65732. };
  65733. // injecting a canvas element on top of the canvas 3D game
  65734. if (!VirtualJoystick.vjCanvas) {
  65735. window.addEventListener("resize", this._onResize, false);
  65736. VirtualJoystick.vjCanvas = document.createElement("canvas");
  65737. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  65738. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  65739. VirtualJoystick.vjCanvas.width = window.innerWidth;
  65740. VirtualJoystick.vjCanvas.height = window.innerHeight;
  65741. VirtualJoystick.vjCanvas.style.width = "100%";
  65742. VirtualJoystick.vjCanvas.style.height = "100%";
  65743. VirtualJoystick.vjCanvas.style.position = "absolute";
  65744. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  65745. VirtualJoystick.vjCanvas.style.top = "0px";
  65746. VirtualJoystick.vjCanvas.style.left = "0px";
  65747. VirtualJoystick.vjCanvas.style.zIndex = "5";
  65748. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  65749. // Support for jQuery PEP polyfill
  65750. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  65751. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  65752. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  65753. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  65754. document.body.appendChild(VirtualJoystick.vjCanvas);
  65755. }
  65756. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  65757. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  65758. this.pressed = false;
  65759. // default joystick color
  65760. this._joystickColor = "cyan";
  65761. this._joystickPointerID = -1;
  65762. // current joystick position
  65763. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  65764. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  65765. // origin joystick position
  65766. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  65767. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  65768. this._onPointerDownHandlerRef = function (evt) {
  65769. _this._onPointerDown(evt);
  65770. };
  65771. this._onPointerMoveHandlerRef = function (evt) {
  65772. _this._onPointerMove(evt);
  65773. };
  65774. this._onPointerOutHandlerRef = function (evt) {
  65775. _this._onPointerUp(evt);
  65776. };
  65777. this._onPointerUpHandlerRef = function (evt) {
  65778. _this._onPointerUp(evt);
  65779. };
  65780. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  65781. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  65782. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  65783. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  65784. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  65785. evt.preventDefault(); // Disables system menu
  65786. }, false);
  65787. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  65788. }
  65789. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  65790. this._joystickSensibility = newJoystickSensibility;
  65791. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  65792. };
  65793. VirtualJoystick.prototype._onPointerDown = function (e) {
  65794. var positionOnScreenCondition;
  65795. e.preventDefault();
  65796. if (this._leftJoystick === true) {
  65797. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  65798. }
  65799. else {
  65800. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  65801. }
  65802. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  65803. // First contact will be dedicated to the virtual joystick
  65804. this._joystickPointerID = e.pointerId;
  65805. this._joystickPointerStartPos.x = e.clientX;
  65806. this._joystickPointerStartPos.y = e.clientY;
  65807. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  65808. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  65809. this._deltaJoystickVector.x = 0;
  65810. this._deltaJoystickVector.y = 0;
  65811. this.pressed = true;
  65812. this._touches.add(e.pointerId.toString(), e);
  65813. }
  65814. else {
  65815. // You can only trigger the action buttons with a joystick declared
  65816. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  65817. this._action();
  65818. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  65819. }
  65820. }
  65821. };
  65822. VirtualJoystick.prototype._onPointerMove = function (e) {
  65823. // If the current pointer is the one associated to the joystick (first touch contact)
  65824. if (this._joystickPointerID == e.pointerId) {
  65825. this._joystickPointerPos.x = e.clientX;
  65826. this._joystickPointerPos.y = e.clientY;
  65827. this._deltaJoystickVector = this._joystickPointerPos.clone();
  65828. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  65829. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  65830. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  65831. switch (this._axisTargetedByLeftAndRight) {
  65832. case JoystickAxis.X:
  65833. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  65834. break;
  65835. case JoystickAxis.Y:
  65836. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  65837. break;
  65838. case JoystickAxis.Z:
  65839. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  65840. break;
  65841. }
  65842. var directionUpDown = this.reverseUpDown ? 1 : -1;
  65843. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  65844. switch (this._axisTargetedByUpAndDown) {
  65845. case JoystickAxis.X:
  65846. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  65847. break;
  65848. case JoystickAxis.Y:
  65849. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  65850. break;
  65851. case JoystickAxis.Z:
  65852. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  65853. break;
  65854. }
  65855. }
  65856. else {
  65857. var data = this._touches.get(e.pointerId.toString());
  65858. if (data) {
  65859. data.x = e.clientX;
  65860. data.y = e.clientY;
  65861. }
  65862. }
  65863. };
  65864. VirtualJoystick.prototype._onPointerUp = function (e) {
  65865. if (this._joystickPointerID == e.pointerId) {
  65866. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  65867. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  65868. this._joystickPointerID = -1;
  65869. this.pressed = false;
  65870. }
  65871. else {
  65872. var touch = this._touches.get(e.pointerId.toString());
  65873. if (touch) {
  65874. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  65875. }
  65876. }
  65877. this._deltaJoystickVector.x = 0;
  65878. this._deltaJoystickVector.y = 0;
  65879. this._touches.remove(e.pointerId.toString());
  65880. };
  65881. /**
  65882. * Change the color of the virtual joystick
  65883. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  65884. */
  65885. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  65886. this._joystickColor = newColor;
  65887. };
  65888. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  65889. this._action = action;
  65890. };
  65891. // Define which axis you'd like to control for left & right
  65892. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  65893. switch (axis) {
  65894. case JoystickAxis.X:
  65895. case JoystickAxis.Y:
  65896. case JoystickAxis.Z:
  65897. this._axisTargetedByLeftAndRight = axis;
  65898. break;
  65899. default:
  65900. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  65901. break;
  65902. }
  65903. };
  65904. // Define which axis you'd like to control for up & down
  65905. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  65906. switch (axis) {
  65907. case JoystickAxis.X:
  65908. case JoystickAxis.Y:
  65909. case JoystickAxis.Z:
  65910. this._axisTargetedByUpAndDown = axis;
  65911. break;
  65912. default:
  65913. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  65914. break;
  65915. }
  65916. };
  65917. VirtualJoystick.prototype._clearCanvas = function () {
  65918. if (this._leftJoystick) {
  65919. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  65920. }
  65921. else {
  65922. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  65923. }
  65924. };
  65925. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  65926. var _this = this;
  65927. if (this.pressed) {
  65928. this._touches.forEach(function (key, touch) {
  65929. if (touch.pointerId === _this._joystickPointerID) {
  65930. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  65931. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  65932. VirtualJoystick.vjCanvasContext.beginPath();
  65933. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  65934. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65935. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  65936. VirtualJoystick.vjCanvasContext.stroke();
  65937. VirtualJoystick.vjCanvasContext.closePath();
  65938. VirtualJoystick.vjCanvasContext.beginPath();
  65939. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65940. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  65941. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  65942. VirtualJoystick.vjCanvasContext.stroke();
  65943. VirtualJoystick.vjCanvasContext.closePath();
  65944. VirtualJoystick.vjCanvasContext.beginPath();
  65945. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65946. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  65947. VirtualJoystick.vjCanvasContext.stroke();
  65948. VirtualJoystick.vjCanvasContext.closePath();
  65949. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  65950. }
  65951. else {
  65952. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  65953. VirtualJoystick.vjCanvasContext.beginPath();
  65954. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  65955. VirtualJoystick.vjCanvasContext.beginPath();
  65956. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  65957. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  65958. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  65959. VirtualJoystick.vjCanvasContext.stroke();
  65960. VirtualJoystick.vjCanvasContext.closePath();
  65961. touch.prevX = touch.x;
  65962. touch.prevY = touch.y;
  65963. }
  65964. ;
  65965. });
  65966. }
  65967. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  65968. };
  65969. VirtualJoystick.prototype.releaseCanvas = function () {
  65970. if (VirtualJoystick.vjCanvas) {
  65971. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  65972. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  65973. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  65974. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  65975. window.removeEventListener("resize", this._onResize);
  65976. document.body.removeChild(VirtualJoystick.vjCanvas);
  65977. VirtualJoystick.vjCanvas = null;
  65978. }
  65979. };
  65980. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  65981. VirtualJoystick._globalJoystickIndex = 0;
  65982. return VirtualJoystick;
  65983. }());
  65984. BABYLON.VirtualJoystick = VirtualJoystick;
  65985. })(BABYLON || (BABYLON = {}));
  65986. //# sourceMappingURL=babylon.virtualJoystick.js.map
  65987. var BABYLON;
  65988. (function (BABYLON) {
  65989. // We're mainly based on the logic defined into the FreeCamera code
  65990. var VirtualJoysticksCamera = (function (_super) {
  65991. __extends(VirtualJoysticksCamera, _super);
  65992. function VirtualJoysticksCamera(name, position, scene) {
  65993. var _this = _super.call(this, name, position, scene) || this;
  65994. _this.inputs.addVirtualJoystick();
  65995. return _this;
  65996. }
  65997. VirtualJoysticksCamera.prototype.getClassName = function () {
  65998. return "VirtualJoysticksCamera";
  65999. };
  66000. return VirtualJoysticksCamera;
  66001. }(BABYLON.FreeCamera));
  66002. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  66003. })(BABYLON || (BABYLON = {}));
  66004. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  66005. var BABYLON;
  66006. (function (BABYLON) {
  66007. var FreeCameraVirtualJoystickInput = (function () {
  66008. function FreeCameraVirtualJoystickInput() {
  66009. }
  66010. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  66011. return this._leftjoystick;
  66012. };
  66013. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  66014. return this._rightjoystick;
  66015. };
  66016. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  66017. if (this._leftjoystick) {
  66018. var camera = this.camera;
  66019. var speed = camera._computeLocalCameraSpeed() * 50;
  66020. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  66021. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  66022. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  66023. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  66024. if (!this._leftjoystick.pressed) {
  66025. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  66026. }
  66027. if (!this._rightjoystick.pressed) {
  66028. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  66029. }
  66030. }
  66031. };
  66032. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  66033. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  66034. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  66035. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  66036. this._leftjoystick.setJoystickSensibility(0.15);
  66037. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  66038. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  66039. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  66040. this._rightjoystick.reverseUpDown = true;
  66041. this._rightjoystick.setJoystickSensibility(0.05);
  66042. this._rightjoystick.setJoystickColor("yellow");
  66043. };
  66044. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  66045. this._leftjoystick.releaseCanvas();
  66046. this._rightjoystick.releaseCanvas();
  66047. };
  66048. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  66049. return "FreeCameraVirtualJoystickInput";
  66050. };
  66051. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  66052. return "virtualJoystick";
  66053. };
  66054. return FreeCameraVirtualJoystickInput;
  66055. }());
  66056. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  66057. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  66058. })(BABYLON || (BABYLON = {}));
  66059. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  66060. var BABYLON;
  66061. (function (BABYLON) {
  66062. var SimplificationSettings = (function () {
  66063. function SimplificationSettings(quality, distance, optimizeMesh) {
  66064. this.quality = quality;
  66065. this.distance = distance;
  66066. this.optimizeMesh = optimizeMesh;
  66067. }
  66068. return SimplificationSettings;
  66069. }());
  66070. BABYLON.SimplificationSettings = SimplificationSettings;
  66071. var SimplificationQueue = (function () {
  66072. function SimplificationQueue() {
  66073. this.running = false;
  66074. this._simplificationArray = [];
  66075. }
  66076. SimplificationQueue.prototype.addTask = function (task) {
  66077. this._simplificationArray.push(task);
  66078. };
  66079. SimplificationQueue.prototype.executeNext = function () {
  66080. var task = this._simplificationArray.pop();
  66081. if (task) {
  66082. this.running = true;
  66083. this.runSimplification(task);
  66084. }
  66085. else {
  66086. this.running = false;
  66087. }
  66088. };
  66089. SimplificationQueue.prototype.runSimplification = function (task) {
  66090. var _this = this;
  66091. if (task.parallelProcessing) {
  66092. //parallel simplifier
  66093. task.settings.forEach(function (setting) {
  66094. var simplifier = _this.getSimplifier(task);
  66095. simplifier.simplify(setting, function (newMesh) {
  66096. task.mesh.addLODLevel(setting.distance, newMesh);
  66097. newMesh.isVisible = true;
  66098. //check if it is the last
  66099. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  66100. //all done, run the success callback.
  66101. task.successCallback();
  66102. }
  66103. _this.executeNext();
  66104. });
  66105. });
  66106. }
  66107. else {
  66108. //single simplifier.
  66109. var simplifier = this.getSimplifier(task);
  66110. var runDecimation = function (setting, callback) {
  66111. simplifier.simplify(setting, function (newMesh) {
  66112. task.mesh.addLODLevel(setting.distance, newMesh);
  66113. newMesh.isVisible = true;
  66114. //run the next quality level
  66115. callback();
  66116. });
  66117. };
  66118. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  66119. runDecimation(task.settings[loop.index], function () {
  66120. loop.executeNext();
  66121. });
  66122. }, function () {
  66123. //execution ended, run the success callback.
  66124. if (task.successCallback) {
  66125. task.successCallback();
  66126. }
  66127. _this.executeNext();
  66128. });
  66129. }
  66130. };
  66131. SimplificationQueue.prototype.getSimplifier = function (task) {
  66132. switch (task.simplificationType) {
  66133. case SimplificationType.QUADRATIC:
  66134. default:
  66135. return new QuadraticErrorSimplification(task.mesh);
  66136. }
  66137. };
  66138. return SimplificationQueue;
  66139. }());
  66140. BABYLON.SimplificationQueue = SimplificationQueue;
  66141. /**
  66142. * The implemented types of simplification.
  66143. * At the moment only Quadratic Error Decimation is implemented.
  66144. */
  66145. var SimplificationType;
  66146. (function (SimplificationType) {
  66147. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  66148. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  66149. var DecimationTriangle = (function () {
  66150. function DecimationTriangle(vertices) {
  66151. this.vertices = vertices;
  66152. this.error = new Array(4);
  66153. this.deleted = false;
  66154. this.isDirty = false;
  66155. this.deletePending = false;
  66156. this.borderFactor = 0;
  66157. }
  66158. return DecimationTriangle;
  66159. }());
  66160. BABYLON.DecimationTriangle = DecimationTriangle;
  66161. var DecimationVertex = (function () {
  66162. function DecimationVertex(position, id) {
  66163. this.position = position;
  66164. this.id = id;
  66165. this.isBorder = true;
  66166. this.q = new QuadraticMatrix();
  66167. this.triangleCount = 0;
  66168. this.triangleStart = 0;
  66169. this.originalOffsets = [];
  66170. }
  66171. DecimationVertex.prototype.updatePosition = function (newPosition) {
  66172. this.position.copyFrom(newPosition);
  66173. };
  66174. return DecimationVertex;
  66175. }());
  66176. BABYLON.DecimationVertex = DecimationVertex;
  66177. var QuadraticMatrix = (function () {
  66178. function QuadraticMatrix(data) {
  66179. this.data = new Array(10);
  66180. for (var i = 0; i < 10; ++i) {
  66181. if (data && data[i]) {
  66182. this.data[i] = data[i];
  66183. }
  66184. else {
  66185. this.data[i] = 0;
  66186. }
  66187. }
  66188. }
  66189. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  66190. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  66191. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  66192. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  66193. return det;
  66194. };
  66195. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  66196. for (var i = 0; i < 10; ++i) {
  66197. this.data[i] += matrix.data[i];
  66198. }
  66199. };
  66200. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  66201. for (var i = 0; i < 10; ++i) {
  66202. this.data[i] += data[i];
  66203. }
  66204. };
  66205. QuadraticMatrix.prototype.add = function (matrix) {
  66206. var m = new QuadraticMatrix();
  66207. for (var i = 0; i < 10; ++i) {
  66208. m.data[i] = this.data[i] + matrix.data[i];
  66209. }
  66210. return m;
  66211. };
  66212. QuadraticMatrix.FromData = function (a, b, c, d) {
  66213. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  66214. };
  66215. //returning an array to avoid garbage collection
  66216. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  66217. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  66218. };
  66219. return QuadraticMatrix;
  66220. }());
  66221. BABYLON.QuadraticMatrix = QuadraticMatrix;
  66222. var Reference = (function () {
  66223. function Reference(vertexId, triangleId) {
  66224. this.vertexId = vertexId;
  66225. this.triangleId = triangleId;
  66226. }
  66227. return Reference;
  66228. }());
  66229. BABYLON.Reference = Reference;
  66230. /**
  66231. * An implementation of the Quadratic Error simplification algorithm.
  66232. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  66233. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  66234. * @author RaananW
  66235. */
  66236. var QuadraticErrorSimplification = (function () {
  66237. function QuadraticErrorSimplification(_mesh) {
  66238. this._mesh = _mesh;
  66239. this.initialized = false;
  66240. this.syncIterations = 5000;
  66241. this.aggressiveness = 7;
  66242. this.decimationIterations = 100;
  66243. this.boundingBoxEpsilon = BABYLON.Epsilon;
  66244. }
  66245. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  66246. var _this = this;
  66247. this.initDecimatedMesh();
  66248. //iterating through the submeshes array, one after the other.
  66249. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  66250. _this.initWithMesh(loop.index, function () {
  66251. _this.runDecimation(settings, loop.index, function () {
  66252. loop.executeNext();
  66253. });
  66254. }, settings.optimizeMesh);
  66255. }, function () {
  66256. setTimeout(function () {
  66257. successCallback(_this._reconstructedMesh);
  66258. }, 0);
  66259. });
  66260. };
  66261. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  66262. var _this = this;
  66263. var gCount = 0;
  66264. triangle.vertices.forEach(function (vertex) {
  66265. var count = 0;
  66266. var vPos = vertex.position;
  66267. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  66268. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  66269. ++count;
  66270. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  66271. ++count;
  66272. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  66273. ++count;
  66274. if (count > 1) {
  66275. ++gCount;
  66276. }
  66277. ;
  66278. });
  66279. if (gCount > 1) {
  66280. console.log(triangle, gCount);
  66281. }
  66282. return gCount > 1;
  66283. };
  66284. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  66285. var _this = this;
  66286. var targetCount = ~~(this.triangles.length * settings.quality);
  66287. var deletedTriangles = 0;
  66288. var triangleCount = this.triangles.length;
  66289. var iterationFunction = function (iteration, callback) {
  66290. setTimeout(function () {
  66291. if (iteration % 5 === 0) {
  66292. _this.updateMesh(iteration === 0);
  66293. }
  66294. for (var i = 0; i < _this.triangles.length; ++i) {
  66295. _this.triangles[i].isDirty = false;
  66296. }
  66297. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  66298. var trianglesIterator = function (i) {
  66299. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  66300. var t = _this.triangles[tIdx];
  66301. if (!t)
  66302. return;
  66303. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  66304. return;
  66305. }
  66306. for (var j = 0; j < 3; ++j) {
  66307. if (t.error[j] < threshold) {
  66308. var deleted0 = [];
  66309. var deleted1 = [];
  66310. var v0 = t.vertices[j];
  66311. var v1 = t.vertices[(j + 1) % 3];
  66312. if (v0.isBorder || v1.isBorder)
  66313. continue;
  66314. var p = BABYLON.Vector3.Zero();
  66315. var n = BABYLON.Vector3.Zero();
  66316. var uv = BABYLON.Vector2.Zero();
  66317. var color = new BABYLON.Color4(0, 0, 0, 1);
  66318. _this.calculateError(v0, v1, p, n, uv, color);
  66319. var delTr = [];
  66320. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  66321. continue;
  66322. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  66323. continue;
  66324. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  66325. continue;
  66326. var uniqueArray = [];
  66327. delTr.forEach(function (deletedT) {
  66328. if (uniqueArray.indexOf(deletedT) === -1) {
  66329. deletedT.deletePending = true;
  66330. uniqueArray.push(deletedT);
  66331. }
  66332. });
  66333. if (uniqueArray.length % 2 !== 0) {
  66334. continue;
  66335. }
  66336. v0.q = v1.q.add(v0.q);
  66337. v0.updatePosition(p);
  66338. var tStart = _this.references.length;
  66339. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  66340. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  66341. var tCount = _this.references.length - tStart;
  66342. if (tCount <= v0.triangleCount) {
  66343. if (tCount) {
  66344. for (var c = 0; c < tCount; c++) {
  66345. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  66346. }
  66347. }
  66348. }
  66349. else {
  66350. v0.triangleStart = tStart;
  66351. }
  66352. v0.triangleCount = tCount;
  66353. break;
  66354. }
  66355. }
  66356. };
  66357. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  66358. }, 0);
  66359. };
  66360. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  66361. if (triangleCount - deletedTriangles <= targetCount)
  66362. loop.breakLoop();
  66363. else {
  66364. iterationFunction(loop.index, function () {
  66365. loop.executeNext();
  66366. });
  66367. }
  66368. }, function () {
  66369. setTimeout(function () {
  66370. //reconstruct this part of the mesh
  66371. _this.reconstructMesh(submeshIndex);
  66372. successCallback();
  66373. }, 0);
  66374. });
  66375. };
  66376. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  66377. var _this = this;
  66378. this.vertices = [];
  66379. this.triangles = [];
  66380. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66381. var indices = this._mesh.getIndices();
  66382. var submesh = this._mesh.subMeshes[submeshIndex];
  66383. var findInVertices = function (positionToSearch) {
  66384. if (optimizeMesh) {
  66385. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  66386. if (_this.vertices[ii].position.equals(positionToSearch)) {
  66387. return _this.vertices[ii];
  66388. }
  66389. }
  66390. }
  66391. return null;
  66392. };
  66393. var vertexReferences = [];
  66394. var vertexInit = function (i) {
  66395. var offset = i + submesh.verticesStart;
  66396. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  66397. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  66398. vertex.originalOffsets.push(offset);
  66399. if (vertex.id === _this.vertices.length) {
  66400. _this.vertices.push(vertex);
  66401. }
  66402. vertexReferences.push(vertex.id);
  66403. };
  66404. //var totalVertices = mesh.getTotalVertices();
  66405. var totalVertices = submesh.verticesCount;
  66406. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  66407. var indicesInit = function (i) {
  66408. var offset = (submesh.indexStart / 3) + i;
  66409. var pos = (offset * 3);
  66410. var i0 = indices[pos + 0];
  66411. var i1 = indices[pos + 1];
  66412. var i2 = indices[pos + 2];
  66413. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  66414. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  66415. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  66416. var triangle = new DecimationTriangle([v0, v1, v2]);
  66417. triangle.originalOffset = pos;
  66418. _this.triangles.push(triangle);
  66419. };
  66420. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  66421. _this.init(callback);
  66422. });
  66423. });
  66424. };
  66425. QuadraticErrorSimplification.prototype.init = function (callback) {
  66426. var _this = this;
  66427. var triangleInit1 = function (i) {
  66428. var t = _this.triangles[i];
  66429. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  66430. for (var j = 0; j < 3; j++) {
  66431. 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))));
  66432. }
  66433. };
  66434. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  66435. var triangleInit2 = function (i) {
  66436. var t = _this.triangles[i];
  66437. for (var j = 0; j < 3; ++j) {
  66438. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  66439. }
  66440. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  66441. };
  66442. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  66443. _this.initialized = true;
  66444. callback();
  66445. });
  66446. });
  66447. };
  66448. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  66449. var newTriangles = [];
  66450. var i;
  66451. for (i = 0; i < this.vertices.length; ++i) {
  66452. this.vertices[i].triangleCount = 0;
  66453. }
  66454. var t;
  66455. var j;
  66456. for (i = 0; i < this.triangles.length; ++i) {
  66457. if (!this.triangles[i].deleted) {
  66458. t = this.triangles[i];
  66459. for (j = 0; j < 3; ++j) {
  66460. t.vertices[j].triangleCount = 1;
  66461. }
  66462. newTriangles.push(t);
  66463. }
  66464. }
  66465. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  66466. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  66467. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  66468. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  66469. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66470. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66471. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66472. var vertexCount = 0;
  66473. for (i = 0; i < this.vertices.length; ++i) {
  66474. var vertex = this.vertices[i];
  66475. vertex.id = vertexCount;
  66476. if (vertex.triangleCount) {
  66477. vertex.originalOffsets.forEach(function (originalOffset) {
  66478. newPositionData.push(vertex.position.x);
  66479. newPositionData.push(vertex.position.y);
  66480. newPositionData.push(vertex.position.z);
  66481. newNormalData.push(normalData[originalOffset * 3]);
  66482. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  66483. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  66484. if (uvs && uvs.length) {
  66485. newUVsData.push(uvs[(originalOffset * 2)]);
  66486. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  66487. }
  66488. else if (colorsData && colorsData.length) {
  66489. newColorsData.push(colorsData[(originalOffset * 4)]);
  66490. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  66491. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  66492. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  66493. }
  66494. ++vertexCount;
  66495. });
  66496. }
  66497. }
  66498. var startingIndex = this._reconstructedMesh.getTotalIndices();
  66499. var startingVertex = this._reconstructedMesh.getTotalVertices();
  66500. var submeshesArray = this._reconstructedMesh.subMeshes;
  66501. this._reconstructedMesh.subMeshes = [];
  66502. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  66503. var originalIndices = this._mesh.getIndices();
  66504. for (i = 0; i < newTriangles.length; ++i) {
  66505. t = newTriangles[i]; //now get the new referencing point for each vertex
  66506. [0, 1, 2].forEach(function (idx) {
  66507. var id = originalIndices[t.originalOffset + idx];
  66508. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  66509. if (offset < 0)
  66510. offset = 0;
  66511. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  66512. });
  66513. }
  66514. //overwriting the old vertex buffers and indices.
  66515. this._reconstructedMesh.setIndices(newIndicesArray);
  66516. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  66517. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  66518. if (newUVsData.length > 0)
  66519. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  66520. if (newColorsData.length > 0)
  66521. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  66522. //create submesh
  66523. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  66524. if (submeshIndex > 0) {
  66525. this._reconstructedMesh.subMeshes = [];
  66526. submeshesArray.forEach(function (submesh) {
  66527. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  66528. });
  66529. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  66530. }
  66531. };
  66532. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  66533. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  66534. this._reconstructedMesh.material = this._mesh.material;
  66535. this._reconstructedMesh.parent = this._mesh.parent;
  66536. this._reconstructedMesh.isVisible = false;
  66537. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  66538. };
  66539. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  66540. for (var i = 0; i < vertex1.triangleCount; ++i) {
  66541. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  66542. if (t.deleted)
  66543. continue;
  66544. var s = this.references[vertex1.triangleStart + i].vertexId;
  66545. var v1 = t.vertices[(s + 1) % 3];
  66546. var v2 = t.vertices[(s + 2) % 3];
  66547. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  66548. deletedArray[i] = true;
  66549. delTr.push(t);
  66550. continue;
  66551. }
  66552. var d1 = v1.position.subtract(point);
  66553. d1 = d1.normalize();
  66554. var d2 = v2.position.subtract(point);
  66555. d2 = d2.normalize();
  66556. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  66557. return true;
  66558. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  66559. deletedArray[i] = false;
  66560. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  66561. return true;
  66562. }
  66563. return false;
  66564. };
  66565. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  66566. var newDeleted = deletedTriangles;
  66567. for (var i = 0; i < vertex.triangleCount; ++i) {
  66568. var ref = this.references[vertex.triangleStart + i];
  66569. var t = this.triangles[ref.triangleId];
  66570. if (t.deleted)
  66571. continue;
  66572. if (deletedArray[i] && t.deletePending) {
  66573. t.deleted = true;
  66574. newDeleted++;
  66575. continue;
  66576. }
  66577. t.vertices[ref.vertexId] = origVertex;
  66578. t.isDirty = true;
  66579. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  66580. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  66581. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  66582. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  66583. this.references.push(ref);
  66584. }
  66585. return newDeleted;
  66586. };
  66587. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  66588. for (var i = 0; i < this.vertices.length; ++i) {
  66589. var vCount = [];
  66590. var vId = [];
  66591. var v = this.vertices[i];
  66592. var j;
  66593. for (j = 0; j < v.triangleCount; ++j) {
  66594. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  66595. for (var ii = 0; ii < 3; ii++) {
  66596. var ofs = 0;
  66597. var vv = triangle.vertices[ii];
  66598. while (ofs < vCount.length) {
  66599. if (vId[ofs] === vv.id)
  66600. break;
  66601. ++ofs;
  66602. }
  66603. if (ofs === vCount.length) {
  66604. vCount.push(1);
  66605. vId.push(vv.id);
  66606. }
  66607. else {
  66608. vCount[ofs]++;
  66609. }
  66610. }
  66611. }
  66612. for (j = 0; j < vCount.length; ++j) {
  66613. if (vCount[j] === 1) {
  66614. this.vertices[vId[j]].isBorder = true;
  66615. }
  66616. else {
  66617. this.vertices[vId[j]].isBorder = false;
  66618. }
  66619. }
  66620. }
  66621. };
  66622. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  66623. if (identifyBorders === void 0) { identifyBorders = false; }
  66624. var i;
  66625. if (!identifyBorders) {
  66626. var newTrianglesVector = [];
  66627. for (i = 0; i < this.triangles.length; ++i) {
  66628. if (!this.triangles[i].deleted) {
  66629. newTrianglesVector.push(this.triangles[i]);
  66630. }
  66631. }
  66632. this.triangles = newTrianglesVector;
  66633. }
  66634. for (i = 0; i < this.vertices.length; ++i) {
  66635. this.vertices[i].triangleCount = 0;
  66636. this.vertices[i].triangleStart = 0;
  66637. }
  66638. var t;
  66639. var j;
  66640. var v;
  66641. for (i = 0; i < this.triangles.length; ++i) {
  66642. t = this.triangles[i];
  66643. for (j = 0; j < 3; ++j) {
  66644. v = t.vertices[j];
  66645. v.triangleCount++;
  66646. }
  66647. }
  66648. var tStart = 0;
  66649. for (i = 0; i < this.vertices.length; ++i) {
  66650. this.vertices[i].triangleStart = tStart;
  66651. tStart += this.vertices[i].triangleCount;
  66652. this.vertices[i].triangleCount = 0;
  66653. }
  66654. var newReferences = new Array(this.triangles.length * 3);
  66655. for (i = 0; i < this.triangles.length; ++i) {
  66656. t = this.triangles[i];
  66657. for (j = 0; j < 3; ++j) {
  66658. v = t.vertices[j];
  66659. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  66660. v.triangleCount++;
  66661. }
  66662. }
  66663. this.references = newReferences;
  66664. if (identifyBorders) {
  66665. this.identifyBorder();
  66666. }
  66667. };
  66668. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  66669. var x = point.x;
  66670. var y = point.y;
  66671. var z = point.z;
  66672. 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
  66673. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  66674. };
  66675. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  66676. var q = vertex1.q.add(vertex2.q);
  66677. var border = vertex1.isBorder && vertex2.isBorder;
  66678. var error = 0;
  66679. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  66680. if (qDet !== 0 && !border) {
  66681. if (!pointResult) {
  66682. pointResult = BABYLON.Vector3.Zero();
  66683. }
  66684. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  66685. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  66686. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  66687. error = this.vertexError(q, pointResult);
  66688. }
  66689. else {
  66690. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  66691. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  66692. var error1 = this.vertexError(q, vertex1.position);
  66693. var error2 = this.vertexError(q, vertex2.position);
  66694. var error3 = this.vertexError(q, p3);
  66695. error = Math.min(error1, error2, error3);
  66696. if (error === error1) {
  66697. if (pointResult) {
  66698. pointResult.copyFrom(vertex1.position);
  66699. }
  66700. }
  66701. else if (error === error2) {
  66702. if (pointResult) {
  66703. pointResult.copyFrom(vertex2.position);
  66704. }
  66705. }
  66706. else {
  66707. if (pointResult) {
  66708. pointResult.copyFrom(p3);
  66709. }
  66710. }
  66711. }
  66712. return error;
  66713. };
  66714. return QuadraticErrorSimplification;
  66715. }());
  66716. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  66717. })(BABYLON || (BABYLON = {}));
  66718. //# sourceMappingURL=babylon.meshSimplification.js.map
  66719. var BABYLON;
  66720. (function (BABYLON) {
  66721. var Internals;
  66722. (function (Internals) {
  66723. var MeshLODLevel = (function () {
  66724. function MeshLODLevel(distance, mesh) {
  66725. this.distance = distance;
  66726. this.mesh = mesh;
  66727. }
  66728. return MeshLODLevel;
  66729. }());
  66730. Internals.MeshLODLevel = MeshLODLevel;
  66731. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66732. })(BABYLON || (BABYLON = {}));
  66733. //# sourceMappingURL=babylon.meshLODLevel.js.map
  66734. var BABYLON;
  66735. (function (BABYLON) {
  66736. // Standard optimizations
  66737. var SceneOptimization = (function () {
  66738. function SceneOptimization(priority) {
  66739. if (priority === void 0) { priority = 0; }
  66740. this.priority = priority;
  66741. this.apply = function (scene) {
  66742. return true; // Return true if everything that can be done was applied
  66743. };
  66744. }
  66745. return SceneOptimization;
  66746. }());
  66747. BABYLON.SceneOptimization = SceneOptimization;
  66748. var TextureOptimization = (function (_super) {
  66749. __extends(TextureOptimization, _super);
  66750. function TextureOptimization(priority, maximumSize) {
  66751. if (priority === void 0) { priority = 0; }
  66752. if (maximumSize === void 0) { maximumSize = 1024; }
  66753. var _this = _super.call(this, priority) || this;
  66754. _this.priority = priority;
  66755. _this.maximumSize = maximumSize;
  66756. _this.apply = function (scene) {
  66757. var allDone = true;
  66758. for (var index = 0; index < scene.textures.length; index++) {
  66759. var texture = scene.textures[index];
  66760. if (!texture.canRescale || texture.getContext) {
  66761. continue;
  66762. }
  66763. var currentSize = texture.getSize();
  66764. var maxDimension = Math.max(currentSize.width, currentSize.height);
  66765. if (maxDimension > _this.maximumSize) {
  66766. texture.scale(0.5);
  66767. allDone = false;
  66768. }
  66769. }
  66770. return allDone;
  66771. };
  66772. return _this;
  66773. }
  66774. return TextureOptimization;
  66775. }(SceneOptimization));
  66776. BABYLON.TextureOptimization = TextureOptimization;
  66777. var HardwareScalingOptimization = (function (_super) {
  66778. __extends(HardwareScalingOptimization, _super);
  66779. function HardwareScalingOptimization(priority, maximumScale) {
  66780. if (priority === void 0) { priority = 0; }
  66781. if (maximumScale === void 0) { maximumScale = 2; }
  66782. var _this = _super.call(this, priority) || this;
  66783. _this.priority = priority;
  66784. _this.maximumScale = maximumScale;
  66785. _this._currentScale = 1;
  66786. _this.apply = function (scene) {
  66787. _this._currentScale++;
  66788. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  66789. return _this._currentScale >= _this.maximumScale;
  66790. };
  66791. return _this;
  66792. }
  66793. return HardwareScalingOptimization;
  66794. }(SceneOptimization));
  66795. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  66796. var ShadowsOptimization = (function (_super) {
  66797. __extends(ShadowsOptimization, _super);
  66798. function ShadowsOptimization() {
  66799. var _this = _super !== null && _super.apply(this, arguments) || this;
  66800. _this.apply = function (scene) {
  66801. scene.shadowsEnabled = false;
  66802. return true;
  66803. };
  66804. return _this;
  66805. }
  66806. return ShadowsOptimization;
  66807. }(SceneOptimization));
  66808. BABYLON.ShadowsOptimization = ShadowsOptimization;
  66809. var PostProcessesOptimization = (function (_super) {
  66810. __extends(PostProcessesOptimization, _super);
  66811. function PostProcessesOptimization() {
  66812. var _this = _super !== null && _super.apply(this, arguments) || this;
  66813. _this.apply = function (scene) {
  66814. scene.postProcessesEnabled = false;
  66815. return true;
  66816. };
  66817. return _this;
  66818. }
  66819. return PostProcessesOptimization;
  66820. }(SceneOptimization));
  66821. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  66822. var LensFlaresOptimization = (function (_super) {
  66823. __extends(LensFlaresOptimization, _super);
  66824. function LensFlaresOptimization() {
  66825. var _this = _super !== null && _super.apply(this, arguments) || this;
  66826. _this.apply = function (scene) {
  66827. scene.lensFlaresEnabled = false;
  66828. return true;
  66829. };
  66830. return _this;
  66831. }
  66832. return LensFlaresOptimization;
  66833. }(SceneOptimization));
  66834. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  66835. var ParticlesOptimization = (function (_super) {
  66836. __extends(ParticlesOptimization, _super);
  66837. function ParticlesOptimization() {
  66838. var _this = _super !== null && _super.apply(this, arguments) || this;
  66839. _this.apply = function (scene) {
  66840. scene.particlesEnabled = false;
  66841. return true;
  66842. };
  66843. return _this;
  66844. }
  66845. return ParticlesOptimization;
  66846. }(SceneOptimization));
  66847. BABYLON.ParticlesOptimization = ParticlesOptimization;
  66848. var RenderTargetsOptimization = (function (_super) {
  66849. __extends(RenderTargetsOptimization, _super);
  66850. function RenderTargetsOptimization() {
  66851. var _this = _super !== null && _super.apply(this, arguments) || this;
  66852. _this.apply = function (scene) {
  66853. scene.renderTargetsEnabled = false;
  66854. return true;
  66855. };
  66856. return _this;
  66857. }
  66858. return RenderTargetsOptimization;
  66859. }(SceneOptimization));
  66860. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  66861. var MergeMeshesOptimization = (function (_super) {
  66862. __extends(MergeMeshesOptimization, _super);
  66863. function MergeMeshesOptimization() {
  66864. var _this = _super !== null && _super.apply(this, arguments) || this;
  66865. _this._canBeMerged = function (abstractMesh) {
  66866. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  66867. return false;
  66868. }
  66869. var mesh = abstractMesh;
  66870. if (!mesh.isVisible || !mesh.isEnabled()) {
  66871. return false;
  66872. }
  66873. if (mesh.instances.length > 0) {
  66874. return false;
  66875. }
  66876. if (mesh.skeleton || mesh.hasLODLevels) {
  66877. return false;
  66878. }
  66879. if (mesh.parent) {
  66880. return false;
  66881. }
  66882. return true;
  66883. };
  66884. _this.apply = function (scene, updateSelectionTree) {
  66885. var globalPool = scene.meshes.slice(0);
  66886. var globalLength = globalPool.length;
  66887. for (var index = 0; index < globalLength; index++) {
  66888. var currentPool = new Array();
  66889. var current = globalPool[index];
  66890. // Checks
  66891. if (!_this._canBeMerged(current)) {
  66892. continue;
  66893. }
  66894. currentPool.push(current);
  66895. // Find compatible meshes
  66896. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  66897. var otherMesh = globalPool[subIndex];
  66898. if (!_this._canBeMerged(otherMesh)) {
  66899. continue;
  66900. }
  66901. if (otherMesh.material !== current.material) {
  66902. continue;
  66903. }
  66904. if (otherMesh.checkCollisions !== current.checkCollisions) {
  66905. continue;
  66906. }
  66907. currentPool.push(otherMesh);
  66908. globalLength--;
  66909. globalPool.splice(subIndex, 1);
  66910. subIndex--;
  66911. }
  66912. if (currentPool.length < 2) {
  66913. continue;
  66914. }
  66915. // Merge meshes
  66916. BABYLON.Mesh.MergeMeshes(currentPool);
  66917. }
  66918. if (updateSelectionTree != undefined) {
  66919. if (updateSelectionTree) {
  66920. scene.createOrUpdateSelectionOctree();
  66921. }
  66922. }
  66923. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  66924. scene.createOrUpdateSelectionOctree();
  66925. }
  66926. return true;
  66927. };
  66928. return _this;
  66929. }
  66930. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  66931. get: function () {
  66932. return MergeMeshesOptimization._UpdateSelectionTree;
  66933. },
  66934. set: function (value) {
  66935. MergeMeshesOptimization._UpdateSelectionTree = value;
  66936. },
  66937. enumerable: true,
  66938. configurable: true
  66939. });
  66940. MergeMeshesOptimization._UpdateSelectionTree = false;
  66941. return MergeMeshesOptimization;
  66942. }(SceneOptimization));
  66943. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  66944. // Options
  66945. var SceneOptimizerOptions = (function () {
  66946. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  66947. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  66948. if (trackerDuration === void 0) { trackerDuration = 2000; }
  66949. this.targetFrameRate = targetFrameRate;
  66950. this.trackerDuration = trackerDuration;
  66951. this.optimizations = new Array();
  66952. }
  66953. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  66954. var result = new SceneOptimizerOptions(targetFrameRate);
  66955. var priority = 0;
  66956. result.optimizations.push(new MergeMeshesOptimization(priority));
  66957. result.optimizations.push(new ShadowsOptimization(priority));
  66958. result.optimizations.push(new LensFlaresOptimization(priority));
  66959. // Next priority
  66960. priority++;
  66961. result.optimizations.push(new PostProcessesOptimization(priority));
  66962. result.optimizations.push(new ParticlesOptimization(priority));
  66963. // Next priority
  66964. priority++;
  66965. result.optimizations.push(new TextureOptimization(priority, 1024));
  66966. return result;
  66967. };
  66968. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  66969. var result = new SceneOptimizerOptions(targetFrameRate);
  66970. var priority = 0;
  66971. result.optimizations.push(new MergeMeshesOptimization(priority));
  66972. result.optimizations.push(new ShadowsOptimization(priority));
  66973. result.optimizations.push(new LensFlaresOptimization(priority));
  66974. // Next priority
  66975. priority++;
  66976. result.optimizations.push(new PostProcessesOptimization(priority));
  66977. result.optimizations.push(new ParticlesOptimization(priority));
  66978. // Next priority
  66979. priority++;
  66980. result.optimizations.push(new TextureOptimization(priority, 512));
  66981. // Next priority
  66982. priority++;
  66983. result.optimizations.push(new RenderTargetsOptimization(priority));
  66984. // Next priority
  66985. priority++;
  66986. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  66987. return result;
  66988. };
  66989. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  66990. var result = new SceneOptimizerOptions(targetFrameRate);
  66991. var priority = 0;
  66992. result.optimizations.push(new MergeMeshesOptimization(priority));
  66993. result.optimizations.push(new ShadowsOptimization(priority));
  66994. result.optimizations.push(new LensFlaresOptimization(priority));
  66995. // Next priority
  66996. priority++;
  66997. result.optimizations.push(new PostProcessesOptimization(priority));
  66998. result.optimizations.push(new ParticlesOptimization(priority));
  66999. // Next priority
  67000. priority++;
  67001. result.optimizations.push(new TextureOptimization(priority, 256));
  67002. // Next priority
  67003. priority++;
  67004. result.optimizations.push(new RenderTargetsOptimization(priority));
  67005. // Next priority
  67006. priority++;
  67007. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  67008. return result;
  67009. };
  67010. return SceneOptimizerOptions;
  67011. }());
  67012. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  67013. // Scene optimizer tool
  67014. var SceneOptimizer = (function () {
  67015. function SceneOptimizer() {
  67016. }
  67017. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  67018. // TODO: add an epsilon
  67019. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  67020. if (onSuccess) {
  67021. onSuccess();
  67022. }
  67023. return;
  67024. }
  67025. // Apply current level of optimizations
  67026. var allDone = true;
  67027. var noOptimizationApplied = true;
  67028. for (var index = 0; index < options.optimizations.length; index++) {
  67029. var optimization = options.optimizations[index];
  67030. if (optimization.priority === currentPriorityLevel) {
  67031. noOptimizationApplied = false;
  67032. allDone = allDone && optimization.apply(scene);
  67033. }
  67034. }
  67035. // If no optimization was applied, this is a failure :(
  67036. if (noOptimizationApplied) {
  67037. if (onFailure) {
  67038. onFailure();
  67039. }
  67040. return;
  67041. }
  67042. // If all optimizations were done, move to next level
  67043. if (allDone) {
  67044. currentPriorityLevel++;
  67045. }
  67046. // Let's the system running for a specific amount of time before checking FPS
  67047. scene.executeWhenReady(function () {
  67048. setTimeout(function () {
  67049. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  67050. }, options.trackerDuration);
  67051. });
  67052. };
  67053. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  67054. if (!options) {
  67055. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  67056. }
  67057. // Let's the system running for a specific amount of time before checking FPS
  67058. scene.executeWhenReady(function () {
  67059. setTimeout(function () {
  67060. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  67061. }, options.trackerDuration);
  67062. });
  67063. };
  67064. return SceneOptimizer;
  67065. }());
  67066. BABYLON.SceneOptimizer = SceneOptimizer;
  67067. })(BABYLON || (BABYLON = {}));
  67068. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  67069. var BABYLON;
  67070. (function (BABYLON) {
  67071. var OutlineRenderer = (function () {
  67072. function OutlineRenderer(scene) {
  67073. this.zOffset = 1;
  67074. this._scene = scene;
  67075. }
  67076. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  67077. var _this = this;
  67078. if (useOverlay === void 0) { useOverlay = false; }
  67079. var scene = this._scene;
  67080. var engine = this._scene.getEngine();
  67081. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67082. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  67083. return;
  67084. }
  67085. var mesh = subMesh.getRenderingMesh();
  67086. var material = subMesh.getMaterial();
  67087. engine.enableEffect(this._effect);
  67088. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  67089. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  67090. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67091. // Bones
  67092. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67093. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67094. }
  67095. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  67096. // Alpha test
  67097. if (material && material.needAlphaTesting()) {
  67098. var alphaTexture = material.getAlphaTestTexture();
  67099. if (alphaTexture) {
  67100. this._effect.setTexture("diffuseSampler", alphaTexture);
  67101. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67102. }
  67103. }
  67104. engine.setZOffset(-this.zOffset);
  67105. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  67106. engine.setZOffset(0);
  67107. };
  67108. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  67109. var defines = [];
  67110. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67111. var mesh = subMesh.getMesh();
  67112. var material = subMesh.getMaterial();
  67113. // Alpha test
  67114. if (material && material.needAlphaTesting()) {
  67115. defines.push("#define ALPHATEST");
  67116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67117. attribs.push(BABYLON.VertexBuffer.UVKind);
  67118. defines.push("#define UV1");
  67119. }
  67120. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67121. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67122. defines.push("#define UV2");
  67123. }
  67124. }
  67125. // Bones
  67126. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67127. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67128. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67129. if (mesh.numBoneInfluencers > 4) {
  67130. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67131. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67132. }
  67133. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67134. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67135. }
  67136. else {
  67137. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67138. }
  67139. // Instances
  67140. if (useInstances) {
  67141. defines.push("#define INSTANCES");
  67142. attribs.push("world0");
  67143. attribs.push("world1");
  67144. attribs.push("world2");
  67145. attribs.push("world3");
  67146. }
  67147. // Get correct effect
  67148. var join = defines.join("\n");
  67149. if (this._cachedDefines !== join) {
  67150. this._cachedDefines = join;
  67151. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  67152. }
  67153. return this._effect.isReady();
  67154. };
  67155. return OutlineRenderer;
  67156. }());
  67157. BABYLON.OutlineRenderer = OutlineRenderer;
  67158. })(BABYLON || (BABYLON = {}));
  67159. //# sourceMappingURL=babylon.outlineRenderer.js.map
  67160. var BABYLON;
  67161. (function (BABYLON) {
  67162. var FaceAdjacencies = (function () {
  67163. function FaceAdjacencies() {
  67164. this.edges = new Array();
  67165. this.edgesConnectedCount = 0;
  67166. }
  67167. return FaceAdjacencies;
  67168. }());
  67169. var EdgesRenderer = (function () {
  67170. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  67171. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  67172. if (epsilon === void 0) { epsilon = 0.95; }
  67173. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  67174. this.edgesWidthScalerForOrthographic = 1000.0;
  67175. this.edgesWidthScalerForPerspective = 50.0;
  67176. this._linesPositions = new Array();
  67177. this._linesNormals = new Array();
  67178. this._linesIndices = new Array();
  67179. this._buffers = {};
  67180. this._checkVerticesInsteadOfIndices = false;
  67181. this._source = source;
  67182. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  67183. this._epsilon = epsilon;
  67184. this._prepareRessources();
  67185. this._generateEdgesLines();
  67186. }
  67187. EdgesRenderer.prototype._prepareRessources = function () {
  67188. if (this._lineShader) {
  67189. return;
  67190. }
  67191. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  67192. attributes: ["position", "normal"],
  67193. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  67194. });
  67195. this._lineShader.disableDepthWrite = true;
  67196. this._lineShader.backFaceCulling = false;
  67197. };
  67198. EdgesRenderer.prototype.dispose = function () {
  67199. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  67200. if (buffer) {
  67201. buffer.dispose();
  67202. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  67203. }
  67204. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  67205. if (buffer) {
  67206. buffer.dispose();
  67207. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  67208. }
  67209. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  67210. this._lineShader.dispose();
  67211. };
  67212. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  67213. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  67214. return 0;
  67215. }
  67216. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  67217. return 1;
  67218. }
  67219. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  67220. return 2;
  67221. }
  67222. return -1;
  67223. };
  67224. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  67225. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  67226. return 0;
  67227. }
  67228. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  67229. return 1;
  67230. }
  67231. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  67232. return 2;
  67233. }
  67234. return -1;
  67235. };
  67236. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  67237. var needToCreateLine;
  67238. if (edge === undefined) {
  67239. needToCreateLine = true;
  67240. }
  67241. else {
  67242. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  67243. needToCreateLine = dotProduct < this._epsilon;
  67244. }
  67245. if (needToCreateLine) {
  67246. var offset = this._linesPositions.length / 3;
  67247. var normal = p0.subtract(p1);
  67248. normal.normalize();
  67249. // Positions
  67250. this._linesPositions.push(p0.x);
  67251. this._linesPositions.push(p0.y);
  67252. this._linesPositions.push(p0.z);
  67253. this._linesPositions.push(p0.x);
  67254. this._linesPositions.push(p0.y);
  67255. this._linesPositions.push(p0.z);
  67256. this._linesPositions.push(p1.x);
  67257. this._linesPositions.push(p1.y);
  67258. this._linesPositions.push(p1.z);
  67259. this._linesPositions.push(p1.x);
  67260. this._linesPositions.push(p1.y);
  67261. this._linesPositions.push(p1.z);
  67262. // Normals
  67263. this._linesNormals.push(p1.x);
  67264. this._linesNormals.push(p1.y);
  67265. this._linesNormals.push(p1.z);
  67266. this._linesNormals.push(-1);
  67267. this._linesNormals.push(p1.x);
  67268. this._linesNormals.push(p1.y);
  67269. this._linesNormals.push(p1.z);
  67270. this._linesNormals.push(1);
  67271. this._linesNormals.push(p0.x);
  67272. this._linesNormals.push(p0.y);
  67273. this._linesNormals.push(p0.z);
  67274. this._linesNormals.push(-1);
  67275. this._linesNormals.push(p0.x);
  67276. this._linesNormals.push(p0.y);
  67277. this._linesNormals.push(p0.z);
  67278. this._linesNormals.push(1);
  67279. // Indices
  67280. this._linesIndices.push(offset);
  67281. this._linesIndices.push(offset + 1);
  67282. this._linesIndices.push(offset + 2);
  67283. this._linesIndices.push(offset);
  67284. this._linesIndices.push(offset + 2);
  67285. this._linesIndices.push(offset + 3);
  67286. }
  67287. };
  67288. EdgesRenderer.prototype._generateEdgesLines = function () {
  67289. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67290. var indices = this._source.getIndices();
  67291. // First let's find adjacencies
  67292. var adjacencies = new Array();
  67293. var faceNormals = new Array();
  67294. var index;
  67295. var faceAdjacencies;
  67296. // Prepare faces
  67297. for (index = 0; index < indices.length; index += 3) {
  67298. faceAdjacencies = new FaceAdjacencies();
  67299. var p0Index = indices[index];
  67300. var p1Index = indices[index + 1];
  67301. var p2Index = indices[index + 2];
  67302. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  67303. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  67304. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  67305. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  67306. faceNormal.normalize();
  67307. faceNormals.push(faceNormal);
  67308. adjacencies.push(faceAdjacencies);
  67309. }
  67310. // Scan
  67311. for (index = 0; index < adjacencies.length; index++) {
  67312. faceAdjacencies = adjacencies[index];
  67313. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  67314. var otherFaceAdjacencies = adjacencies[otherIndex];
  67315. if (faceAdjacencies.edgesConnectedCount === 3) {
  67316. break;
  67317. }
  67318. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  67319. continue;
  67320. }
  67321. var otherP0 = indices[otherIndex * 3];
  67322. var otherP1 = indices[otherIndex * 3 + 1];
  67323. var otherP2 = indices[otherIndex * 3 + 2];
  67324. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  67325. var otherEdgeIndex;
  67326. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  67327. continue;
  67328. }
  67329. switch (edgeIndex) {
  67330. case 0:
  67331. if (this._checkVerticesInsteadOfIndices) {
  67332. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67333. }
  67334. else {
  67335. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  67336. }
  67337. break;
  67338. case 1:
  67339. if (this._checkVerticesInsteadOfIndices) {
  67340. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67341. }
  67342. else {
  67343. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  67344. }
  67345. break;
  67346. case 2:
  67347. if (this._checkVerticesInsteadOfIndices) {
  67348. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67349. }
  67350. else {
  67351. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  67352. }
  67353. break;
  67354. }
  67355. if (otherEdgeIndex === -1) {
  67356. continue;
  67357. }
  67358. faceAdjacencies.edges[edgeIndex] = otherIndex;
  67359. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  67360. faceAdjacencies.edgesConnectedCount++;
  67361. otherFaceAdjacencies.edgesConnectedCount++;
  67362. if (faceAdjacencies.edgesConnectedCount === 3) {
  67363. break;
  67364. }
  67365. }
  67366. }
  67367. }
  67368. // Create lines
  67369. for (index = 0; index < adjacencies.length; index++) {
  67370. // 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
  67371. var current = adjacencies[index];
  67372. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  67373. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  67374. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  67375. }
  67376. // Merge into a single mesh
  67377. var engine = this._source.getScene().getEngine();
  67378. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  67379. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  67380. this._ib = engine.createIndexBuffer(this._linesIndices);
  67381. this._indicesCount = this._linesIndices.length;
  67382. };
  67383. EdgesRenderer.prototype.render = function () {
  67384. if (!this._lineShader.isReady()) {
  67385. return;
  67386. }
  67387. var scene = this._source.getScene();
  67388. var engine = scene.getEngine();
  67389. this._lineShader._preBind();
  67390. // VBOs
  67391. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  67392. scene.resetCachedMaterial();
  67393. this._lineShader.setColor4("color", this._source.edgesColor);
  67394. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  67395. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  67396. }
  67397. else {
  67398. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  67399. }
  67400. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  67401. this._lineShader.bind(this._source.getWorldMatrix());
  67402. // Draw order
  67403. engine.draw(true, 0, this._indicesCount);
  67404. this._lineShader.unbind();
  67405. engine.setDepthWrite(true);
  67406. };
  67407. return EdgesRenderer;
  67408. }());
  67409. BABYLON.EdgesRenderer = EdgesRenderer;
  67410. })(BABYLON || (BABYLON = {}));
  67411. //# sourceMappingURL=babylon.edgesRenderer.js.map
  67412. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  67413. /// <reference path="..\Math\babylon.math.ts" />
  67414. var BABYLON;
  67415. (function (BABYLON) {
  67416. /**
  67417. * Special Glow Blur post process only blurring the alpha channel
  67418. * It enforces keeping the most luminous color in the color channel.
  67419. */
  67420. var GlowBlurPostProcess = (function (_super) {
  67421. __extends(GlowBlurPostProcess, _super);
  67422. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  67423. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67424. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  67425. _this.direction = direction;
  67426. _this.kernel = kernel;
  67427. _this.onApplyObservable.add(function (effect) {
  67428. effect.setFloat2("screenSize", _this.width, _this.height);
  67429. effect.setVector2("direction", _this.direction);
  67430. effect.setFloat("blurWidth", _this.kernel);
  67431. });
  67432. return _this;
  67433. }
  67434. return GlowBlurPostProcess;
  67435. }(BABYLON.PostProcess));
  67436. /**
  67437. * The highlight layer Helps adding a glow effect around a mesh.
  67438. *
  67439. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  67440. * glowy meshes to your scene.
  67441. *
  67442. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  67443. */
  67444. var HighlightLayer = (function () {
  67445. /**
  67446. * Instantiates a new highlight Layer and references it to the scene..
  67447. * @param name The name of the layer
  67448. * @param scene The scene to use the layer in
  67449. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  67450. */
  67451. function HighlightLayer(name, scene, options) {
  67452. this.name = name;
  67453. this._vertexBuffers = {};
  67454. this._mainTextureDesiredSize = { width: 0, height: 0 };
  67455. this._meshes = {};
  67456. this._maxSize = 0;
  67457. this._shouldRender = false;
  67458. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  67459. this._excludedMeshes = {};
  67460. /**
  67461. * Specifies whether or not the inner glow is ACTIVE in the layer.
  67462. */
  67463. this.innerGlow = true;
  67464. /**
  67465. * Specifies whether or not the outer glow is ACTIVE in the layer.
  67466. */
  67467. this.outerGlow = true;
  67468. /**
  67469. * Specifies wether the highlight layer is enabled or not.
  67470. */
  67471. this.isEnabled = true;
  67472. /**
  67473. * An event triggered when the highlight layer has been disposed.
  67474. * @type {BABYLON.Observable}
  67475. */
  67476. this.onDisposeObservable = new BABYLON.Observable();
  67477. /**
  67478. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  67479. * @type {BABYLON.Observable}
  67480. */
  67481. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  67482. /**
  67483. * An event triggered when the highlight layer is being blurred.
  67484. * @type {BABYLON.Observable}
  67485. */
  67486. this.onBeforeBlurObservable = new BABYLON.Observable();
  67487. /**
  67488. * An event triggered when the highlight layer has been blurred.
  67489. * @type {BABYLON.Observable}
  67490. */
  67491. this.onAfterBlurObservable = new BABYLON.Observable();
  67492. /**
  67493. * An event triggered when the glowing blurred texture is being merged in the scene.
  67494. * @type {BABYLON.Observable}
  67495. */
  67496. this.onBeforeComposeObservable = new BABYLON.Observable();
  67497. /**
  67498. * An event triggered when the glowing blurred texture has been merged in the scene.
  67499. * @type {BABYLON.Observable}
  67500. */
  67501. this.onAfterComposeObservable = new BABYLON.Observable();
  67502. /**
  67503. * An event triggered when the highlight layer changes its size.
  67504. * @type {BABYLON.Observable}
  67505. */
  67506. this.onSizeChangedObservable = new BABYLON.Observable();
  67507. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67508. var engine = scene.getEngine();
  67509. this._engine = engine;
  67510. this._maxSize = this._engine.getCaps().maxTextureSize;
  67511. this._scene.highlightLayers.push(this);
  67512. // Warn on stencil.
  67513. if (!this._engine.isStencilEnable) {
  67514. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  67515. }
  67516. // Adapt options
  67517. this._options = options || {
  67518. mainTextureRatio: 0.5,
  67519. blurTextureSizeRatio: 0.5,
  67520. blurHorizontalSize: 1.0,
  67521. blurVerticalSize: 1.0,
  67522. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  67523. };
  67524. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  67525. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  67526. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  67527. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  67528. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  67529. // VBO
  67530. var vertices = [];
  67531. vertices.push(1, 1);
  67532. vertices.push(-1, 1);
  67533. vertices.push(-1, -1);
  67534. vertices.push(1, -1);
  67535. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67536. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  67537. this._createIndexBuffer();
  67538. // Effect
  67539. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  67540. // Render target
  67541. this.setMainTextureSize();
  67542. // Create Textures and post processes
  67543. this.createTextureAndPostProcesses();
  67544. }
  67545. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  67546. /**
  67547. * Gets the horizontal size of the blur.
  67548. */
  67549. get: function () {
  67550. return this._horizontalBlurPostprocess.kernel;
  67551. },
  67552. /**
  67553. * Specifies the horizontal size of the blur.
  67554. */
  67555. set: function (value) {
  67556. this._horizontalBlurPostprocess.kernel = value;
  67557. },
  67558. enumerable: true,
  67559. configurable: true
  67560. });
  67561. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  67562. /**
  67563. * Gets the vertical size of the blur.
  67564. */
  67565. get: function () {
  67566. return this._verticalBlurPostprocess.kernel;
  67567. },
  67568. /**
  67569. * Specifies the vertical size of the blur.
  67570. */
  67571. set: function (value) {
  67572. this._verticalBlurPostprocess.kernel = value;
  67573. },
  67574. enumerable: true,
  67575. configurable: true
  67576. });
  67577. Object.defineProperty(HighlightLayer.prototype, "camera", {
  67578. /**
  67579. * Gets the camera attached to the layer.
  67580. */
  67581. get: function () {
  67582. return this._options.camera;
  67583. },
  67584. enumerable: true,
  67585. configurable: true
  67586. });
  67587. HighlightLayer.prototype._createIndexBuffer = function () {
  67588. var engine = this._scene.getEngine();
  67589. // Indices
  67590. var indices = [];
  67591. indices.push(0);
  67592. indices.push(1);
  67593. indices.push(2);
  67594. indices.push(0);
  67595. indices.push(2);
  67596. indices.push(3);
  67597. this._indexBuffer = engine.createIndexBuffer(indices);
  67598. };
  67599. HighlightLayer.prototype._rebuild = function () {
  67600. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  67601. this._createIndexBuffer();
  67602. };
  67603. /**
  67604. * Creates the render target textures and post processes used in the highlight layer.
  67605. */
  67606. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  67607. var _this = this;
  67608. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  67609. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  67610. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  67611. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  67612. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  67613. width: this._mainTextureDesiredSize.width,
  67614. height: this._mainTextureDesiredSize.height
  67615. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67616. this._mainTexture.activeCamera = this._options.camera;
  67617. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67618. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67619. this._mainTexture.anisotropicFilteringLevel = 1;
  67620. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67621. this._mainTexture.renderParticles = false;
  67622. this._mainTexture.renderList = null;
  67623. this._mainTexture.ignoreCameraViewport = true;
  67624. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  67625. width: blurTextureWidth,
  67626. height: blurTextureHeight
  67627. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67628. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67629. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67630. this._blurTexture.anisotropicFilteringLevel = 16;
  67631. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67632. this._blurTexture.renderParticles = false;
  67633. this._blurTexture.ignoreCameraViewport = true;
  67634. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67635. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  67636. effect.setTexture("textureSampler", _this._mainTexture);
  67637. });
  67638. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  67639. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67640. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  67641. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67642. });
  67643. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67644. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  67645. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67646. });
  67647. }
  67648. else {
  67649. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67650. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  67651. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67652. });
  67653. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67654. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  67655. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67656. });
  67657. }
  67658. this._mainTexture.onAfterUnbindObservable.add(function () {
  67659. _this.onBeforeBlurObservable.notifyObservers(_this);
  67660. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  67661. _this.onAfterBlurObservable.notifyObservers(_this);
  67662. });
  67663. // Custom render function
  67664. var renderSubMesh = function (subMesh) {
  67665. var mesh = subMesh.getRenderingMesh();
  67666. var scene = _this._scene;
  67667. var engine = scene.getEngine();
  67668. // Culling
  67669. engine.setState(subMesh.getMaterial().backFaceCulling);
  67670. // Managing instances
  67671. var batch = mesh._getInstancesRenderList(subMesh._id);
  67672. if (batch.mustReturn) {
  67673. return;
  67674. }
  67675. // Excluded Mesh
  67676. if (_this._excludedMeshes[mesh.uniqueId]) {
  67677. return;
  67678. }
  67679. ;
  67680. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67681. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  67682. var material = subMesh.getMaterial();
  67683. var emissiveTexture = null;
  67684. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  67685. emissiveTexture = material.emissiveTexture;
  67686. }
  67687. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  67688. engine.enableEffect(_this._glowMapGenerationEffect);
  67689. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  67690. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  67691. if (highlightLayerMesh) {
  67692. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  67693. }
  67694. else {
  67695. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  67696. }
  67697. // Alpha test
  67698. if (material && material.needAlphaTesting()) {
  67699. var alphaTexture = material.getAlphaTestTexture();
  67700. if (alphaTexture) {
  67701. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  67702. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67703. }
  67704. }
  67705. // Glow emissive only
  67706. if (emissiveTexture) {
  67707. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  67708. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  67709. }
  67710. // Bones
  67711. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67712. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67713. }
  67714. // Draw
  67715. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  67716. }
  67717. else {
  67718. // Need to reset refresh rate of the shadowMap
  67719. _this._mainTexture.resetRefreshCounter();
  67720. }
  67721. };
  67722. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  67723. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  67724. var index;
  67725. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67726. renderSubMesh(opaqueSubMeshes.data[index]);
  67727. }
  67728. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67729. renderSubMesh(alphaTestSubMeshes.data[index]);
  67730. }
  67731. for (index = 0; index < transparentSubMeshes.length; index++) {
  67732. renderSubMesh(transparentSubMeshes.data[index]);
  67733. }
  67734. };
  67735. this._mainTexture.onClearObservable.add(function (engine) {
  67736. engine.clear(HighlightLayer.neutralColor, true, true, true);
  67737. });
  67738. };
  67739. /**
  67740. * Checks for the readiness of the element composing the layer.
  67741. * @param subMesh the mesh to check for
  67742. * @param useInstances specify wether or not to use instances to render the mesh
  67743. * @param emissiveTexture the associated emissive texture used to generate the glow
  67744. * @return true if ready otherwise, false
  67745. */
  67746. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  67747. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  67748. return false;
  67749. }
  67750. var defines = [];
  67751. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67752. var mesh = subMesh.getMesh();
  67753. var material = subMesh.getMaterial();
  67754. var uv1 = false;
  67755. var uv2 = false;
  67756. // Alpha test
  67757. if (material && material.needAlphaTesting()) {
  67758. var alphaTexture = material.getAlphaTestTexture();
  67759. if (alphaTexture) {
  67760. defines.push("#define ALPHATEST");
  67761. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  67762. alphaTexture.coordinatesIndex === 1) {
  67763. defines.push("#define DIFFUSEUV2");
  67764. uv2 = true;
  67765. }
  67766. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67767. defines.push("#define DIFFUSEUV1");
  67768. uv1 = true;
  67769. }
  67770. }
  67771. }
  67772. // Emissive
  67773. if (emissiveTexture) {
  67774. defines.push("#define EMISSIVE");
  67775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  67776. emissiveTexture.coordinatesIndex === 1) {
  67777. defines.push("#define EMISSIVEUV2");
  67778. uv2 = true;
  67779. }
  67780. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67781. defines.push("#define EMISSIVEUV1");
  67782. uv1 = true;
  67783. }
  67784. }
  67785. if (uv1) {
  67786. attribs.push(BABYLON.VertexBuffer.UVKind);
  67787. defines.push("#define UV1");
  67788. }
  67789. if (uv2) {
  67790. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67791. defines.push("#define UV2");
  67792. }
  67793. // Bones
  67794. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67795. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67796. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67797. if (mesh.numBoneInfluencers > 4) {
  67798. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67799. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67800. }
  67801. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67802. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67803. }
  67804. else {
  67805. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67806. }
  67807. // Instances
  67808. if (useInstances) {
  67809. defines.push("#define INSTANCES");
  67810. attribs.push("world0");
  67811. attribs.push("world1");
  67812. attribs.push("world2");
  67813. attribs.push("world3");
  67814. }
  67815. // Get correct effect
  67816. var join = defines.join("\n");
  67817. if (this._cachedDefines !== join) {
  67818. this._cachedDefines = join;
  67819. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  67820. }
  67821. return this._glowMapGenerationEffect.isReady();
  67822. };
  67823. /**
  67824. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  67825. */
  67826. HighlightLayer.prototype.render = function () {
  67827. var currentEffect = this._glowMapMergeEffect;
  67828. // Check
  67829. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  67830. return;
  67831. var engine = this._scene.getEngine();
  67832. this.onBeforeComposeObservable.notifyObservers(this);
  67833. // Render
  67834. engine.enableEffect(currentEffect);
  67835. engine.setState(false);
  67836. // Cache
  67837. var previousStencilBuffer = engine.getStencilBuffer();
  67838. var previousStencilFunction = engine.getStencilFunction();
  67839. var previousStencilMask = engine.getStencilMask();
  67840. var previousStencilOperationPass = engine.getStencilOperationPass();
  67841. var previousStencilOperationFail = engine.getStencilOperationFail();
  67842. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  67843. var previousAlphaMode = engine.getAlphaMode();
  67844. // Texture
  67845. currentEffect.setTexture("textureSampler", this._blurTexture);
  67846. // VBOs
  67847. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  67848. // Stencil operations
  67849. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  67850. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  67851. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  67852. // Draw order
  67853. engine.setAlphaMode(this._options.alphaBlendingMode);
  67854. engine.setStencilMask(0x00);
  67855. engine.setStencilBuffer(true);
  67856. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  67857. if (this.outerGlow) {
  67858. currentEffect.setFloat("offset", 0);
  67859. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  67860. engine.draw(true, 0, 6);
  67861. }
  67862. if (this.innerGlow) {
  67863. currentEffect.setFloat("offset", 1);
  67864. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  67865. engine.draw(true, 0, 6);
  67866. }
  67867. // Restore Cache
  67868. engine.setStencilFunction(previousStencilFunction);
  67869. engine.setStencilMask(previousStencilMask);
  67870. engine.setAlphaMode(previousAlphaMode);
  67871. engine.setStencilBuffer(previousStencilBuffer);
  67872. engine.setStencilOperationPass(previousStencilOperationPass);
  67873. engine.setStencilOperationFail(previousStencilOperationFail);
  67874. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  67875. engine._stencilState.reset();
  67876. this.onAfterComposeObservable.notifyObservers(this);
  67877. // Handle size changes.
  67878. var size = this._mainTexture.getSize();
  67879. this.setMainTextureSize();
  67880. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  67881. // Recreate RTT and post processes on size change.
  67882. this.onSizeChangedObservable.notifyObservers(this);
  67883. this.disposeTextureAndPostProcesses();
  67884. this.createTextureAndPostProcesses();
  67885. }
  67886. };
  67887. /**
  67888. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  67889. * @param mesh The mesh to exclude from the highlight layer
  67890. */
  67891. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  67892. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  67893. if (!meshExcluded) {
  67894. this._excludedMeshes[mesh.uniqueId] = {
  67895. mesh: mesh,
  67896. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  67897. mesh.getEngine().setStencilBuffer(false);
  67898. }),
  67899. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  67900. mesh.getEngine().setStencilBuffer(true);
  67901. }),
  67902. };
  67903. }
  67904. };
  67905. /**
  67906. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  67907. * @param mesh The mesh to highlight
  67908. */
  67909. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  67910. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  67911. if (meshExcluded) {
  67912. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  67913. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  67914. }
  67915. this._excludedMeshes[mesh.uniqueId] = undefined;
  67916. };
  67917. /**
  67918. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  67919. * @param mesh The mesh to highlight
  67920. * @param color The color of the highlight
  67921. * @param glowEmissiveOnly Extract the glow from the emissive texture
  67922. */
  67923. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  67924. var _this = this;
  67925. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  67926. var meshHighlight = this._meshes[mesh.uniqueId];
  67927. if (meshHighlight) {
  67928. meshHighlight.color = color;
  67929. }
  67930. else {
  67931. this._meshes[mesh.uniqueId] = {
  67932. mesh: mesh,
  67933. color: color,
  67934. // Lambda required for capture due to Observable this context
  67935. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  67936. if (_this._excludedMeshes[mesh.uniqueId]) {
  67937. _this.defaultStencilReference(mesh);
  67938. }
  67939. else {
  67940. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  67941. }
  67942. }),
  67943. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  67944. glowEmissiveOnly: glowEmissiveOnly
  67945. };
  67946. }
  67947. this._shouldRender = true;
  67948. };
  67949. /**
  67950. * Remove a mesh from the highlight layer in order to make it stop glowing.
  67951. * @param mesh The mesh to highlight
  67952. */
  67953. HighlightLayer.prototype.removeMesh = function (mesh) {
  67954. var meshHighlight = this._meshes[mesh.uniqueId];
  67955. if (meshHighlight) {
  67956. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  67957. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  67958. }
  67959. this._meshes[mesh.uniqueId] = undefined;
  67960. this._shouldRender = false;
  67961. for (var meshHighlightToCheck in this._meshes) {
  67962. if (meshHighlightToCheck) {
  67963. this._shouldRender = true;
  67964. break;
  67965. }
  67966. }
  67967. };
  67968. /**
  67969. * Returns true if the layer contains information to display, otherwise false.
  67970. */
  67971. HighlightLayer.prototype.shouldRender = function () {
  67972. return this.isEnabled && this._shouldRender;
  67973. };
  67974. /**
  67975. * Sets the main texture desired size which is the closest power of two
  67976. * of the engine canvas size.
  67977. */
  67978. HighlightLayer.prototype.setMainTextureSize = function () {
  67979. if (this._options.mainTextureFixedSize) {
  67980. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  67981. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  67982. }
  67983. else {
  67984. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  67985. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  67986. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  67987. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  67988. }
  67989. };
  67990. /**
  67991. * Force the stencil to the normal expected value for none glowing parts
  67992. */
  67993. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  67994. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  67995. };
  67996. /**
  67997. * Dispose only the render target textures and post process.
  67998. */
  67999. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  68000. this._blurTexture.dispose();
  68001. this._mainTexture.dispose();
  68002. this._downSamplePostprocess.dispose();
  68003. this._horizontalBlurPostprocess.dispose();
  68004. this._verticalBlurPostprocess.dispose();
  68005. };
  68006. /**
  68007. * Dispose the highlight layer and free resources.
  68008. */
  68009. HighlightLayer.prototype.dispose = function () {
  68010. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68011. if (vertexBuffer) {
  68012. vertexBuffer.dispose();
  68013. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68014. }
  68015. if (this._indexBuffer) {
  68016. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68017. this._indexBuffer = null;
  68018. }
  68019. // Clean textures and post processes
  68020. this.disposeTextureAndPostProcesses();
  68021. // Clean mesh references
  68022. for (var id in this._meshes) {
  68023. var meshHighlight = this._meshes[id];
  68024. if (meshHighlight && meshHighlight.mesh) {
  68025. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  68026. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  68027. }
  68028. }
  68029. this._meshes = null;
  68030. for (var id in this._excludedMeshes) {
  68031. var meshHighlight = this._excludedMeshes[id];
  68032. if (meshHighlight) {
  68033. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  68034. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  68035. }
  68036. }
  68037. this._excludedMeshes = null;
  68038. // Remove from scene
  68039. var index = this._scene.highlightLayers.indexOf(this, 0);
  68040. if (index > -1) {
  68041. this._scene.highlightLayers.splice(index, 1);
  68042. }
  68043. // Callback
  68044. this.onDisposeObservable.notifyObservers(this);
  68045. this.onDisposeObservable.clear();
  68046. this.onBeforeRenderMainTextureObservable.clear();
  68047. this.onBeforeBlurObservable.clear();
  68048. this.onBeforeComposeObservable.clear();
  68049. this.onAfterComposeObservable.clear();
  68050. this.onSizeChangedObservable.clear();
  68051. };
  68052. /**
  68053. * The neutral color used during the preparation of the glow effect.
  68054. * This is black by default as the blend operation is a blend operation.
  68055. */
  68056. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  68057. /**
  68058. * Stencil value used for glowing meshes.
  68059. */
  68060. HighlightLayer.glowingMeshStencilReference = 0x02;
  68061. /**
  68062. * Stencil value used for the other meshes in the scene.
  68063. */
  68064. HighlightLayer.normalMeshStencilReference = 0x01;
  68065. return HighlightLayer;
  68066. }());
  68067. BABYLON.HighlightLayer = HighlightLayer;
  68068. })(BABYLON || (BABYLON = {}));
  68069. //# sourceMappingURL=babylon.highlightlayer.js.map
  68070. var BABYLON;
  68071. (function (BABYLON) {
  68072. var MeshAssetTask = (function () {
  68073. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  68074. this.name = name;
  68075. this.meshesNames = meshesNames;
  68076. this.rootUrl = rootUrl;
  68077. this.sceneFilename = sceneFilename;
  68078. this.isCompleted = false;
  68079. }
  68080. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68081. var _this = this;
  68082. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  68083. _this.loadedMeshes = meshes;
  68084. _this.loadedParticleSystems = particleSystems;
  68085. _this.loadedSkeletons = skeletons;
  68086. _this.isCompleted = true;
  68087. if (_this.onSuccess) {
  68088. _this.onSuccess(_this);
  68089. }
  68090. onSuccess();
  68091. }, null, function () {
  68092. if (_this.onError) {
  68093. _this.onError(_this);
  68094. }
  68095. onError();
  68096. });
  68097. };
  68098. return MeshAssetTask;
  68099. }());
  68100. BABYLON.MeshAssetTask = MeshAssetTask;
  68101. var TextFileAssetTask = (function () {
  68102. function TextFileAssetTask(name, url) {
  68103. this.name = name;
  68104. this.url = url;
  68105. this.isCompleted = false;
  68106. }
  68107. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68108. var _this = this;
  68109. BABYLON.Tools.LoadFile(this.url, function (data) {
  68110. _this.text = data;
  68111. _this.isCompleted = true;
  68112. if (_this.onSuccess) {
  68113. _this.onSuccess(_this);
  68114. }
  68115. onSuccess();
  68116. }, null, scene.database, false, function () {
  68117. if (_this.onError) {
  68118. _this.onError(_this);
  68119. }
  68120. onError();
  68121. });
  68122. };
  68123. return TextFileAssetTask;
  68124. }());
  68125. BABYLON.TextFileAssetTask = TextFileAssetTask;
  68126. var BinaryFileAssetTask = (function () {
  68127. function BinaryFileAssetTask(name, url) {
  68128. this.name = name;
  68129. this.url = url;
  68130. this.isCompleted = false;
  68131. }
  68132. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68133. var _this = this;
  68134. BABYLON.Tools.LoadFile(this.url, function (data) {
  68135. _this.data = data;
  68136. _this.isCompleted = true;
  68137. if (_this.onSuccess) {
  68138. _this.onSuccess(_this);
  68139. }
  68140. onSuccess();
  68141. }, null, scene.database, true, function () {
  68142. if (_this.onError) {
  68143. _this.onError(_this);
  68144. }
  68145. onError();
  68146. });
  68147. };
  68148. return BinaryFileAssetTask;
  68149. }());
  68150. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  68151. var ImageAssetTask = (function () {
  68152. function ImageAssetTask(name, url) {
  68153. this.name = name;
  68154. this.url = url;
  68155. this.isCompleted = false;
  68156. }
  68157. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68158. var _this = this;
  68159. var img = new Image();
  68160. BABYLON.Tools.SetCorsBehavior(this.url, img);
  68161. img.onload = function () {
  68162. _this.image = img;
  68163. _this.isCompleted = true;
  68164. if (_this.onSuccess) {
  68165. _this.onSuccess(_this);
  68166. }
  68167. onSuccess();
  68168. };
  68169. img.onerror = function () {
  68170. if (_this.onError) {
  68171. _this.onError(_this);
  68172. }
  68173. onError();
  68174. };
  68175. img.src = this.url;
  68176. };
  68177. return ImageAssetTask;
  68178. }());
  68179. BABYLON.ImageAssetTask = ImageAssetTask;
  68180. var TextureAssetTask = (function () {
  68181. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  68182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68183. this.name = name;
  68184. this.url = url;
  68185. this.noMipmap = noMipmap;
  68186. this.invertY = invertY;
  68187. this.samplingMode = samplingMode;
  68188. this.isCompleted = false;
  68189. }
  68190. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68191. var _this = this;
  68192. var onload = function () {
  68193. _this.isCompleted = true;
  68194. if (_this.onSuccess) {
  68195. _this.onSuccess(_this);
  68196. }
  68197. onSuccess();
  68198. };
  68199. var onerror = function () {
  68200. if (_this.onError) {
  68201. _this.onError(_this);
  68202. }
  68203. onError();
  68204. };
  68205. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  68206. };
  68207. return TextureAssetTask;
  68208. }());
  68209. BABYLON.TextureAssetTask = TextureAssetTask;
  68210. var CubeTextureAssetTask = (function () {
  68211. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  68212. this.name = name;
  68213. this.url = url;
  68214. this.extensions = extensions;
  68215. this.noMipmap = noMipmap;
  68216. this.files = files;
  68217. this.isCompleted = false;
  68218. }
  68219. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68220. var _this = this;
  68221. var onload = function () {
  68222. _this.isCompleted = true;
  68223. if (_this.onSuccess) {
  68224. _this.onSuccess(_this);
  68225. }
  68226. onSuccess();
  68227. };
  68228. var onerror = function () {
  68229. if (_this.onError) {
  68230. _this.onError(_this);
  68231. }
  68232. onError();
  68233. };
  68234. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  68235. };
  68236. return CubeTextureAssetTask;
  68237. }());
  68238. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  68239. var HDRCubeTextureAssetTask = (function () {
  68240. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  68241. if (noMipmap === void 0) { noMipmap = false; }
  68242. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68243. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68244. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68245. this.name = name;
  68246. this.url = url;
  68247. this.size = size;
  68248. this.noMipmap = noMipmap;
  68249. this.generateHarmonics = generateHarmonics;
  68250. this.useInGammaSpace = useInGammaSpace;
  68251. this.usePMREMGenerator = usePMREMGenerator;
  68252. this.isCompleted = false;
  68253. }
  68254. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68255. var _this = this;
  68256. var onload = function () {
  68257. _this.isCompleted = true;
  68258. if (_this.onSuccess) {
  68259. _this.onSuccess(_this);
  68260. }
  68261. onSuccess();
  68262. };
  68263. var onerror = function () {
  68264. if (_this.onError) {
  68265. _this.onError(_this);
  68266. }
  68267. onError();
  68268. };
  68269. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  68270. };
  68271. return HDRCubeTextureAssetTask;
  68272. }());
  68273. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  68274. var AssetsManager = (function () {
  68275. function AssetsManager(scene) {
  68276. this.tasks = new Array();
  68277. this.waitingTasksCount = 0;
  68278. this.useDefaultLoadingScreen = true;
  68279. this._scene = scene;
  68280. }
  68281. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  68282. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  68283. this.tasks.push(task);
  68284. return task;
  68285. };
  68286. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  68287. var task = new TextFileAssetTask(taskName, url);
  68288. this.tasks.push(task);
  68289. return task;
  68290. };
  68291. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  68292. var task = new BinaryFileAssetTask(taskName, url);
  68293. this.tasks.push(task);
  68294. return task;
  68295. };
  68296. AssetsManager.prototype.addImageTask = function (taskName, url) {
  68297. var task = new ImageAssetTask(taskName, url);
  68298. this.tasks.push(task);
  68299. return task;
  68300. };
  68301. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  68302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68303. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  68304. this.tasks.push(task);
  68305. return task;
  68306. };
  68307. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  68308. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  68309. this.tasks.push(task);
  68310. return task;
  68311. };
  68312. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  68313. if (noMipmap === void 0) { noMipmap = false; }
  68314. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68315. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68316. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68317. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  68318. this.tasks.push(task);
  68319. return task;
  68320. };
  68321. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  68322. this.waitingTasksCount--;
  68323. if (this.waitingTasksCount === 0) {
  68324. if (this.onFinish) {
  68325. this.onFinish(this.tasks);
  68326. }
  68327. this._scene.getEngine().hideLoadingUI();
  68328. }
  68329. };
  68330. AssetsManager.prototype._runTask = function (task) {
  68331. var _this = this;
  68332. task.run(this._scene, function () {
  68333. if (_this.onTaskSuccess) {
  68334. _this.onTaskSuccess(task);
  68335. }
  68336. _this._decreaseWaitingTasksCount();
  68337. }, function () {
  68338. if (_this.onTaskError) {
  68339. _this.onTaskError(task);
  68340. }
  68341. _this._decreaseWaitingTasksCount();
  68342. });
  68343. };
  68344. AssetsManager.prototype.reset = function () {
  68345. this.tasks = new Array();
  68346. return this;
  68347. };
  68348. AssetsManager.prototype.load = function () {
  68349. this.waitingTasksCount = this.tasks.length;
  68350. if (this.waitingTasksCount === 0) {
  68351. if (this.onFinish) {
  68352. this.onFinish(this.tasks);
  68353. }
  68354. return this;
  68355. }
  68356. if (this.useDefaultLoadingScreen) {
  68357. this._scene.getEngine().displayLoadingUI();
  68358. }
  68359. for (var index = 0; index < this.tasks.length; index++) {
  68360. var task = this.tasks[index];
  68361. this._runTask(task);
  68362. }
  68363. return this;
  68364. };
  68365. return AssetsManager;
  68366. }());
  68367. BABYLON.AssetsManager = AssetsManager;
  68368. })(BABYLON || (BABYLON = {}));
  68369. //# sourceMappingURL=babylon.assetsManager.js.map
  68370. var BABYLON;
  68371. (function (BABYLON) {
  68372. var MapTexture = (function (_super) {
  68373. __extends(MapTexture, _super);
  68374. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  68375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68376. if (useMipMap === void 0) { useMipMap = false; }
  68377. if (margin === void 0) { margin = 0; }
  68378. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  68379. _this.name = name;
  68380. _this._size = size;
  68381. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68382. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68383. // Create the rectPackMap that will allocate portion of the texture
  68384. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  68385. // Create the texture that will store the content
  68386. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  68387. return _this;
  68388. }
  68389. /**
  68390. * Allocate a rectangle of a given size in the texture map
  68391. * @param size the size of the rectangle to allocation
  68392. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  68393. */
  68394. MapTexture.prototype.allocateRect = function (size) {
  68395. return this._rectPackingMap.addRect(size);
  68396. };
  68397. /**
  68398. * Free a given rectangle from the texture map
  68399. * @param rectInfo the instance corresponding to the rect to free.
  68400. */
  68401. MapTexture.prototype.freeRect = function (rectInfo) {
  68402. if (rectInfo) {
  68403. rectInfo.freeContent();
  68404. }
  68405. };
  68406. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  68407. /**
  68408. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  68409. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  68410. * @returns {}
  68411. */
  68412. get: function () {
  68413. return this._rectPackingMap.freeSpace;
  68414. },
  68415. enumerable: true,
  68416. configurable: true
  68417. });
  68418. /**
  68419. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  68420. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  68421. * Don't forget to call unbindTexture when you're done rendering
  68422. * @param rect the zone to render to
  68423. * @param clear true to clear the portion's color/depth data
  68424. */
  68425. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  68426. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  68427. };
  68428. /**
  68429. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  68430. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  68431. * Don't forget to call unbindTexture when you're done rendering
  68432. * @param pos the position into the texture
  68433. * @param size the portion to fit the clip space to
  68434. * @param clear true to clear the portion's color/depth data
  68435. */
  68436. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  68437. var engine = this.getScene().getEngine();
  68438. engine.bindFramebuffer(this._texture);
  68439. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  68440. if (clear) {
  68441. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  68442. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  68443. }
  68444. };
  68445. /**
  68446. * Unbind the texture map from the rendering engine.
  68447. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  68448. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  68449. */
  68450. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  68451. // Dump ?
  68452. if (dumpForDebug) {
  68453. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  68454. }
  68455. var engine = this.getScene().getEngine();
  68456. if (this._replacedViewport) {
  68457. engine.setViewport(this._replacedViewport);
  68458. this._replacedViewport = null;
  68459. }
  68460. engine.unBindFramebuffer(this._texture);
  68461. };
  68462. Object.defineProperty(MapTexture.prototype, "canRescale", {
  68463. get: function () {
  68464. return false;
  68465. },
  68466. enumerable: true,
  68467. configurable: true
  68468. });
  68469. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  68470. // Anyway, there's not much point to use this method for this kind of texture I guess
  68471. MapTexture.prototype.clone = function () {
  68472. return null;
  68473. };
  68474. return MapTexture;
  68475. }(BABYLON.Texture));
  68476. BABYLON.MapTexture = MapTexture;
  68477. })(BABYLON || (BABYLON = {}));
  68478. //# sourceMappingURL=babylon.mapTexture.js.map
  68479. var BABYLON;
  68480. (function (BABYLON) {
  68481. /**
  68482. * This class describe a rectangle that were added to the map.
  68483. * You have access to its coordinates either in pixel or normalized (UV)
  68484. */
  68485. var PackedRect = (function () {
  68486. function PackedRect(root, parent, pos, size) {
  68487. this._pos = pos;
  68488. this._size = size;
  68489. this._root = root;
  68490. this._parent = parent;
  68491. this._contentSize = null;
  68492. this._bottomNode = null;
  68493. this._leftNode = null;
  68494. this._initialSize = null;
  68495. this._rightNode = null;
  68496. }
  68497. Object.defineProperty(PackedRect.prototype, "pos", {
  68498. /**
  68499. * @returns the position of this node into the map
  68500. */
  68501. get: function () {
  68502. return this._pos;
  68503. },
  68504. enumerable: true,
  68505. configurable: true
  68506. });
  68507. Object.defineProperty(PackedRect.prototype, "contentSize", {
  68508. /**
  68509. * @returns the size of the rectangle this node handles
  68510. */
  68511. get: function () {
  68512. return this._contentSize;
  68513. },
  68514. enumerable: true,
  68515. configurable: true
  68516. });
  68517. /**
  68518. * Retrieve the inner position (considering the margin) and stores it into the res object
  68519. * @param res must be a valid Vector2 that will contain the inner position after this call
  68520. */
  68521. PackedRect.prototype.getInnerPosToRef = function (res) {
  68522. var m = this._root._margin;
  68523. res.x = this._pos.x + m;
  68524. res.y = this._pos.y + m;
  68525. };
  68526. /**
  68527. * Retrieve the inner size (considering the margin) and stores it into the res object
  68528. * @param res must be a valid Size that will contain the inner size after this call
  68529. */
  68530. PackedRect.prototype.getInnerSizeToRef = function (res) {
  68531. var m = this._root._margin;
  68532. res.width = this._contentSize.width - (m * 2);
  68533. res.height = this._contentSize.height - (m * 2);
  68534. };
  68535. Object.defineProperty(PackedRect.prototype, "UVs", {
  68536. /**
  68537. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  68538. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  68539. */
  68540. get: function () {
  68541. if (!this._contentSize) {
  68542. throw new Error("Can't compute UVs for this object because it's nor allocated");
  68543. }
  68544. return this.getUVsForCustomSize(this._contentSize);
  68545. },
  68546. enumerable: true,
  68547. configurable: true
  68548. });
  68549. /**
  68550. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  68551. * and then using only a part of the PackRect.
  68552. * This method will return the UVs for this part by given the custom size of what you really use
  68553. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  68554. */
  68555. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  68556. var mainWidth = this._root._size.width;
  68557. var mainHeight = this._root._size.height;
  68558. var margin = this._root._margin;
  68559. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  68560. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  68561. var uvs = new Array();
  68562. uvs.push(topLeft);
  68563. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  68564. uvs.push(rightBottom);
  68565. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  68566. return uvs;
  68567. };
  68568. /**
  68569. * Free this rectangle from the map.
  68570. * Call this method when you no longer need the rectangle to be in the map.
  68571. */
  68572. PackedRect.prototype.freeContent = function () {
  68573. if (!this.contentSize) {
  68574. return;
  68575. }
  68576. this._contentSize = null;
  68577. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  68578. this.attemptDefrag();
  68579. };
  68580. Object.defineProperty(PackedRect.prototype, "isUsed", {
  68581. get: function () {
  68582. return this._contentSize != null || this._leftNode != null;
  68583. },
  68584. enumerable: true,
  68585. configurable: true
  68586. });
  68587. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  68588. var node = this.findNode(contentSize);
  68589. // Not enough space...
  68590. if (!node) {
  68591. return null;
  68592. }
  68593. node.splitNode(contentSize);
  68594. return node;
  68595. };
  68596. PackedRect.prototype.findNode = function (size) {
  68597. var resNode = null;
  68598. var margin = this._root._margin * 2;
  68599. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  68600. if (this.isUsed) {
  68601. if (this._leftNode) {
  68602. resNode = this._leftNode.findNode(size);
  68603. }
  68604. if (!resNode && this._rightNode) {
  68605. resNode = this._rightNode.findNode(size);
  68606. }
  68607. if (!resNode && this._bottomNode) {
  68608. resNode = this._bottomNode.findNode(size);
  68609. }
  68610. }
  68611. else if (this._initialSize) {
  68612. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  68613. resNode = this;
  68614. }
  68615. else {
  68616. return null;
  68617. }
  68618. }
  68619. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  68620. resNode = this;
  68621. }
  68622. return resNode;
  68623. };
  68624. PackedRect.prototype.splitNode = function (contentSize) {
  68625. var cs = PackedRect.TpsSize;
  68626. var margin = this._root._margin * 2;
  68627. cs.copyFrom(contentSize);
  68628. cs.width += margin;
  68629. cs.height += margin;
  68630. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  68631. if (!this._contentSize && this._initialSize) {
  68632. this._contentSize = cs.clone();
  68633. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  68634. return this._leftNode.splitNode(contentSize);
  68635. }
  68636. else {
  68637. this._contentSize = cs.clone();
  68638. this._initialSize = cs.clone();
  68639. if (cs.width !== this._size.width) {
  68640. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  68641. }
  68642. if (cs.height !== this._size.height) {
  68643. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  68644. }
  68645. return this;
  68646. }
  68647. };
  68648. PackedRect.prototype.attemptDefrag = function () {
  68649. if (!this.isUsed && this.isRecursiveFree) {
  68650. this.clearNode();
  68651. if (this._parent) {
  68652. this._parent.attemptDefrag();
  68653. }
  68654. }
  68655. };
  68656. PackedRect.prototype.clearNode = function () {
  68657. this._initialSize = null;
  68658. this._rightNode = null;
  68659. this._bottomNode = null;
  68660. };
  68661. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  68662. get: function () {
  68663. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  68664. },
  68665. enumerable: true,
  68666. configurable: true
  68667. });
  68668. PackedRect.prototype.evalFreeSize = function (size) {
  68669. var levelSize = 0;
  68670. if (!this.isUsed) {
  68671. var margin = this._root._margin;
  68672. var is = this._initialSize;
  68673. if (is) {
  68674. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  68675. }
  68676. else {
  68677. var size_1 = this._size;
  68678. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  68679. }
  68680. }
  68681. if (this._rightNode) {
  68682. levelSize += this._rightNode.evalFreeSize(0);
  68683. }
  68684. if (this._bottomNode) {
  68685. levelSize += this._bottomNode.evalFreeSize(0);
  68686. }
  68687. return levelSize + size;
  68688. };
  68689. PackedRect.TpsSize = BABYLON.Size.Zero();
  68690. return PackedRect;
  68691. }());
  68692. BABYLON.PackedRect = PackedRect;
  68693. /**
  68694. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  68695. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  68696. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  68697. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  68698. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  68699. */
  68700. var RectPackingMap = (function (_super) {
  68701. __extends(RectPackingMap, _super);
  68702. /**
  68703. * Create an instance of the object with a dimension using the given size
  68704. * @param size The dimension of the rectangle that will contain all the sub ones.
  68705. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  68706. */
  68707. function RectPackingMap(size, margin) {
  68708. if (margin === void 0) { margin = 0; }
  68709. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  68710. _this._margin = margin;
  68711. _this._root = _this;
  68712. return _this;
  68713. }
  68714. /**
  68715. * Add a rectangle, finding the best location to store it into the map
  68716. * @param size the dimension of the rectangle to store
  68717. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  68718. */
  68719. RectPackingMap.prototype.addRect = function (size) {
  68720. var node = this.findAndSplitNode(size);
  68721. return node;
  68722. };
  68723. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  68724. /**
  68725. * Return the current space free normalized between [0;1]
  68726. * @returns {}
  68727. */
  68728. get: function () {
  68729. var freeSize = 0;
  68730. freeSize = this.evalFreeSize(freeSize);
  68731. return freeSize / (this._size.width * this._size.height);
  68732. },
  68733. enumerable: true,
  68734. configurable: true
  68735. });
  68736. return RectPackingMap;
  68737. }(PackedRect));
  68738. BABYLON.RectPackingMap = RectPackingMap;
  68739. })(BABYLON || (BABYLON = {}));
  68740. //# sourceMappingURL=babylon.rectPackingMap.js.map
  68741. var BABYLON;
  68742. (function (BABYLON) {
  68743. /**
  68744. * This groups together the common properties used for image processing either in direct forward pass
  68745. * or through post processing effect depending on the use of the image processing pipeline in your scene
  68746. * or not.
  68747. */
  68748. var ImageProcessingConfiguration = (function () {
  68749. function ImageProcessingConfiguration() {
  68750. /**
  68751. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  68752. */
  68753. this.colorCurves = new BABYLON.ColorCurves();
  68754. this._colorCurvesEnabled = false;
  68755. this._colorGradingEnabled = false;
  68756. this._colorGradingWithGreenDepth = false;
  68757. this._colorGradingBGR = false;
  68758. this._exposure = 1.0;
  68759. this._toneMappingEnabled = false;
  68760. this._contrast = 1.0;
  68761. /**
  68762. * Vignette stretch size.
  68763. */
  68764. this.vignetteStretch = 0;
  68765. /**
  68766. * Vignette centre X Offset.
  68767. */
  68768. this.vignetteCentreX = 0;
  68769. /**
  68770. * Vignette centre Y Offset.
  68771. */
  68772. this.vignetteCentreY = 0;
  68773. /**
  68774. * Vignette weight or intensity of the vignette effect.
  68775. */
  68776. this.vignetteWeight = 1.5;
  68777. /**
  68778. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68779. * if vignetteEnabled is set to true.
  68780. */
  68781. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  68782. /**
  68783. * Camera field of view used by the Vignette effect.
  68784. */
  68785. this.vignetteCameraFov = 0.5;
  68786. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  68787. this._vignetteEnabled = false;
  68788. this._applyByPostProcess = false;
  68789. /**
  68790. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  68791. * @type {BABYLON.Observable}
  68792. */
  68793. this.onUpdateParameters = new BABYLON.Observable();
  68794. }
  68795. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  68796. /**
  68797. * Gets wether the color curves effect is enabled.
  68798. */
  68799. get: function () {
  68800. return this._colorCurvesEnabled;
  68801. },
  68802. /**
  68803. * Sets wether the color curves effect is enabled.
  68804. */
  68805. set: function (value) {
  68806. if (this._colorCurvesEnabled === value) {
  68807. return;
  68808. }
  68809. this._colorCurvesEnabled = value;
  68810. this._updateParameters();
  68811. },
  68812. enumerable: true,
  68813. configurable: true
  68814. });
  68815. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  68816. /**
  68817. * Gets wether the color grading effect is enabled.
  68818. */
  68819. get: function () {
  68820. return this._colorGradingEnabled;
  68821. },
  68822. /**
  68823. * Sets wether the color grading effect is enabled.
  68824. */
  68825. set: function (value) {
  68826. if (this._colorGradingEnabled === value) {
  68827. return;
  68828. }
  68829. this._colorGradingEnabled = value;
  68830. this._updateParameters();
  68831. },
  68832. enumerable: true,
  68833. configurable: true
  68834. });
  68835. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  68836. /**
  68837. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  68838. */
  68839. get: function () {
  68840. return this._colorGradingWithGreenDepth;
  68841. },
  68842. /**
  68843. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  68844. */
  68845. set: function (value) {
  68846. if (this._colorGradingWithGreenDepth === value) {
  68847. return;
  68848. }
  68849. this._colorGradingWithGreenDepth = value;
  68850. this._updateParameters();
  68851. },
  68852. enumerable: true,
  68853. configurable: true
  68854. });
  68855. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  68856. /**
  68857. * Gets wether the color grading texture contains BGR values.
  68858. */
  68859. get: function () {
  68860. return this._colorGradingBGR;
  68861. },
  68862. /**
  68863. * Sets wether the color grading texture contains BGR values.
  68864. */
  68865. set: function (value) {
  68866. if (this._colorGradingBGR === value) {
  68867. return;
  68868. }
  68869. this._colorGradingBGR = value;
  68870. this._updateParameters();
  68871. },
  68872. enumerable: true,
  68873. configurable: true
  68874. });
  68875. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  68876. /**
  68877. * Gets the Exposure used in the effect.
  68878. */
  68879. get: function () {
  68880. return this._exposure;
  68881. },
  68882. /**
  68883. * Sets the Exposure used in the effect.
  68884. */
  68885. set: function (value) {
  68886. if (this._exposure === value) {
  68887. return;
  68888. }
  68889. this._exposure = value;
  68890. this._updateParameters();
  68891. },
  68892. enumerable: true,
  68893. configurable: true
  68894. });
  68895. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  68896. /**
  68897. * Gets wether the tone mapping effect is enabled.
  68898. */
  68899. get: function () {
  68900. return this._toneMappingEnabled;
  68901. },
  68902. /**
  68903. * Sets wether the tone mapping effect is enabled.
  68904. */
  68905. set: function (value) {
  68906. if (this._toneMappingEnabled === value) {
  68907. return;
  68908. }
  68909. this._toneMappingEnabled = value;
  68910. this._updateParameters();
  68911. },
  68912. enumerable: true,
  68913. configurable: true
  68914. });
  68915. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  68916. /**
  68917. * Gets the contrast used in the effect.
  68918. */
  68919. get: function () {
  68920. return this._contrast;
  68921. },
  68922. /**
  68923. * Sets the contrast used in the effect.
  68924. */
  68925. set: function (value) {
  68926. if (this._contrast === value) {
  68927. return;
  68928. }
  68929. this._contrast = value;
  68930. this._updateParameters();
  68931. },
  68932. enumerable: true,
  68933. configurable: true
  68934. });
  68935. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  68936. /**
  68937. * Gets the vignette blend mode allowing different kind of effect.
  68938. */
  68939. get: function () {
  68940. return this._vignetteBlendMode;
  68941. },
  68942. /**
  68943. * Sets the vignette blend mode allowing different kind of effect.
  68944. */
  68945. set: function (value) {
  68946. if (this._vignetteBlendMode === value) {
  68947. return;
  68948. }
  68949. this._vignetteBlendMode = value;
  68950. this._updateParameters();
  68951. },
  68952. enumerable: true,
  68953. configurable: true
  68954. });
  68955. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  68956. /**
  68957. * Gets wether the vignette effect is enabled.
  68958. */
  68959. get: function () {
  68960. return this._vignetteEnabled;
  68961. },
  68962. /**
  68963. * Sets wether the vignette effect is enabled.
  68964. */
  68965. set: function (value) {
  68966. if (this._vignetteEnabled === value) {
  68967. return;
  68968. }
  68969. this._vignetteEnabled = value;
  68970. this._updateParameters();
  68971. },
  68972. enumerable: true,
  68973. configurable: true
  68974. });
  68975. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  68976. /**
  68977. * Gets wether the image processing is applied through a post process or not.
  68978. */
  68979. get: function () {
  68980. return this._applyByPostProcess;
  68981. },
  68982. /**
  68983. * Sets wether the image processing is applied through a post process or not.
  68984. */
  68985. set: function (value) {
  68986. if (this._applyByPostProcess === value) {
  68987. return;
  68988. }
  68989. this._applyByPostProcess = value;
  68990. this._updateParameters();
  68991. },
  68992. enumerable: true,
  68993. configurable: true
  68994. });
  68995. /**
  68996. * Method called each time the image processing information changes requires to recompile the effect.
  68997. */
  68998. ImageProcessingConfiguration.prototype._updateParameters = function () {
  68999. this.onUpdateParameters.notifyObservers(this);
  69000. };
  69001. ImageProcessingConfiguration.prototype.getClassName = function () {
  69002. return "ImageProcessingConfiguration";
  69003. };
  69004. /**
  69005. * Prepare the list of uniforms associated with the Image Processing effects.
  69006. * @param uniformsList The list of uniforms used in the effect
  69007. * @param defines the list of defines currently in use
  69008. */
  69009. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  69010. if (defines.EXPOSURE) {
  69011. uniforms.push("exposureLinear");
  69012. }
  69013. if (defines.CONTRAST) {
  69014. uniforms.push("contrast");
  69015. }
  69016. if (defines.COLORGRADING) {
  69017. uniforms.push("colorTransformSettings");
  69018. }
  69019. if (defines.VIGNETTE) {
  69020. uniforms.push("vInverseScreenSize");
  69021. uniforms.push("vignetteSettings1");
  69022. uniforms.push("vignetteSettings2");
  69023. }
  69024. if (defines.COLORCURVES) {
  69025. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  69026. }
  69027. };
  69028. /**
  69029. * Prepare the list of samplers associated with the Image Processing effects.
  69030. * @param uniformsList The list of uniforms used in the effect
  69031. * @param defines the list of defines currently in use
  69032. */
  69033. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  69034. if (defines.COLORGRADING) {
  69035. samplersList.push("txColorTransform");
  69036. }
  69037. };
  69038. /**
  69039. * Prepare the list of defines associated to the shader.
  69040. * @param defines the list of defines to complete
  69041. */
  69042. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  69043. defines.VIGNETTE = this.vignetteEnabled;
  69044. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  69045. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  69046. defines.TONEMAPPING = this.toneMappingEnabled;
  69047. defines.CONTRAST = (this.contrast !== 1.0);
  69048. defines.EXPOSURE = (this.exposure !== 1.0);
  69049. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  69050. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  69051. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  69052. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  69053. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  69054. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  69055. };
  69056. /**
  69057. * Returns true if all the image processing information are ready.
  69058. */
  69059. ImageProcessingConfiguration.prototype.isReady = function () {
  69060. // Color Grading texure can not be none blocking.
  69061. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  69062. };
  69063. /**
  69064. * Binds the image processing to the shader.
  69065. * @param effect The effect to bind to
  69066. */
  69067. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  69068. if (aspectRatio === void 0) { aspectRatio = 1; }
  69069. // Color Curves
  69070. if (this._colorCurvesEnabled) {
  69071. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  69072. }
  69073. // Vignette
  69074. if (this._vignetteEnabled) {
  69075. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  69076. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  69077. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  69078. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  69079. var vignetteScaleX = vignetteScaleY * aspectRatio;
  69080. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  69081. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  69082. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  69083. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  69084. var vignettePower = -2.0 * this.vignetteWeight;
  69085. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  69086. }
  69087. // Exposure
  69088. effect.setFloat("exposureLinear", this.exposure);
  69089. // Contrast
  69090. effect.setFloat("contrast", this.contrast);
  69091. // Color transform settings
  69092. if (this.colorGradingTexture) {
  69093. effect.setTexture("txColorTransform", this.colorGradingTexture);
  69094. var textureSize = this.colorGradingTexture.getSize().height;
  69095. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  69096. 0.5 / textureSize, // textureOffset
  69097. textureSize, // textureSize
  69098. this.colorGradingTexture.level // weight
  69099. );
  69100. }
  69101. };
  69102. /**
  69103. * Clones the current image processing instance.
  69104. * @return The cloned image processing
  69105. */
  69106. ImageProcessingConfiguration.prototype.clone = function () {
  69107. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  69108. };
  69109. /**
  69110. * Serializes the current image processing instance to a json representation.
  69111. * @return a JSON representation
  69112. */
  69113. ImageProcessingConfiguration.prototype.serialize = function () {
  69114. return BABYLON.SerializationHelper.Serialize(this);
  69115. };
  69116. /**
  69117. * Parses the image processing from a json representation.
  69118. * @param source the JSON source to parse
  69119. * @return The parsed image processing
  69120. */
  69121. ImageProcessingConfiguration.Parse = function (source) {
  69122. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  69123. };
  69124. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  69125. /**
  69126. * Used to apply the vignette as a mix with the pixel color.
  69127. */
  69128. get: function () {
  69129. return this._VIGNETTEMODE_MULTIPLY;
  69130. },
  69131. enumerable: true,
  69132. configurable: true
  69133. });
  69134. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  69135. /**
  69136. * Used to apply the vignette as a replacement of the pixel color.
  69137. */
  69138. get: function () {
  69139. return this._VIGNETTEMODE_OPAQUE;
  69140. },
  69141. enumerable: true,
  69142. configurable: true
  69143. });
  69144. // Static constants associated to the image processing.
  69145. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  69146. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  69147. __decorate([
  69148. BABYLON.serializeAsColorCurves()
  69149. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  69150. __decorate([
  69151. BABYLON.serialize()
  69152. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  69153. __decorate([
  69154. BABYLON.serializeAsTexture()
  69155. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  69156. __decorate([
  69157. BABYLON.serialize()
  69158. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  69159. __decorate([
  69160. BABYLON.serialize()
  69161. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  69162. __decorate([
  69163. BABYLON.serialize()
  69164. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  69165. __decorate([
  69166. BABYLON.serialize()
  69167. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  69168. __decorate([
  69169. BABYLON.serialize()
  69170. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  69171. __decorate([
  69172. BABYLON.serialize()
  69173. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  69174. __decorate([
  69175. BABYLON.serialize()
  69176. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  69177. __decorate([
  69178. BABYLON.serialize()
  69179. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  69180. __decorate([
  69181. BABYLON.serialize()
  69182. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  69183. __decorate([
  69184. BABYLON.serialize()
  69185. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  69186. __decorate([
  69187. BABYLON.serializeAsColor4()
  69188. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  69189. __decorate([
  69190. BABYLON.serialize()
  69191. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  69192. __decorate([
  69193. BABYLON.serialize()
  69194. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  69195. __decorate([
  69196. BABYLON.serialize()
  69197. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  69198. __decorate([
  69199. BABYLON.serialize()
  69200. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  69201. return ImageProcessingConfiguration;
  69202. }());
  69203. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  69204. })(BABYLON || (BABYLON = {}));
  69205. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  69206. var BABYLON;
  69207. (function (BABYLON) {
  69208. var serializedGeometries = [];
  69209. var serializeGeometry = function (geometry, serializationGeometries) {
  69210. if (serializedGeometries[geometry.id]) {
  69211. return;
  69212. }
  69213. if (geometry.doNotSerialize) {
  69214. return;
  69215. }
  69216. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  69217. serializationGeometries.boxes.push(geometry.serialize());
  69218. }
  69219. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  69220. serializationGeometries.spheres.push(geometry.serialize());
  69221. }
  69222. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  69223. serializationGeometries.cylinders.push(geometry.serialize());
  69224. }
  69225. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  69226. serializationGeometries.toruses.push(geometry.serialize());
  69227. }
  69228. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  69229. serializationGeometries.grounds.push(geometry.serialize());
  69230. }
  69231. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  69232. serializationGeometries.planes.push(geometry.serialize());
  69233. }
  69234. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  69235. serializationGeometries.torusKnots.push(geometry.serialize());
  69236. }
  69237. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  69238. throw new Error("Unknown primitive type");
  69239. }
  69240. else {
  69241. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  69242. }
  69243. serializedGeometries[geometry.id] = true;
  69244. };
  69245. var serializeMesh = function (mesh, serializationScene) {
  69246. var serializationObject = {};
  69247. // Geometry
  69248. var geometry = mesh._geometry;
  69249. if (geometry) {
  69250. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  69251. // 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
  69252. serializeGeometry(geometry, serializationScene.geometries);
  69253. }
  69254. }
  69255. // Custom
  69256. if (mesh.serialize) {
  69257. mesh.serialize(serializationObject);
  69258. }
  69259. return serializationObject;
  69260. };
  69261. var finalizeSingleMesh = function (mesh, serializationObject) {
  69262. //only works if the mesh is already loaded
  69263. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  69264. //serialize material
  69265. if (mesh.material) {
  69266. if (mesh.material instanceof BABYLON.StandardMaterial) {
  69267. serializationObject.materials = serializationObject.materials || [];
  69268. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  69269. serializationObject.materials.push(mesh.material.serialize());
  69270. }
  69271. }
  69272. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  69273. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  69274. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  69275. serializationObject.multiMaterials.push(mesh.material.serialize());
  69276. }
  69277. }
  69278. }
  69279. //serialize geometry
  69280. var geometry = mesh._geometry;
  69281. if (geometry) {
  69282. if (!serializationObject.geometries) {
  69283. serializationObject.geometries = {};
  69284. serializationObject.geometries.boxes = [];
  69285. serializationObject.geometries.spheres = [];
  69286. serializationObject.geometries.cylinders = [];
  69287. serializationObject.geometries.toruses = [];
  69288. serializationObject.geometries.grounds = [];
  69289. serializationObject.geometries.planes = [];
  69290. serializationObject.geometries.torusKnots = [];
  69291. serializationObject.geometries.vertexData = [];
  69292. }
  69293. serializeGeometry(geometry, serializationObject.geometries);
  69294. }
  69295. // Skeletons
  69296. if (mesh.skeleton) {
  69297. serializationObject.skeletons = serializationObject.skeletons || [];
  69298. serializationObject.skeletons.push(mesh.skeleton.serialize());
  69299. }
  69300. //serialize the actual mesh
  69301. serializationObject.meshes = serializationObject.meshes || [];
  69302. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  69303. }
  69304. };
  69305. var SceneSerializer = (function () {
  69306. function SceneSerializer() {
  69307. }
  69308. SceneSerializer.ClearCache = function () {
  69309. serializedGeometries = [];
  69310. };
  69311. SceneSerializer.Serialize = function (scene) {
  69312. var serializationObject = {};
  69313. SceneSerializer.ClearCache();
  69314. // Scene
  69315. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  69316. serializationObject.autoClear = scene.autoClear;
  69317. serializationObject.clearColor = scene.clearColor.asArray();
  69318. serializationObject.ambientColor = scene.ambientColor.asArray();
  69319. serializationObject.gravity = scene.gravity.asArray();
  69320. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  69321. serializationObject.workerCollisions = scene.workerCollisions;
  69322. // Fog
  69323. if (scene.fogMode && scene.fogMode !== 0) {
  69324. serializationObject.fogMode = scene.fogMode;
  69325. serializationObject.fogColor = scene.fogColor.asArray();
  69326. serializationObject.fogStart = scene.fogStart;
  69327. serializationObject.fogEnd = scene.fogEnd;
  69328. serializationObject.fogDensity = scene.fogDensity;
  69329. }
  69330. //Physics
  69331. if (scene.isPhysicsEnabled()) {
  69332. serializationObject.physicsEnabled = true;
  69333. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  69334. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  69335. }
  69336. // Metadata
  69337. if (scene.metadata) {
  69338. serializationObject.metadata = scene.metadata;
  69339. }
  69340. // Morph targets
  69341. serializationObject.morphTargetManagers = [];
  69342. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  69343. var abstractMesh = _a[_i];
  69344. var manager = abstractMesh.morphTargetManager;
  69345. if (manager) {
  69346. serializationObject.morphTargetManagers.push(manager.serialize());
  69347. }
  69348. }
  69349. // Lights
  69350. serializationObject.lights = [];
  69351. var index;
  69352. var light;
  69353. for (index = 0; index < scene.lights.length; index++) {
  69354. light = scene.lights[index];
  69355. if (!light.doNotSerialize) {
  69356. serializationObject.lights.push(light.serialize());
  69357. }
  69358. }
  69359. // Cameras
  69360. serializationObject.cameras = [];
  69361. for (index = 0; index < scene.cameras.length; index++) {
  69362. var camera = scene.cameras[index];
  69363. if (!camera.doNotSerialize) {
  69364. serializationObject.cameras.push(camera.serialize());
  69365. }
  69366. }
  69367. if (scene.activeCamera) {
  69368. serializationObject.activeCameraID = scene.activeCamera.id;
  69369. }
  69370. // Animations
  69371. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  69372. // Materials
  69373. serializationObject.materials = [];
  69374. serializationObject.multiMaterials = [];
  69375. var material;
  69376. for (index = 0; index < scene.materials.length; index++) {
  69377. material = scene.materials[index];
  69378. if (!material.doNotSerialize) {
  69379. serializationObject.materials.push(material.serialize());
  69380. }
  69381. }
  69382. // MultiMaterials
  69383. serializationObject.multiMaterials = [];
  69384. for (index = 0; index < scene.multiMaterials.length; index++) {
  69385. var multiMaterial = scene.multiMaterials[index];
  69386. serializationObject.multiMaterials.push(multiMaterial.serialize());
  69387. }
  69388. // Skeletons
  69389. serializationObject.skeletons = [];
  69390. for (index = 0; index < scene.skeletons.length; index++) {
  69391. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  69392. }
  69393. // Geometries
  69394. serializationObject.geometries = {};
  69395. serializationObject.geometries.boxes = [];
  69396. serializationObject.geometries.spheres = [];
  69397. serializationObject.geometries.cylinders = [];
  69398. serializationObject.geometries.toruses = [];
  69399. serializationObject.geometries.grounds = [];
  69400. serializationObject.geometries.planes = [];
  69401. serializationObject.geometries.torusKnots = [];
  69402. serializationObject.geometries.vertexData = [];
  69403. serializedGeometries = [];
  69404. var geometries = scene.getGeometries();
  69405. for (index = 0; index < geometries.length; index++) {
  69406. var geometry = geometries[index];
  69407. if (geometry.isReady()) {
  69408. serializeGeometry(geometry, serializationObject.geometries);
  69409. }
  69410. }
  69411. // Meshes
  69412. serializationObject.meshes = [];
  69413. for (index = 0; index < scene.meshes.length; index++) {
  69414. var abstractMesh = scene.meshes[index];
  69415. if (abstractMesh instanceof BABYLON.Mesh) {
  69416. var mesh = abstractMesh;
  69417. if (!mesh.doNotSerialize) {
  69418. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  69419. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  69420. }
  69421. }
  69422. }
  69423. }
  69424. // Particles Systems
  69425. serializationObject.particleSystems = [];
  69426. for (index = 0; index < scene.particleSystems.length; index++) {
  69427. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  69428. }
  69429. // Lens flares
  69430. serializationObject.lensFlareSystems = [];
  69431. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  69432. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  69433. }
  69434. // Shadows
  69435. serializationObject.shadowGenerators = [];
  69436. for (index = 0; index < scene.lights.length; index++) {
  69437. light = scene.lights[index];
  69438. var shadowGenerator = light.getShadowGenerator();
  69439. if (shadowGenerator) {
  69440. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  69441. }
  69442. }
  69443. // Action Manager
  69444. if (scene.actionManager) {
  69445. serializationObject.actions = scene.actionManager.serialize("scene");
  69446. }
  69447. // Audio
  69448. serializationObject.sounds = [];
  69449. for (index = 0; index < scene.soundTracks.length; index++) {
  69450. var soundtrack = scene.soundTracks[index];
  69451. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69452. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69453. }
  69454. }
  69455. return serializationObject;
  69456. };
  69457. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  69458. if (withParents === void 0) { withParents = false; }
  69459. if (withChildren === void 0) { withChildren = false; }
  69460. var serializationObject = {};
  69461. SceneSerializer.ClearCache();
  69462. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  69463. if (withParents || withChildren) {
  69464. //deliberate for loop! not for each, appended should be processed as well.
  69465. for (var i = 0; i < toSerialize.length; ++i) {
  69466. if (withChildren) {
  69467. toSerialize[i].getDescendants().forEach(function (node) {
  69468. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  69469. toSerialize.push(node);
  69470. }
  69471. });
  69472. }
  69473. //make sure the array doesn't contain the object already
  69474. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  69475. toSerialize.push(toSerialize[i].parent);
  69476. }
  69477. }
  69478. }
  69479. toSerialize.forEach(function (mesh) {
  69480. finalizeSingleMesh(mesh, serializationObject);
  69481. });
  69482. return serializationObject;
  69483. };
  69484. return SceneSerializer;
  69485. }());
  69486. BABYLON.SceneSerializer = SceneSerializer;
  69487. })(BABYLON || (BABYLON = {}));
  69488. //# sourceMappingURL=babylon.sceneSerializer.js.map
  69489. var BABYLON;
  69490. (function (BABYLON) {
  69491. var ReflectionProbe = (function () {
  69492. function ReflectionProbe(name, size, scene, generateMipMaps) {
  69493. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69494. var _this = this;
  69495. this.name = name;
  69496. this._viewMatrix = BABYLON.Matrix.Identity();
  69497. this._target = BABYLON.Vector3.Zero();
  69498. this._add = BABYLON.Vector3.Zero();
  69499. this.invertYAxis = false;
  69500. this.position = BABYLON.Vector3.Zero();
  69501. this._scene = scene;
  69502. this._scene.reflectionProbes.push(this);
  69503. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  69504. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  69505. switch (faceIndex) {
  69506. case 0:
  69507. _this._add.copyFromFloats(1, 0, 0);
  69508. break;
  69509. case 1:
  69510. _this._add.copyFromFloats(-1, 0, 0);
  69511. break;
  69512. case 2:
  69513. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  69514. break;
  69515. case 3:
  69516. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  69517. break;
  69518. case 4:
  69519. _this._add.copyFromFloats(0, 0, 1);
  69520. break;
  69521. case 5:
  69522. _this._add.copyFromFloats(0, 0, -1);
  69523. break;
  69524. }
  69525. if (_this._attachedMesh) {
  69526. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  69527. }
  69528. _this.position.addToRef(_this._add, _this._target);
  69529. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  69530. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  69531. });
  69532. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  69533. scene.updateTransformMatrix(true);
  69534. });
  69535. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69536. }
  69537. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  69538. get: function () {
  69539. return this._renderTargetTexture.samples;
  69540. },
  69541. set: function (value) {
  69542. this._renderTargetTexture.samples = value;
  69543. },
  69544. enumerable: true,
  69545. configurable: true
  69546. });
  69547. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  69548. get: function () {
  69549. return this._renderTargetTexture.refreshRate;
  69550. },
  69551. set: function (value) {
  69552. this._renderTargetTexture.refreshRate = value;
  69553. },
  69554. enumerable: true,
  69555. configurable: true
  69556. });
  69557. ReflectionProbe.prototype.getScene = function () {
  69558. return this._scene;
  69559. };
  69560. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  69561. get: function () {
  69562. return this._renderTargetTexture;
  69563. },
  69564. enumerable: true,
  69565. configurable: true
  69566. });
  69567. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  69568. get: function () {
  69569. return this._renderTargetTexture.renderList;
  69570. },
  69571. enumerable: true,
  69572. configurable: true
  69573. });
  69574. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  69575. this._attachedMesh = mesh;
  69576. };
  69577. /**
  69578. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  69579. *
  69580. * @param renderingGroupId The rendering group id corresponding to its index
  69581. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  69582. */
  69583. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  69584. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  69585. };
  69586. ReflectionProbe.prototype.dispose = function () {
  69587. var index = this._scene.reflectionProbes.indexOf(this);
  69588. if (index !== -1) {
  69589. // Remove from the scene if found
  69590. this._scene.reflectionProbes.splice(index, 1);
  69591. }
  69592. if (this._renderTargetTexture) {
  69593. this._renderTargetTexture.dispose();
  69594. this._renderTargetTexture = null;
  69595. }
  69596. };
  69597. return ReflectionProbe;
  69598. }());
  69599. BABYLON.ReflectionProbe = ReflectionProbe;
  69600. })(BABYLON || (BABYLON = {}));
  69601. //# sourceMappingURL=babylon.reflectionProbe.js.map
  69602. var BABYLON;
  69603. (function (BABYLON) {
  69604. var Layer = (function () {
  69605. function Layer(name, imgUrl, scene, isBackground, color) {
  69606. this.name = name;
  69607. this.scale = new BABYLON.Vector2(1, 1);
  69608. this.offset = new BABYLON.Vector2(0, 0);
  69609. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  69610. this.layerMask = 0x0FFFFFFF;
  69611. this._vertexBuffers = {};
  69612. // Events
  69613. /**
  69614. * An event triggered when the layer is disposed.
  69615. * @type {BABYLON.Observable}
  69616. */
  69617. this.onDisposeObservable = new BABYLON.Observable();
  69618. /**
  69619. * An event triggered before rendering the scene
  69620. * @type {BABYLON.Observable}
  69621. */
  69622. this.onBeforeRenderObservable = new BABYLON.Observable();
  69623. /**
  69624. * An event triggered after rendering the scene
  69625. * @type {BABYLON.Observable}
  69626. */
  69627. this.onAfterRenderObservable = new BABYLON.Observable();
  69628. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  69629. this.isBackground = isBackground === undefined ? true : isBackground;
  69630. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  69631. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69632. this._scene.layers.push(this);
  69633. var engine = this._scene.getEngine();
  69634. // VBO
  69635. var vertices = [];
  69636. vertices.push(1, 1);
  69637. vertices.push(-1, 1);
  69638. vertices.push(-1, -1);
  69639. vertices.push(1, -1);
  69640. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69641. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  69642. this._createIndexBuffer();
  69643. // Effects
  69644. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  69645. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  69646. }
  69647. Object.defineProperty(Layer.prototype, "onDispose", {
  69648. set: function (callback) {
  69649. if (this._onDisposeObserver) {
  69650. this.onDisposeObservable.remove(this._onDisposeObserver);
  69651. }
  69652. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  69653. },
  69654. enumerable: true,
  69655. configurable: true
  69656. });
  69657. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  69658. set: function (callback) {
  69659. if (this._onBeforeRenderObserver) {
  69660. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69661. }
  69662. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69663. },
  69664. enumerable: true,
  69665. configurable: true
  69666. });
  69667. Object.defineProperty(Layer.prototype, "onAfterRender", {
  69668. set: function (callback) {
  69669. if (this._onAfterRenderObserver) {
  69670. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69671. }
  69672. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69673. },
  69674. enumerable: true,
  69675. configurable: true
  69676. });
  69677. Layer.prototype._createIndexBuffer = function () {
  69678. var engine = this._scene.getEngine();
  69679. // Indices
  69680. var indices = [];
  69681. indices.push(0);
  69682. indices.push(1);
  69683. indices.push(2);
  69684. indices.push(0);
  69685. indices.push(2);
  69686. indices.push(3);
  69687. this._indexBuffer = engine.createIndexBuffer(indices);
  69688. };
  69689. Layer.prototype._rebuild = function () {
  69690. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  69691. this._createIndexBuffer();
  69692. };
  69693. Layer.prototype.render = function () {
  69694. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  69695. // Check
  69696. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  69697. return;
  69698. var engine = this._scene.getEngine();
  69699. this.onBeforeRenderObservable.notifyObservers(this);
  69700. // Render
  69701. engine.enableEffect(currentEffect);
  69702. engine.setState(false);
  69703. // Texture
  69704. currentEffect.setTexture("textureSampler", this.texture);
  69705. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  69706. // Color
  69707. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  69708. // Scale / offset
  69709. currentEffect.setVector2("offset", this.offset);
  69710. currentEffect.setVector2("scale", this.scale);
  69711. // VBOs
  69712. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69713. // Draw order
  69714. if (!this.alphaTest) {
  69715. engine.setAlphaMode(this.alphaBlendingMode);
  69716. engine.draw(true, 0, 6);
  69717. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69718. }
  69719. else {
  69720. engine.draw(true, 0, 6);
  69721. }
  69722. this.onAfterRenderObservable.notifyObservers(this);
  69723. };
  69724. Layer.prototype.dispose = function () {
  69725. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69726. if (vertexBuffer) {
  69727. vertexBuffer.dispose();
  69728. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69729. }
  69730. if (this._indexBuffer) {
  69731. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69732. this._indexBuffer = null;
  69733. }
  69734. if (this.texture) {
  69735. this.texture.dispose();
  69736. this.texture = null;
  69737. }
  69738. // Remove from scene
  69739. var index = this._scene.layers.indexOf(this);
  69740. this._scene.layers.splice(index, 1);
  69741. // Callback
  69742. this.onDisposeObservable.notifyObservers(this);
  69743. this.onDisposeObservable.clear();
  69744. this.onAfterRenderObservable.clear();
  69745. this.onBeforeRenderObservable.clear();
  69746. };
  69747. return Layer;
  69748. }());
  69749. BABYLON.Layer = Layer;
  69750. })(BABYLON || (BABYLON = {}));
  69751. //# sourceMappingURL=babylon.layer.js.map
  69752. var BABYLON;
  69753. (function (BABYLON) {
  69754. var TextureTools = (function () {
  69755. function TextureTools() {
  69756. }
  69757. /**
  69758. * Uses the GPU to create a copy texture rescaled at a given size
  69759. * @param texture Texture to copy from
  69760. * @param width Desired width
  69761. * @param height Desired height
  69762. * @return Generated texture
  69763. */
  69764. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  69765. if (useBilinearMode === void 0) { useBilinearMode = true; }
  69766. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  69767. var scene = texture.getScene();
  69768. var engine = scene.getEngine();
  69769. rtt.wrapU = texture.wrapU;
  69770. rtt.wrapV = texture.wrapV;
  69771. rtt.uOffset = texture.uOffset;
  69772. rtt.vOffset = texture.vOffset;
  69773. rtt.uScale = texture.uScale;
  69774. rtt.vScale = texture.vScale;
  69775. rtt.uAng = texture.uAng;
  69776. rtt.vAng = texture.vAng;
  69777. rtt.wAng = texture.wAng;
  69778. rtt.coordinatesIndex = texture.coordinatesIndex;
  69779. rtt.level = texture.level;
  69780. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  69781. rtt._texture.isReady = false;
  69782. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69783. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69784. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69785. passPostProcess.getEffect().executeWhenCompiled(function () {
  69786. passPostProcess.onApply = function (effect) {
  69787. effect.setTexture("textureSampler", texture);
  69788. };
  69789. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  69790. engine.unBindFramebuffer(rtt.getInternalTexture());
  69791. rtt.disposeFramebufferObjects();
  69792. passPostProcess.dispose();
  69793. rtt._texture.isReady = true;
  69794. });
  69795. return rtt;
  69796. };
  69797. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  69798. if (!scene._environmentBRDFTexture) {
  69799. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69800. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69801. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69802. scene._environmentBRDFTexture = texture;
  69803. }
  69804. return scene._environmentBRDFTexture;
  69805. };
  69806. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  69807. return TextureTools;
  69808. }());
  69809. BABYLON.TextureTools = TextureTools;
  69810. })(BABYLON || (BABYLON = {}));
  69811. //# sourceMappingURL=babylon.textureTools.js.map
  69812. var BABYLON;
  69813. (function (BABYLON) {
  69814. var FramingBehavior = (function () {
  69815. function FramingBehavior() {
  69816. this._mode = FramingBehavior.FitFrustumSidesMode;
  69817. this._radiusScale = 1.0;
  69818. this._positionScale = 0.5;
  69819. this._defaultElevation = 0.3;
  69820. this._elevationReturnTime = 1500;
  69821. this._elevationReturnWaitTime = 1000;
  69822. this._zoomStopsAnimation = false;
  69823. this._framingTime = 1500;
  69824. this._isPointerDown = false;
  69825. this._lastFrameTime = null;
  69826. this._lastInteractionTime = -Infinity;
  69827. // Framing control
  69828. this._animatables = new Array();
  69829. this._betaIsAnimating = false;
  69830. this._lastFrameRadius = 0;
  69831. }
  69832. Object.defineProperty(FramingBehavior.prototype, "name", {
  69833. get: function () {
  69834. return "Framing";
  69835. },
  69836. enumerable: true,
  69837. configurable: true
  69838. });
  69839. Object.defineProperty(FramingBehavior.prototype, "mode", {
  69840. /**
  69841. * Gets current mode used by the behavior.
  69842. */
  69843. get: function () {
  69844. return this._mode;
  69845. },
  69846. /**
  69847. * Sets the current mode used by the behavior
  69848. */
  69849. set: function (mode) {
  69850. this._mode = mode;
  69851. },
  69852. enumerable: true,
  69853. configurable: true
  69854. });
  69855. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  69856. /**
  69857. * Gets the scale applied to the radius
  69858. */
  69859. get: function () {
  69860. return this._radiusScale;
  69861. },
  69862. /**
  69863. * Sets the scale applied to the radius (1 by default)
  69864. */
  69865. set: function (radius) {
  69866. this._radiusScale = radius;
  69867. },
  69868. enumerable: true,
  69869. configurable: true
  69870. });
  69871. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  69872. /**
  69873. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  69874. */
  69875. get: function () {
  69876. return this._positionScale;
  69877. },
  69878. /**
  69879. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  69880. */
  69881. set: function (scale) {
  69882. this._positionScale = scale;
  69883. },
  69884. enumerable: true,
  69885. configurable: true
  69886. });
  69887. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  69888. /**
  69889. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  69890. * behaviour is triggered, in radians.
  69891. */
  69892. get: function () {
  69893. return this._defaultElevation;
  69894. },
  69895. /**
  69896. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  69897. * behaviour is triggered, in radians.
  69898. */
  69899. set: function (elevation) {
  69900. this._defaultElevation = elevation;
  69901. },
  69902. enumerable: true,
  69903. configurable: true
  69904. });
  69905. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  69906. /**
  69907. * Gets the time (in milliseconds) taken to return to the default beta position.
  69908. * Negative value indicates camera should not return to default.
  69909. */
  69910. get: function () {
  69911. return this._elevationReturnTime;
  69912. },
  69913. /**
  69914. * Sets the time (in milliseconds) taken to return to the default beta position.
  69915. * Negative value indicates camera should not return to default.
  69916. */
  69917. set: function (speed) {
  69918. this._elevationReturnTime = speed;
  69919. },
  69920. enumerable: true,
  69921. configurable: true
  69922. });
  69923. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  69924. /**
  69925. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  69926. */
  69927. get: function () {
  69928. return this._elevationReturnWaitTime;
  69929. },
  69930. /**
  69931. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  69932. */
  69933. set: function (time) {
  69934. this._elevationReturnWaitTime = time;
  69935. },
  69936. enumerable: true,
  69937. configurable: true
  69938. });
  69939. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  69940. /**
  69941. * Gets the flag that indicates if user zooming should stop animation.
  69942. */
  69943. get: function () {
  69944. return this._zoomStopsAnimation;
  69945. },
  69946. /**
  69947. * Sets the flag that indicates if user zooming should stop animation.
  69948. */
  69949. set: function (flag) {
  69950. this._zoomStopsAnimation = flag;
  69951. },
  69952. enumerable: true,
  69953. configurable: true
  69954. });
  69955. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  69956. /**
  69957. * Gets the transition time when framing the mesh, in milliseconds
  69958. */
  69959. get: function () {
  69960. return this._framingTime;
  69961. },
  69962. /**
  69963. * Sets the transition time when framing the mesh, in milliseconds
  69964. */
  69965. set: function (time) {
  69966. this._framingTime = time;
  69967. },
  69968. enumerable: true,
  69969. configurable: true
  69970. });
  69971. FramingBehavior.prototype.attach = function (camera) {
  69972. var _this = this;
  69973. this._attachedCamera = camera;
  69974. var scene = this._attachedCamera.getScene();
  69975. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  69976. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  69977. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69978. _this._isPointerDown = true;
  69979. return;
  69980. }
  69981. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  69982. _this._isPointerDown = false;
  69983. }
  69984. });
  69985. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  69986. if (mesh) {
  69987. _this.zoomOnMesh(mesh);
  69988. }
  69989. });
  69990. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  69991. // Stop the animation if there is user interaction and the animation should stop for this interaction
  69992. _this._applyUserInteraction();
  69993. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  69994. // back to the default position after a given timeout
  69995. _this._maintainCameraAboveGround();
  69996. });
  69997. };
  69998. FramingBehavior.prototype.detach = function () {
  69999. var scene = this._attachedCamera.getScene();
  70000. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  70001. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70002. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70003. this._attachedCamera = null;
  70004. };
  70005. /**
  70006. * Targets the given mesh and updates zoom level accordingly.
  70007. * @param mesh The mesh to target.
  70008. * @param radius Optional. If a cached radius position already exists, overrides default.
  70009. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  70010. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  70011. */
  70012. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  70013. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  70014. mesh.computeWorldMatrix(true);
  70015. var boundingBox = mesh.getBoundingInfo().boundingBox;
  70016. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  70017. };
  70018. /**
  70019. * Targets the given mesh and updates zoom level accordingly.
  70020. * @param mesh The mesh to target.
  70021. * @param radius Optional. If a cached radius position already exists, overrides default.
  70022. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  70023. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  70024. */
  70025. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  70026. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  70027. var zoomTarget;
  70028. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  70029. var bottom = minimumWorld.y;
  70030. var top = maximumWorld.y;
  70031. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  70032. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  70033. if (focusOnOriginXZ) {
  70034. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  70035. }
  70036. else {
  70037. var centerWorld = minimumWorld.add(radiusWorld);
  70038. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  70039. }
  70040. if (!this._vectorTransition) {
  70041. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  70042. }
  70043. this._betaIsAnimating = true;
  70044. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  70045. // sets the radius and lower radius bounds
  70046. // Small delta ensures camera is not always at lower zoom limit.
  70047. var delta = 0.1;
  70048. var radius = 0;
  70049. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  70050. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70051. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  70052. radius = position;
  70053. }
  70054. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70055. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70056. if (this._attachedCamera.lowerRadiusLimit === null) {
  70057. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  70058. }
  70059. }
  70060. // transition to new radius
  70061. if (!this._radiusTransition) {
  70062. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70063. }
  70064. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  70065. };
  70066. /**
  70067. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  70068. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  70069. * frustum width.
  70070. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  70071. * to fully enclose the mesh in the viewing frustum.
  70072. */
  70073. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  70074. var size = maximumWorld.subtract(minimumWorld);
  70075. var boxVectorGlobalDiagonal = size.length();
  70076. var frustumSlope = this._getFrustumSlope();
  70077. // Formula for setting distance
  70078. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  70079. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  70080. // Horizon distance
  70081. var radius = radiusWithoutFraming * this._radiusScale;
  70082. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  70083. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  70084. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  70085. var camera = this._attachedCamera;
  70086. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70087. // Don't exceed the requested limit
  70088. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  70089. }
  70090. // Don't exceed the upper radius limit
  70091. if (camera.upperRadiusLimit) {
  70092. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  70093. }
  70094. return distance;
  70095. };
  70096. /**
  70097. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  70098. * is automatically returned to its default position (expected to be above ground plane).
  70099. */
  70100. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  70101. var _this = this;
  70102. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  70103. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  70104. var limitBeta = Math.PI * 0.5;
  70105. // Bring the camera back up if below the ground plane
  70106. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  70107. this._betaIsAnimating = true;
  70108. //Transition to new position
  70109. this.stopAllAnimations();
  70110. if (!this._betaTransition) {
  70111. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70112. }
  70113. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  70114. _this._clearAnimationLocks();
  70115. _this.stopAllAnimations();
  70116. }));
  70117. }
  70118. };
  70119. /**
  70120. * Returns the frustum slope based on the canvas ratio and camera FOV
  70121. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  70122. */
  70123. FramingBehavior.prototype._getFrustumSlope = function () {
  70124. // Calculate the viewport ratio
  70125. // Aspect Ratio is Height/Width.
  70126. var camera = this._attachedCamera;
  70127. var engine = camera.getScene().getEngine();
  70128. var aspectRatio = engine.getAspectRatio(camera);
  70129. // Camera FOV is the vertical field of view (top-bottom) in radians.
  70130. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  70131. var frustumSlopeY = Math.tan(camera.fov / 2);
  70132. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  70133. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  70134. // along the forward vector.
  70135. var frustumSlopeX = frustumSlopeY * aspectRatio;
  70136. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  70137. };
  70138. /**
  70139. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  70140. */
  70141. FramingBehavior.prototype._clearAnimationLocks = function () {
  70142. this._betaIsAnimating = false;
  70143. };
  70144. /**
  70145. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  70146. */
  70147. FramingBehavior.prototype._applyUserInteraction = function () {
  70148. if (this.isUserIsMoving) {
  70149. this._lastInteractionTime = BABYLON.Tools.Now;
  70150. this.stopAllAnimations();
  70151. this._clearAnimationLocks();
  70152. }
  70153. };
  70154. /**
  70155. * Stops and removes all animations that have been applied to the camera
  70156. */
  70157. FramingBehavior.prototype.stopAllAnimations = function () {
  70158. this._attachedCamera.animations = [];
  70159. while (this._animatables.length) {
  70160. if (this._animatables[0]) {
  70161. this._animatables[0].onAnimationEnd = null;
  70162. this._animatables[0].stop();
  70163. }
  70164. this._animatables.shift();
  70165. }
  70166. };
  70167. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  70168. /**
  70169. * Gets a value indicating if the user is moving the camera
  70170. */
  70171. get: function () {
  70172. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  70173. this._attachedCamera.inertialBetaOffset !== 0 ||
  70174. this._attachedCamera.inertialRadiusOffset !== 0 ||
  70175. this._attachedCamera.inertialPanningX !== 0 ||
  70176. this._attachedCamera.inertialPanningY !== 0 ||
  70177. this._isPointerDown;
  70178. },
  70179. enumerable: true,
  70180. configurable: true
  70181. });
  70182. /**
  70183. * The easing function used by animations
  70184. */
  70185. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  70186. /**
  70187. * The easing mode used by animations
  70188. */
  70189. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  70190. // Statics
  70191. /**
  70192. * The camera can move all the way towards the mesh.
  70193. */
  70194. FramingBehavior.IgnoreBoundsSizeMode = 0;
  70195. /**
  70196. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  70197. */
  70198. FramingBehavior.FitFrustumSidesMode = 1;
  70199. return FramingBehavior;
  70200. }());
  70201. BABYLON.FramingBehavior = FramingBehavior;
  70202. })(BABYLON || (BABYLON = {}));
  70203. //# sourceMappingURL=babylon.framingBehavior.js.map
  70204. var BABYLON;
  70205. (function (BABYLON) {
  70206. /**
  70207. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  70208. */
  70209. var BouncingBehavior = (function () {
  70210. function BouncingBehavior() {
  70211. /**
  70212. * The duration of the animation, in milliseconds
  70213. */
  70214. this.transitionDuration = 450;
  70215. /**
  70216. * Length of the distance animated by the transition when lower radius is reached
  70217. */
  70218. this.lowerRadiusTransitionRange = 2;
  70219. /**
  70220. * Length of the distance animated by the transition when upper radius is reached
  70221. */
  70222. this.upperRadiusTransitionRange = -2;
  70223. this._autoTransitionRange = false;
  70224. // Animations
  70225. this._radiusIsAnimating = false;
  70226. this._radiusBounceTransition = null;
  70227. this._animatables = new Array();
  70228. }
  70229. Object.defineProperty(BouncingBehavior.prototype, "name", {
  70230. get: function () {
  70231. return "Bouncing";
  70232. },
  70233. enumerable: true,
  70234. configurable: true
  70235. });
  70236. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  70237. /**
  70238. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  70239. */
  70240. get: function () {
  70241. return this._autoTransitionRange;
  70242. },
  70243. /**
  70244. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  70245. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  70246. */
  70247. set: function (value) {
  70248. var _this = this;
  70249. if (this._autoTransitionRange === value) {
  70250. return;
  70251. }
  70252. this._autoTransitionRange = value;
  70253. var camera = this._attachedCamera;
  70254. if (value) {
  70255. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  70256. if (!mesh) {
  70257. return;
  70258. }
  70259. mesh.computeWorldMatrix(true);
  70260. var diagonal = mesh.getBoundingInfo().diagonalLength;
  70261. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  70262. _this.upperRadiusTransitionRange = diagonal * 0.05;
  70263. });
  70264. }
  70265. else if (this._onMeshTargetChangedObserver) {
  70266. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70267. }
  70268. },
  70269. enumerable: true,
  70270. configurable: true
  70271. });
  70272. BouncingBehavior.prototype.attach = function (camera) {
  70273. var _this = this;
  70274. this._attachedCamera = camera;
  70275. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70276. // Add the bounce animation to the lower radius limit
  70277. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  70278. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  70279. }
  70280. // Add the bounce animation to the upper radius limit
  70281. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  70282. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  70283. }
  70284. });
  70285. };
  70286. BouncingBehavior.prototype.detach = function () {
  70287. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70288. if (this._onMeshTargetChangedObserver) {
  70289. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70290. }
  70291. this._attachedCamera = null;
  70292. };
  70293. /**
  70294. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  70295. * @param radiusLimit The limit to check against.
  70296. * @return Bool to indicate if at limit.
  70297. */
  70298. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  70299. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  70300. return true;
  70301. }
  70302. return false;
  70303. };
  70304. /**
  70305. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  70306. * @param radiusDelta The delta by which to animate to. Can be negative.
  70307. */
  70308. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  70309. var _this = this;
  70310. if (!this._radiusBounceTransition) {
  70311. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  70312. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  70313. }
  70314. // Prevent zoom until bounce has completed
  70315. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  70316. this._attachedCamera.wheelPrecision = Infinity;
  70317. this._attachedCamera.inertialRadiusOffset = 0;
  70318. // Animate to the radius limit
  70319. this.stopAllAnimations();
  70320. this._radiusIsAnimating = true;
  70321. this._animatables.push(BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }));
  70322. };
  70323. /**
  70324. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  70325. */
  70326. BouncingBehavior.prototype._clearAnimationLocks = function () {
  70327. this._radiusIsAnimating = false;
  70328. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  70329. };
  70330. /**
  70331. * Stops and removes all animations that have been applied to the camera
  70332. */
  70333. BouncingBehavior.prototype.stopAllAnimations = function () {
  70334. this._attachedCamera.animations = [];
  70335. while (this._animatables.length) {
  70336. this._animatables[0].onAnimationEnd = null;
  70337. this._animatables[0].stop();
  70338. this._animatables.shift();
  70339. }
  70340. };
  70341. /**
  70342. * The easing function used by animations
  70343. */
  70344. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  70345. /**
  70346. * The easing mode used by animations
  70347. */
  70348. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  70349. return BouncingBehavior;
  70350. }());
  70351. BABYLON.BouncingBehavior = BouncingBehavior;
  70352. })(BABYLON || (BABYLON = {}));
  70353. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  70354. var BABYLON;
  70355. (function (BABYLON) {
  70356. var AutoRotationBehavior = (function () {
  70357. function AutoRotationBehavior() {
  70358. this._zoomStopsAnimation = false;
  70359. this._idleRotationSpeed = 0.05;
  70360. this._idleRotationWaitTime = 2000;
  70361. this._idleRotationSpinupTime = 2000;
  70362. this._isPointerDown = false;
  70363. this._lastFrameTime = null;
  70364. this._lastInteractionTime = -Infinity;
  70365. this._cameraRotationSpeed = 0;
  70366. this._lastFrameRadius = 0;
  70367. }
  70368. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  70369. get: function () {
  70370. return "AutoRotation";
  70371. },
  70372. enumerable: true,
  70373. configurable: true
  70374. });
  70375. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  70376. /**
  70377. * Gets the flag that indicates if user zooming should stop animation.
  70378. */
  70379. get: function () {
  70380. return this._zoomStopsAnimation;
  70381. },
  70382. /**
  70383. * Sets the flag that indicates if user zooming should stop animation.
  70384. */
  70385. set: function (flag) {
  70386. this._zoomStopsAnimation = flag;
  70387. },
  70388. enumerable: true,
  70389. configurable: true
  70390. });
  70391. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  70392. /**
  70393. * Gets the default speed at which the camera rotates around the model.
  70394. */
  70395. get: function () {
  70396. return this._idleRotationSpeed;
  70397. },
  70398. /**
  70399. * Sets the default speed at which the camera rotates around the model.
  70400. */
  70401. set: function (speed) {
  70402. this._idleRotationSpeed = speed;
  70403. },
  70404. enumerable: true,
  70405. configurable: true
  70406. });
  70407. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  70408. /**
  70409. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  70410. */
  70411. get: function () {
  70412. return this._idleRotationWaitTime;
  70413. },
  70414. /**
  70415. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  70416. */
  70417. set: function (time) {
  70418. this._idleRotationWaitTime = time;
  70419. },
  70420. enumerable: true,
  70421. configurable: true
  70422. });
  70423. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  70424. /**
  70425. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  70426. */
  70427. get: function () {
  70428. return this._idleRotationSpinupTime;
  70429. },
  70430. /**
  70431. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  70432. */
  70433. set: function (time) {
  70434. this._idleRotationSpinupTime = time;
  70435. },
  70436. enumerable: true,
  70437. configurable: true
  70438. });
  70439. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  70440. /**
  70441. * Gets a value indicating if the camera is currently rotating because of this behavior
  70442. */
  70443. get: function () {
  70444. return Math.abs(this._cameraRotationSpeed) > 0;
  70445. },
  70446. enumerable: true,
  70447. configurable: true
  70448. });
  70449. AutoRotationBehavior.prototype.attach = function (camera) {
  70450. var _this = this;
  70451. this._attachedCamera = camera;
  70452. var scene = this._attachedCamera.getScene();
  70453. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  70454. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70455. _this._isPointerDown = true;
  70456. return;
  70457. }
  70458. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  70459. _this._isPointerDown = false;
  70460. }
  70461. });
  70462. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70463. var now = BABYLON.Tools.Now;
  70464. var dt = 0;
  70465. if (_this._lastFrameTime != null) {
  70466. dt = now - _this._lastFrameTime;
  70467. }
  70468. _this._lastFrameTime = now;
  70469. // Stop the animation if there is user interaction and the animation should stop for this interaction
  70470. _this._applyUserInteraction();
  70471. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  70472. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  70473. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  70474. // Step camera rotation by rotation speed
  70475. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  70476. });
  70477. };
  70478. AutoRotationBehavior.prototype.detach = function () {
  70479. var scene = this._attachedCamera.getScene();
  70480. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  70481. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70482. this._attachedCamera = null;
  70483. };
  70484. /**
  70485. * Returns true if user is scrolling.
  70486. * @return true if user is scrolling.
  70487. */
  70488. AutoRotationBehavior.prototype._userIsZooming = function () {
  70489. return this._attachedCamera.inertialRadiusOffset !== 0;
  70490. };
  70491. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  70492. var zoomHasHitLimit = false;
  70493. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  70494. zoomHasHitLimit = true;
  70495. }
  70496. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  70497. this._lastFrameRadius = this._attachedCamera.radius;
  70498. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  70499. };
  70500. /**
  70501. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  70502. */
  70503. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  70504. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  70505. this._lastInteractionTime = BABYLON.Tools.Now;
  70506. }
  70507. };
  70508. // Tools
  70509. AutoRotationBehavior.prototype._userIsMoving = function () {
  70510. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  70511. this._attachedCamera.inertialBetaOffset !== 0 ||
  70512. this._attachedCamera.inertialRadiusOffset !== 0 ||
  70513. this._attachedCamera.inertialPanningX !== 0 ||
  70514. this._attachedCamera.inertialPanningY !== 0 ||
  70515. this._isPointerDown;
  70516. };
  70517. return AutoRotationBehavior;
  70518. }());
  70519. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  70520. })(BABYLON || (BABYLON = {}));
  70521. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  70522. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\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>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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 MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\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#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\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#if defined(OPACITY) && OPACITYDIRECTUV == 0\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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\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(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\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) && SPECULARDIRECTUV == 0\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#if defined(BUMP) && BUMPDIRECTUV == 0\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<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\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;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\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=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\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+uvOffset).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+uvOffset);\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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\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+uvOffset);\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+uvOffset).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#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\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\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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 MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \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#if defined(OPACITY) && OPACITYDIRECTUV == 0 \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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \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(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \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(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \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\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nfloat comp=sign(dot(normalW,faceNormal));\nnormalW*=-comp;\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\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;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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\nvFogDistance=viewPos;\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}","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}","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}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\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>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\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}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 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#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\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}","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}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\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\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\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}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\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;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\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#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\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","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}","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}","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","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\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(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\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(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\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;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\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(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\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()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"#version 300 es\nprecision highp float;\nprecision highp int;\n#include<bones300Declaration>\n#include<instances300Declaration>\nin vec3 position;\nin vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nout vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nin vec2 uv;\n#endif\n#ifdef UV2\nin vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nout vec3 vNormalV;\nout vec4 vViewPos;\n#ifdef POSITION\nout vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\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}","geometryPixelShader":"#version 300 es\nprecision highp float;\nprecision highp int;\nin vec3 vNormalV;\nin vec4 vViewPos;\n#ifdef POSITION\nin vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nin vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nlayout(location=0) out vec4 color0;\nlayout(location=1) out vec4 color1;\n#ifdef POSITION\nlayout(location=2) out vec4 color2;\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ncolor0=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\ncolor1=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ncolor2=vec4(vPosition,1.0);\n#endif\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}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\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}","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}","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 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\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)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,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(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,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}","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}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 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}\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#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\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}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","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}","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}","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,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\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{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\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 DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\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}","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}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\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","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}","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}","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}"};
  70523. 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","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\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","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 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}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{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#ifdef NDOTL\nfloat ndl;\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));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=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;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec4 vNormalReoderParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\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_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vNormalReoderParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\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#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\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\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\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\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","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","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\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.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\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}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\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#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap.x=vNormalReoderParams.x+vNormalReoderParams.y*map.x;\nmap.y=vNormalReoderParams.z+vNormalReoderParams.w*map.y;\nmap=map*255./127.-128./127.;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\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","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\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 vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec4 vNormalReoderParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec4 vNormalReoderParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  70524. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  70525. module.exports = BABYLON;
  70526. };