babylon.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * 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.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. /**
  1424. * Constant used to convert a value to gamma space
  1425. * @ignorenaming
  1426. */
  1427. BABYLON.ToGammaSpace = 1 / 2.2;
  1428. /**
  1429. * Constant used to convert a value to linear space
  1430. * @ignorenaming
  1431. */
  1432. BABYLON.ToLinearSpace = 2.2;
  1433. /**
  1434. * Constant used to define the minimal number value in Babylon.js
  1435. * @ignorenaming
  1436. */
  1437. BABYLON.Epsilon = 0.001;
  1438. /**
  1439. * Class used to hold a RBG color
  1440. */
  1441. var Color3 = /** @class */ (function () {
  1442. /**
  1443. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1444. * @param r defines the red component (between 0 and 1, default is 0)
  1445. * @param g defines the green component (between 0 and 1, default is 0)
  1446. * @param b defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. function Color3(
  1449. /**
  1450. * Defines the red component (between 0 and 1, default is 0)
  1451. */
  1452. r,
  1453. /**
  1454. * Defines the green component (between 0 and 1, default is 0)
  1455. */
  1456. g,
  1457. /**
  1458. * Defines the blue component (between 0 and 1, default is 0)
  1459. */
  1460. b) {
  1461. if (r === void 0) { r = 0; }
  1462. if (g === void 0) { g = 0; }
  1463. if (b === void 0) { b = 0; }
  1464. this.r = r;
  1465. this.g = g;
  1466. this.b = b;
  1467. }
  1468. /**
  1469. * Creates a string with the Color3 current values
  1470. * @returns the string representation of the Color3 object
  1471. */
  1472. Color3.prototype.toString = function () {
  1473. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1474. };
  1475. /**
  1476. * Returns the string "Color3"
  1477. * @returns "Color3"
  1478. */
  1479. Color3.prototype.getClassName = function () {
  1480. return "Color3";
  1481. };
  1482. /**
  1483. * Compute the Color3 hash code
  1484. * @returns an unique number that can be used to hash Color3 objects
  1485. */
  1486. Color3.prototype.getHashCode = function () {
  1487. var hash = this.r || 0;
  1488. hash = (hash * 397) ^ (this.g || 0);
  1489. hash = (hash * 397) ^ (this.b || 0);
  1490. return hash;
  1491. };
  1492. // Operators
  1493. /**
  1494. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1495. * @param array defines the array where to store the r,g,b components
  1496. * @param index defines an optional index in the target array to define where to start storing values
  1497. * @returns the current Color3 object
  1498. */
  1499. Color3.prototype.toArray = function (array, index) {
  1500. if (index === undefined) {
  1501. index = 0;
  1502. }
  1503. array[index] = this.r;
  1504. array[index + 1] = this.g;
  1505. array[index + 2] = this.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1510. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1511. * @returns a new {BABYLON.Color4} object
  1512. */
  1513. Color3.prototype.toColor4 = function (alpha) {
  1514. if (alpha === void 0) { alpha = 1; }
  1515. return new Color4(this.r, this.g, this.b, alpha);
  1516. };
  1517. /**
  1518. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1519. * @returns the new array
  1520. */
  1521. Color3.prototype.asArray = function () {
  1522. var result = new Array();
  1523. this.toArray(result, 0);
  1524. return result;
  1525. };
  1526. /**
  1527. * Returns the luminance value
  1528. * @returns a float value
  1529. */
  1530. Color3.prototype.toLuminance = function () {
  1531. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1532. };
  1533. /**
  1534. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1535. * @param otherColor defines the second operand
  1536. * @returns the new Color3 object
  1537. */
  1538. Color3.prototype.multiply = function (otherColor) {
  1539. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1540. };
  1541. /**
  1542. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1543. * @param otherColor defines the second operand
  1544. * @param result defines the Color3 object where to store the result
  1545. * @returns the current Color3
  1546. */
  1547. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1548. result.r = this.r * otherColor.r;
  1549. result.g = this.g * otherColor.g;
  1550. result.b = this.b * otherColor.b;
  1551. return this;
  1552. };
  1553. /**
  1554. * Determines equality between Color3 objects
  1555. * @param otherColor defines the second operand
  1556. * @returns true if the rgb values are equal to the given ones
  1557. */
  1558. Color3.prototype.equals = function (otherColor) {
  1559. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1560. };
  1561. /**
  1562. * Determines equality between the current Color3 object and a set of r,b,g values
  1563. * @param r defines the red component to check
  1564. * @param g defines the green component to check
  1565. * @param b defines the blue component to check
  1566. * @returns true if the rgb values are equal to the given ones
  1567. */
  1568. Color3.prototype.equalsFloats = function (r, g, b) {
  1569. return this.r === r && this.g === g && this.b === b;
  1570. };
  1571. /**
  1572. * Multiplies in place each rgb value by scale
  1573. * @param scale defines the scaling factor
  1574. * @returns the updated Color3
  1575. */
  1576. Color3.prototype.scale = function (scale) {
  1577. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1578. };
  1579. /**
  1580. * Multiplies the rgb values by scale and stores the result into "result"
  1581. * @param scale defines the scaling factor
  1582. * @param result defines the Color3 object where to store the result
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleToRef = function (scale, result) {
  1586. result.r = this.r * scale;
  1587. result.g = this.g * scale;
  1588. result.b = this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Scale the current Color3 values by a factor and add the result to a given Color3
  1593. * @param scale defines the scale factor
  1594. * @param result defines color to store the result into
  1595. * @returns the unmodified current Color3
  1596. */
  1597. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1598. result.r += this.r * scale;
  1599. result.g += this.g * scale;
  1600. result.b += this.b * scale;
  1601. return this;
  1602. };
  1603. /**
  1604. * Clamps the rgb values by the min and max values and stores the result into "result"
  1605. * @param min defines minimum clamping value (default is 0)
  1606. * @param max defines maximum clamping value (default is 1)
  1607. * @param result defines color to store the result into
  1608. * @returns the original Color3
  1609. */
  1610. Color3.prototype.clampToRef = function (min, max, result) {
  1611. if (min === void 0) { min = 0; }
  1612. if (max === void 0) { max = 1; }
  1613. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1614. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1615. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1616. return this;
  1617. };
  1618. /**
  1619. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1620. * @param otherColor defines the second operand
  1621. * @returns the new Color3
  1622. */
  1623. Color3.prototype.add = function (otherColor) {
  1624. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1625. };
  1626. /**
  1627. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1628. * @param otherColor defines the second operand
  1629. * @param result defines Color3 object to store the result into
  1630. * @returns the unmodified current Color3
  1631. */
  1632. Color3.prototype.addToRef = function (otherColor, result) {
  1633. result.r = this.r + otherColor.r;
  1634. result.g = this.g + otherColor.g;
  1635. result.b = this.b + otherColor.b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1640. * @param otherColor defines the second operand
  1641. * @returns the new Color3
  1642. */
  1643. Color3.prototype.subtract = function (otherColor) {
  1644. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1645. };
  1646. /**
  1647. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1648. * @param otherColor defines the second operand
  1649. * @param result defines Color3 object to store the result into
  1650. * @returns the unmodified current Color3
  1651. */
  1652. Color3.prototype.subtractToRef = function (otherColor, result) {
  1653. result.r = this.r - otherColor.r;
  1654. result.g = this.g - otherColor.g;
  1655. result.b = this.b - otherColor.b;
  1656. return this;
  1657. };
  1658. /**
  1659. * Copy the current object
  1660. * @returns a new Color3 copied the current one
  1661. */
  1662. Color3.prototype.clone = function () {
  1663. return new Color3(this.r, this.g, this.b);
  1664. };
  1665. /**
  1666. * Copies the rgb values from the source in the current Color3
  1667. * @param source defines the source Color3 object
  1668. * @returns the updated Color3 object
  1669. */
  1670. Color3.prototype.copyFrom = function (source) {
  1671. this.r = source.r;
  1672. this.g = source.g;
  1673. this.b = source.b;
  1674. return this;
  1675. };
  1676. /**
  1677. * Updates the Color3 rgb values from the given floats
  1678. * @param r defines the red component to read from
  1679. * @param g defines the green component to read from
  1680. * @param b defines the blue component to read from
  1681. * @returns the current Color3 object
  1682. */
  1683. Color3.prototype.copyFromFloats = function (r, g, b) {
  1684. this.r = r;
  1685. this.g = g;
  1686. this.b = b;
  1687. return this;
  1688. };
  1689. /**
  1690. * Updates the Color3 rgb values from the given floats
  1691. * @param r defines the red component to read from
  1692. * @param g defines the green component to read from
  1693. * @param b defines the blue component to read from
  1694. * @returns the current Color3 object
  1695. */
  1696. Color3.prototype.set = function (r, g, b) {
  1697. return this.copyFromFloats(r, g, b);
  1698. };
  1699. /**
  1700. * Compute the Color3 hexadecimal code as a string
  1701. * @returns a string containing the hexadecimal representation of the Color3 object
  1702. */
  1703. Color3.prototype.toHexString = function () {
  1704. var intR = (this.r * 255) | 0;
  1705. var intG = (this.g * 255) | 0;
  1706. var intB = (this.b * 255) | 0;
  1707. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1708. };
  1709. /**
  1710. * Computes a new Color3 converted from the current one to linear space
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.prototype.toLinearSpace = function () {
  1714. var convertedColor = new Color3();
  1715. this.toLinearSpaceToRef(convertedColor);
  1716. return convertedColor;
  1717. };
  1718. /**
  1719. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1720. * @param convertedColor defines the Color3 object where to store the linear space version
  1721. * @returns the unmodified Color3
  1722. */
  1723. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1724. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1725. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1726. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1727. return this;
  1728. };
  1729. /**
  1730. * Computes a new Color3 converted from the current one to gamma space
  1731. * @returns a new Color3 object
  1732. */
  1733. Color3.prototype.toGammaSpace = function () {
  1734. var convertedColor = new Color3();
  1735. this.toGammaSpaceToRef(convertedColor);
  1736. return convertedColor;
  1737. };
  1738. /**
  1739. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1740. * @param convertedColor defines the Color3 object where to store the gamma space version
  1741. * @returns the unmodified Color3
  1742. */
  1743. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1744. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1745. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1746. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1747. return this;
  1748. };
  1749. // Statics
  1750. /**
  1751. * Creates a new Color3 from the string containing valid hexadecimal values
  1752. * @param hex defines a string containing valid hexadecimal values
  1753. * @returns a new Color3 object
  1754. */
  1755. Color3.FromHexString = function (hex) {
  1756. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1757. return new Color3(0, 0, 0);
  1758. }
  1759. var r = parseInt(hex.substring(1, 3), 16);
  1760. var g = parseInt(hex.substring(3, 5), 16);
  1761. var b = parseInt(hex.substring(5, 7), 16);
  1762. return Color3.FromInts(r, g, b);
  1763. };
  1764. /**
  1765. * Creates a new Vector3 from the starting index of the given array
  1766. * @param array defines the source array
  1767. * @param offset defines an offset in the source array
  1768. * @returns a new Color3 object
  1769. */
  1770. Color3.FromArray = function (array, offset) {
  1771. if (offset === void 0) { offset = 0; }
  1772. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1773. };
  1774. /**
  1775. * Creates a new Color3 from integer values (< 256)
  1776. * @param r defines the red component to read from (value between 0 and 255)
  1777. * @param g defines the green component to read from (value between 0 and 255)
  1778. * @param b defines the blue component to read from (value between 0 and 255)
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.FromInts = function (r, g, b) {
  1782. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1783. };
  1784. /**
  1785. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1786. * @param start defines the start Color3 value
  1787. * @param end defines the end Color3 value
  1788. * @param amount defines the gradient value between start and end
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Lerp = function (start, end, amount) {
  1792. var result = new Color3(0.0, 0.0, 0.0);
  1793. Color3.LerpToRef(start, end, amount, result);
  1794. return result;
  1795. };
  1796. /**
  1797. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1798. * @param left defines the start value
  1799. * @param right defines the end value
  1800. * @param amount defines the gradient factor
  1801. * @param result defines the Color3 object where to store the result
  1802. */
  1803. Color3.LerpToRef = function (left, right, amount, result) {
  1804. result.r = left.r + ((right.r - left.r) * amount);
  1805. result.g = left.g + ((right.g - left.g) * amount);
  1806. result.b = left.b + ((right.b - left.b) * amount);
  1807. };
  1808. /**
  1809. * Returns a Color3 value containing a red color
  1810. * @returns a new Color3 object
  1811. */
  1812. Color3.Red = function () { return new Color3(1, 0, 0); };
  1813. /**
  1814. * Returns a Color3 value containing a green color
  1815. * @returns a new Color3 object
  1816. */
  1817. Color3.Green = function () { return new Color3(0, 1, 0); };
  1818. /**
  1819. * Returns a Color3 value containing a blue color
  1820. * @returns a new Color3 object
  1821. */
  1822. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1823. /**
  1824. * Returns a Color3 value containing a black color
  1825. * @returns a new Color3 object
  1826. */
  1827. Color3.Black = function () { return new Color3(0, 0, 0); };
  1828. /**
  1829. * Returns a Color3 value containing a white color
  1830. * @returns a new Color3 object
  1831. */
  1832. Color3.White = function () { return new Color3(1, 1, 1); };
  1833. /**
  1834. * Returns a Color3 value containing a purple color
  1835. * @returns a new Color3 object
  1836. */
  1837. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1838. /**
  1839. * Returns a Color3 value containing a magenta color
  1840. * @returns a new Color3 object
  1841. */
  1842. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1843. /**
  1844. * Returns a Color3 value containing a yellow color
  1845. * @returns a new Color3 object
  1846. */
  1847. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1848. /**
  1849. * Returns a Color3 value containing a gray color
  1850. * @returns a new Color3 object
  1851. */
  1852. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1853. /**
  1854. * Returns a Color3 value containing a teal color
  1855. * @returns a new Color3 object
  1856. */
  1857. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1858. /**
  1859. * Returns a Color3 value containing a random color
  1860. * @returns a new Color3 object
  1861. */
  1862. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1863. return Color3;
  1864. }());
  1865. BABYLON.Color3 = Color3;
  1866. /**
  1867. * Class used to hold a RBGA color
  1868. */
  1869. var Color4 = /** @class */ (function () {
  1870. /**
  1871. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1872. * @param r defines the red component (between 0 and 1, default is 0)
  1873. * @param g defines the green component (between 0 and 1, default is 0)
  1874. * @param b defines the blue component (between 0 and 1, default is 0)
  1875. * @param a defines the alpha component (between 0 and 1, default is 1)
  1876. */
  1877. function Color4(
  1878. /**
  1879. * Defines the red component (between 0 and 1, default is 0)
  1880. */
  1881. r,
  1882. /**
  1883. * Defines the green component (between 0 and 1, default is 0)
  1884. */
  1885. g,
  1886. /**
  1887. * Defines the blue component (between 0 and 1, default is 0)
  1888. */
  1889. b,
  1890. /**
  1891. * Defines the alpha component (between 0 and 1, default is 1)
  1892. */
  1893. a) {
  1894. if (r === void 0) { r = 0; }
  1895. if (g === void 0) { g = 0; }
  1896. if (b === void 0) { b = 0; }
  1897. if (a === void 0) { a = 1; }
  1898. this.r = r;
  1899. this.g = g;
  1900. this.b = b;
  1901. this.a = a;
  1902. }
  1903. // Operators
  1904. /**
  1905. * Adds in place the given Color4 values to the current Color4 object
  1906. * @param right defines the second operand
  1907. * @returns the current updated Color4 object
  1908. */
  1909. Color4.prototype.addInPlace = function (right) {
  1910. this.r += right.r;
  1911. this.g += right.g;
  1912. this.b += right.b;
  1913. this.a += right.a;
  1914. return this;
  1915. };
  1916. /**
  1917. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1918. * @returns the new array
  1919. */
  1920. Color4.prototype.asArray = function () {
  1921. var result = new Array();
  1922. this.toArray(result, 0);
  1923. return result;
  1924. };
  1925. /**
  1926. * Stores from the starting index in the given array the Color4 successive values
  1927. * @param array defines the array where to store the r,g,b components
  1928. * @param index defines an optional index in the target array to define where to start storing values
  1929. * @returns the current Color4 object
  1930. */
  1931. Color4.prototype.toArray = function (array, index) {
  1932. if (index === undefined) {
  1933. index = 0;
  1934. }
  1935. array[index] = this.r;
  1936. array[index + 1] = this.g;
  1937. array[index + 2] = this.b;
  1938. array[index + 3] = this.a;
  1939. return this;
  1940. };
  1941. /**
  1942. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1943. * @param right defines the second operand
  1944. * @returns a new Color4 object
  1945. */
  1946. Color4.prototype.add = function (right) {
  1947. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1948. };
  1949. /**
  1950. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1951. * @param right defines the second operand
  1952. * @returns a new Color4 object
  1953. */
  1954. Color4.prototype.subtract = function (right) {
  1955. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1956. };
  1957. /**
  1958. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1959. * @param right defines the second operand
  1960. * @param result defines the Color4 object where to store the result
  1961. * @returns the current Color4 object
  1962. */
  1963. Color4.prototype.subtractToRef = function (right, result) {
  1964. result.r = this.r - right.r;
  1965. result.g = this.g - right.g;
  1966. result.b = this.b - right.b;
  1967. result.a = this.a - right.a;
  1968. return this;
  1969. };
  1970. /**
  1971. * Creates a new Color4 with the current Color4 values multiplied by scale
  1972. * @param scale defines the scaling factor to apply
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.scale = function (scale) {
  1976. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1977. };
  1978. /**
  1979. * Multiplies the current Color4 values by scale and stores the result in "result"
  1980. * @param scale defines the scaling factor to apply
  1981. * @param result defines the Color4 object where to store the result
  1982. * @returns the current unmodified Color4
  1983. */
  1984. Color4.prototype.scaleToRef = function (scale, result) {
  1985. result.r = this.r * scale;
  1986. result.g = this.g * scale;
  1987. result.b = this.b * scale;
  1988. result.a = this.a * scale;
  1989. return this;
  1990. };
  1991. /**
  1992. * Scale the current Color4 values by a factor and add the result to a given Color4
  1993. * @param scale defines the scale factor
  1994. * @param result defines the Color4 object where to store the result
  1995. * @returns the unmodified current Color4
  1996. */
  1997. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1998. result.r += this.r * scale;
  1999. result.g += this.g * scale;
  2000. result.b += this.b * scale;
  2001. result.a += this.a * scale;
  2002. return this;
  2003. };
  2004. /**
  2005. * Clamps the rgb values by the min and max values and stores the result into "result"
  2006. * @param min defines minimum clamping value (default is 0)
  2007. * @param max defines maximum clamping value (default is 1)
  2008. * @param result defines color to store the result into.
  2009. * @returns the cuurent Color4
  2010. */
  2011. Color4.prototype.clampToRef = function (min, max, result) {
  2012. if (min === void 0) { min = 0; }
  2013. if (max === void 0) { max = 1; }
  2014. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2015. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2016. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2017. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2018. return this;
  2019. };
  2020. /**
  2021. * Multipy an Color4 value by another and return a new Color4 object
  2022. * @param color defines the Color4 value to multiply by
  2023. * @returns a new Color4 object
  2024. */
  2025. Color4.prototype.multiply = function (color) {
  2026. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2027. };
  2028. /**
  2029. * Multipy a Color4 value by another and push the result in a reference value
  2030. * @param color defines the Color4 value to multiply by
  2031. * @param result defines the Color4 to fill the result in
  2032. * @returns the result Color4
  2033. */
  2034. Color4.prototype.multiplyToRef = function (color, result) {
  2035. result.r = this.r * color.r;
  2036. result.g = this.g * color.g;
  2037. result.b = this.b * color.b;
  2038. result.a = this.a * color.a;
  2039. return result;
  2040. };
  2041. /**
  2042. * Creates a string with the Color4 current values
  2043. * @returns the string representation of the Color4 object
  2044. */
  2045. Color4.prototype.toString = function () {
  2046. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2047. };
  2048. /**
  2049. * Returns the string "Color4"
  2050. * @returns "Color4"
  2051. */
  2052. Color4.prototype.getClassName = function () {
  2053. return "Color4";
  2054. };
  2055. /**
  2056. * Compute the Color4 hash code
  2057. * @returns an unique number that can be used to hash Color4 objects
  2058. */
  2059. Color4.prototype.getHashCode = function () {
  2060. var hash = this.r || 0;
  2061. hash = (hash * 397) ^ (this.g || 0);
  2062. hash = (hash * 397) ^ (this.b || 0);
  2063. hash = (hash * 397) ^ (this.a || 0);
  2064. return hash;
  2065. };
  2066. /**
  2067. * Creates a new Color4 copied from the current one
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.clone = function () {
  2071. return new Color4(this.r, this.g, this.b, this.a);
  2072. };
  2073. /**
  2074. * Copies the given Color4 values into the current one
  2075. * @param source defines the source Color4 object
  2076. * @returns the current updated Color4 object
  2077. */
  2078. Color4.prototype.copyFrom = function (source) {
  2079. this.r = source.r;
  2080. this.g = source.g;
  2081. this.b = source.b;
  2082. this.a = source.a;
  2083. return this;
  2084. };
  2085. /**
  2086. * Copies the given float values into the current one
  2087. * @param r defines the red component to read from
  2088. * @param g defines the green component to read from
  2089. * @param b defines the blue component to read from
  2090. * @param a defines the alpha component to read from
  2091. * @returns the current updated Color4 object
  2092. */
  2093. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2094. this.r = r;
  2095. this.g = g;
  2096. this.b = b;
  2097. this.a = a;
  2098. return this;
  2099. };
  2100. /**
  2101. * Copies the given float values into the current one
  2102. * @param r defines the red component to read from
  2103. * @param g defines the green component to read from
  2104. * @param b defines the blue component to read from
  2105. * @param a defines the alpha component to read from
  2106. * @returns the current updated Color4 object
  2107. */
  2108. Color4.prototype.set = function (r, g, b, a) {
  2109. return this.copyFromFloats(r, g, b, a);
  2110. };
  2111. /**
  2112. * Compute the Color4 hexadecimal code as a string
  2113. * @returns a string containing the hexadecimal representation of the Color4 object
  2114. */
  2115. Color4.prototype.toHexString = function () {
  2116. var intR = (this.r * 255) | 0;
  2117. var intG = (this.g * 255) | 0;
  2118. var intB = (this.b * 255) | 0;
  2119. var intA = (this.a * 255) | 0;
  2120. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2121. };
  2122. /**
  2123. * Computes a new Color4 converted from the current one to linear space
  2124. * @returns a new Color4 object
  2125. */
  2126. Color4.prototype.toLinearSpace = function () {
  2127. var convertedColor = new Color4();
  2128. this.toLinearSpaceToRef(convertedColor);
  2129. return convertedColor;
  2130. };
  2131. /**
  2132. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2133. * @param convertedColor defines the Color4 object where to store the linear space version
  2134. * @returns the unmodified Color4
  2135. */
  2136. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2137. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2138. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2139. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2140. convertedColor.a = this.a;
  2141. return this;
  2142. };
  2143. /**
  2144. * Computes a new Color4 converted from the current one to gamma space
  2145. * @returns a new Color4 object
  2146. */
  2147. Color4.prototype.toGammaSpace = function () {
  2148. var convertedColor = new Color4();
  2149. this.toGammaSpaceToRef(convertedColor);
  2150. return convertedColor;
  2151. };
  2152. /**
  2153. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2154. * @param convertedColor defines the Color4 object where to store the gamma space version
  2155. * @returns the unmodified Color4
  2156. */
  2157. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2158. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2159. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2160. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2161. convertedColor.a = this.a;
  2162. return this;
  2163. };
  2164. // Statics
  2165. /**
  2166. * Creates a new Color4 from the string containing valid hexadecimal values
  2167. * @param hex defines a string containing valid hexadecimal values
  2168. * @returns a new Color4 object
  2169. */
  2170. Color4.FromHexString = function (hex) {
  2171. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2172. return new Color4(0.0, 0.0, 0.0, 0.0);
  2173. }
  2174. var r = parseInt(hex.substring(1, 3), 16);
  2175. var g = parseInt(hex.substring(3, 5), 16);
  2176. var b = parseInt(hex.substring(5, 7), 16);
  2177. var a = parseInt(hex.substring(7, 9), 16);
  2178. return Color4.FromInts(r, g, b, a);
  2179. };
  2180. /**
  2181. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2182. * @param left defines the start value
  2183. * @param right defines the end value
  2184. * @param amount defines the gradient factor
  2185. * @returns a new Color4 object
  2186. */
  2187. Color4.Lerp = function (left, right, amount) {
  2188. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2189. Color4.LerpToRef(left, right, amount, result);
  2190. return result;
  2191. };
  2192. /**
  2193. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2194. * @param left defines the start value
  2195. * @param right defines the end value
  2196. * @param amount defines the gradient factor
  2197. * @param result defines the Color4 object where to store data
  2198. */
  2199. Color4.LerpToRef = function (left, right, amount, result) {
  2200. result.r = left.r + (right.r - left.r) * amount;
  2201. result.g = left.g + (right.g - left.g) * amount;
  2202. result.b = left.b + (right.b - left.b) * amount;
  2203. result.a = left.a + (right.a - left.a) * amount;
  2204. };
  2205. /**
  2206. * Creates a new Color4 from a Color3 and an alpha value
  2207. * @param color3 defines the source Color3 to read from
  2208. * @param alpha defines the alpha component (1.0 by default)
  2209. * @returns a new Color4 object
  2210. */
  2211. Color4.FromColor3 = function (color3, alpha) {
  2212. if (alpha === void 0) { alpha = 1.0; }
  2213. return new Color4(color3.r, color3.g, color3.b, alpha);
  2214. };
  2215. /**
  2216. * Creates a new Color4 from the starting index element of the given array
  2217. * @param array defines the source array to read from
  2218. * @param offset defines the offset in the source array
  2219. * @returns a new Color4 object
  2220. */
  2221. Color4.FromArray = function (array, offset) {
  2222. if (offset === void 0) { offset = 0; }
  2223. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2224. };
  2225. /**
  2226. * Creates a new Color3 from integer values (< 256)
  2227. * @param r defines the red component to read from (value between 0 and 255)
  2228. * @param g defines the green component to read from (value between 0 and 255)
  2229. * @param b defines the blue component to read from (value between 0 and 255)
  2230. * @param a defines the alpha component to read from (value between 0 and 255)
  2231. * @returns a new Color3 object
  2232. */
  2233. Color4.FromInts = function (r, g, b, a) {
  2234. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2235. };
  2236. /**
  2237. * Check the content of a given array and convert it to an array containing RGBA data
  2238. * If the original array was already containing count * 4 values then it is returned directly
  2239. * @param colors defines the array to check
  2240. * @param count defines the number of RGBA data to expect
  2241. * @returns an array containing count * 4 values (RGBA)
  2242. */
  2243. Color4.CheckColors4 = function (colors, count) {
  2244. // Check if color3 was used
  2245. if (colors.length === count * 3) {
  2246. var colors4 = [];
  2247. for (var index = 0; index < colors.length; index += 3) {
  2248. var newIndex = (index / 3) * 4;
  2249. colors4[newIndex] = colors[index];
  2250. colors4[newIndex + 1] = colors[index + 1];
  2251. colors4[newIndex + 2] = colors[index + 2];
  2252. colors4[newIndex + 3] = 1.0;
  2253. }
  2254. return colors4;
  2255. }
  2256. return colors;
  2257. };
  2258. return Color4;
  2259. }());
  2260. BABYLON.Color4 = Color4;
  2261. /**
  2262. * Class representing a vector containing 2 coordinates
  2263. */
  2264. var Vector2 = /** @class */ (function () {
  2265. /**
  2266. * Creates a new Vector2 from the given x and y coordinates
  2267. * @param x defines the first coordinate
  2268. * @param y defines the second coordinate
  2269. */
  2270. function Vector2(
  2271. /** defines the first coordinate */
  2272. x,
  2273. /** defines the second coordinate */
  2274. y) {
  2275. if (x === void 0) { x = 0; }
  2276. if (y === void 0) { y = 0; }
  2277. this.x = x;
  2278. this.y = y;
  2279. }
  2280. /**
  2281. * Gets a string with the Vector2 coordinates
  2282. * @returns a string with the Vector2 coordinates
  2283. */
  2284. Vector2.prototype.toString = function () {
  2285. return "{X: " + this.x + " Y:" + this.y + "}";
  2286. };
  2287. /**
  2288. * Gets class name
  2289. * @returns the string "Vector2"
  2290. */
  2291. Vector2.prototype.getClassName = function () {
  2292. return "Vector2";
  2293. };
  2294. /**
  2295. * Gets current vector hash code
  2296. * @returns the Vector2 hash code as a number
  2297. */
  2298. Vector2.prototype.getHashCode = function () {
  2299. var hash = this.x || 0;
  2300. hash = (hash * 397) ^ (this.y || 0);
  2301. return hash;
  2302. };
  2303. // Operators
  2304. /**
  2305. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2306. * @param array defines the source array
  2307. * @param index defines the offset in source array
  2308. * @returns the current Vector2
  2309. */
  2310. Vector2.prototype.toArray = function (array, index) {
  2311. if (index === void 0) { index = 0; }
  2312. array[index] = this.x;
  2313. array[index + 1] = this.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Copy the current vector to an array
  2318. * @returns a new array with 2 elements: the Vector2 coordinates.
  2319. */
  2320. Vector2.prototype.asArray = function () {
  2321. var result = new Array();
  2322. this.toArray(result, 0);
  2323. return result;
  2324. };
  2325. /**
  2326. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2327. * @param source defines the source Vector2
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.copyFrom = function (source) {
  2331. this.x = source.x;
  2332. this.y = source.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Sets the Vector2 coordinates with the given floats
  2337. * @param x defines the first coordinate
  2338. * @param y defines the second coordinate
  2339. * @returns the current updated Vector2
  2340. */
  2341. Vector2.prototype.copyFromFloats = function (x, y) {
  2342. this.x = x;
  2343. this.y = y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the given floats
  2348. * @param x defines the first coordinate
  2349. * @param y defines the second coordinate
  2350. * @returns the current updated Vector2
  2351. */
  2352. Vector2.prototype.set = function (x, y) {
  2353. return this.copyFromFloats(x, y);
  2354. };
  2355. /**
  2356. * Add another vector with the current one
  2357. * @param otherVector defines the other vector
  2358. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2359. */
  2360. Vector2.prototype.add = function (otherVector) {
  2361. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2362. };
  2363. /**
  2364. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2365. * @param otherVector defines the other vector
  2366. * @param result defines the target vector
  2367. * @returns the unmodified current Vector2
  2368. */
  2369. Vector2.prototype.addToRef = function (otherVector, result) {
  2370. result.x = this.x + otherVector.x;
  2371. result.y = this.y + otherVector.y;
  2372. return this;
  2373. };
  2374. /**
  2375. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2376. * @param otherVector defines the other vector
  2377. * @returns the current updated Vector2
  2378. */
  2379. Vector2.prototype.addInPlace = function (otherVector) {
  2380. this.x += otherVector.x;
  2381. this.y += otherVector.y;
  2382. return this;
  2383. };
  2384. /**
  2385. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2386. * @param otherVector defines the other vector
  2387. * @returns a new Vector2
  2388. */
  2389. Vector2.prototype.addVector3 = function (otherVector) {
  2390. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2391. };
  2392. /**
  2393. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2394. * @param otherVector defines the other vector
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.subtract = function (otherVector) {
  2398. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2399. };
  2400. /**
  2401. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2402. * @param otherVector defines the other vector
  2403. * @param result defines the target vector
  2404. * @returns the unmodified current Vector2
  2405. */
  2406. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2407. result.x = this.x - otherVector.x;
  2408. result.y = this.y - otherVector.y;
  2409. return this;
  2410. };
  2411. /**
  2412. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2413. * @param otherVector defines the other vector
  2414. * @returns the current updated Vector2
  2415. */
  2416. Vector2.prototype.subtractInPlace = function (otherVector) {
  2417. this.x -= otherVector.x;
  2418. this.y -= otherVector.y;
  2419. return this;
  2420. };
  2421. /**
  2422. * Multiplies in place the current Vector2 coordinates by the given ones
  2423. * @param otherVector defines the other vector
  2424. * @returns the current updated Vector2
  2425. */
  2426. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2427. this.x *= otherVector.x;
  2428. this.y *= otherVector.y;
  2429. return this;
  2430. };
  2431. /**
  2432. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2433. * @param otherVector defines the other vector
  2434. * @returns a new Vector2
  2435. */
  2436. Vector2.prototype.multiply = function (otherVector) {
  2437. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2438. };
  2439. /**
  2440. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2441. * @param otherVector defines the other vector
  2442. * @param result defines the target vector
  2443. * @returns the unmodified current Vector2
  2444. */
  2445. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2446. result.x = this.x * otherVector.x;
  2447. result.y = this.y * otherVector.y;
  2448. return this;
  2449. };
  2450. /**
  2451. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2452. * @param x defines the first coordinate
  2453. * @param y defines the second coordinate
  2454. * @returns a new Vector2
  2455. */
  2456. Vector2.prototype.multiplyByFloats = function (x, y) {
  2457. return new Vector2(this.x * x, this.y * y);
  2458. };
  2459. /**
  2460. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2461. * @param otherVector defines the other vector
  2462. * @returns a new Vector2
  2463. */
  2464. Vector2.prototype.divide = function (otherVector) {
  2465. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2466. };
  2467. /**
  2468. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2469. * @param otherVector defines the other vector
  2470. * @param result defines the target vector
  2471. * @returns the unmodified current Vector2
  2472. */
  2473. Vector2.prototype.divideToRef = function (otherVector, result) {
  2474. result.x = this.x / otherVector.x;
  2475. result.y = this.y / otherVector.y;
  2476. return this;
  2477. };
  2478. /**
  2479. * Divides the current Vector2 coordinates by the given ones
  2480. * @param otherVector defines the other vector
  2481. * @returns the current updated Vector2
  2482. */
  2483. Vector2.prototype.divideInPlace = function (otherVector) {
  2484. return this.divideToRef(otherVector, this);
  2485. };
  2486. /**
  2487. * Gets a new Vector2 with current Vector2 negated coordinates
  2488. * @returns a new Vector2
  2489. */
  2490. Vector2.prototype.negate = function () {
  2491. return new Vector2(-this.x, -this.y);
  2492. };
  2493. /**
  2494. * Multiply the Vector2 coordinates by scale
  2495. * @param scale defines the scaling factor
  2496. * @returns the current updated Vector2
  2497. */
  2498. Vector2.prototype.scaleInPlace = function (scale) {
  2499. this.x *= scale;
  2500. this.y *= scale;
  2501. return this;
  2502. };
  2503. /**
  2504. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2505. * @param scale defines the scaling factor
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.prototype.scale = function (scale) {
  2509. var result = new Vector2(0, 0);
  2510. this.scaleToRef(scale, result);
  2511. return result;
  2512. };
  2513. /**
  2514. * Scale the current Vector2 values by a factor to a given Vector2
  2515. * @param scale defines the scale factor
  2516. * @param result defines the Vector2 object where to store the result
  2517. * @returns the unmodified current Vector2
  2518. */
  2519. Vector2.prototype.scaleToRef = function (scale, result) {
  2520. result.x = this.x * scale;
  2521. result.y = this.y * scale;
  2522. return this;
  2523. };
  2524. /**
  2525. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2526. * @param scale defines the scale factor
  2527. * @param result defines the Vector2 object where to store the result
  2528. * @returns the unmodified current Vector2
  2529. */
  2530. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2531. result.x += this.x * scale;
  2532. result.y += this.y * scale;
  2533. return this;
  2534. };
  2535. /**
  2536. * Gets a boolean if two vectors are equals
  2537. * @param otherVector defines the other vector
  2538. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2539. */
  2540. Vector2.prototype.equals = function (otherVector) {
  2541. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2542. };
  2543. /**
  2544. * Gets a boolean if two vectors are equals (using an epsilon value)
  2545. * @param otherVector defines the other vector
  2546. * @param epsilon defines the minimal distance to consider equality
  2547. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2548. */
  2549. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2550. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2551. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2552. };
  2553. /**
  2554. * Gets a new Vector2 from current Vector2 floored values
  2555. * @returns a new Vector2
  2556. */
  2557. Vector2.prototype.floor = function () {
  2558. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2559. };
  2560. /**
  2561. * Gets a new Vector2 from current Vector2 floored values
  2562. * @returns a new Vector2
  2563. */
  2564. Vector2.prototype.fract = function () {
  2565. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2566. };
  2567. // Properties
  2568. /**
  2569. * Gets the length of the vector
  2570. * @returns the vector length (float)
  2571. */
  2572. Vector2.prototype.length = function () {
  2573. return Math.sqrt(this.x * this.x + this.y * this.y);
  2574. };
  2575. /**
  2576. * Gets the vector squared length
  2577. * @returns the vector squared length (float)
  2578. */
  2579. Vector2.prototype.lengthSquared = function () {
  2580. return (this.x * this.x + this.y * this.y);
  2581. };
  2582. // Methods
  2583. /**
  2584. * Normalize the vector
  2585. * @returns the current updated Vector2
  2586. */
  2587. Vector2.prototype.normalize = function () {
  2588. var len = this.length();
  2589. if (len === 0)
  2590. return this;
  2591. var num = 1.0 / len;
  2592. this.x *= num;
  2593. this.y *= num;
  2594. return this;
  2595. };
  2596. /**
  2597. * Gets a new Vector2 copied from the Vector2
  2598. * @returns a new Vector2
  2599. */
  2600. Vector2.prototype.clone = function () {
  2601. return new Vector2(this.x, this.y);
  2602. };
  2603. // Statics
  2604. /**
  2605. * Gets a new Vector2(0, 0)
  2606. * @returns a new Vector2
  2607. */
  2608. Vector2.Zero = function () {
  2609. return new Vector2(0, 0);
  2610. };
  2611. /**
  2612. * Gets a new Vector2(1, 1)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.One = function () {
  2616. return new Vector2(1, 1);
  2617. };
  2618. /**
  2619. * Gets a new Vector2 set from the given index element of the given array
  2620. * @param array defines the data source
  2621. * @param offset defines the offset in the data source
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.FromArray = function (array, offset) {
  2625. if (offset === void 0) { offset = 0; }
  2626. return new Vector2(array[offset], array[offset + 1]);
  2627. };
  2628. /**
  2629. * Sets "result" from the given index element of the given array
  2630. * @param array defines the data source
  2631. * @param offset defines the offset in the data source
  2632. * @param result defines the target vector
  2633. */
  2634. Vector2.FromArrayToRef = function (array, offset, result) {
  2635. result.x = array[offset];
  2636. result.y = array[offset + 1];
  2637. };
  2638. /**
  2639. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2640. * @param value1 defines 1st point of control
  2641. * @param value2 defines 2nd point of control
  2642. * @param value3 defines 3rd point of control
  2643. * @param value4 defines 4th point of control
  2644. * @param amount defines the interpolation factor
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2648. var squared = amount * amount;
  2649. var cubed = amount * squared;
  2650. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2651. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2652. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2653. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2654. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2655. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2656. return new Vector2(x, y);
  2657. };
  2658. /**
  2659. * 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".
  2660. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2661. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2662. * @param value defines the value to clamp
  2663. * @param min defines the lower limit
  2664. * @param max defines the upper limit
  2665. * @returns a new Vector2
  2666. */
  2667. Vector2.Clamp = function (value, min, max) {
  2668. var x = value.x;
  2669. x = (x > max.x) ? max.x : x;
  2670. x = (x < min.x) ? min.x : x;
  2671. var y = value.y;
  2672. y = (y > max.y) ? max.y : y;
  2673. y = (y < min.y) ? min.y : y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2678. * @param value1 defines the 1st control point
  2679. * @param tangent1 defines the outgoing tangent
  2680. * @param value2 defines the 2nd control point
  2681. * @param tangent2 defines the incoming tangent
  2682. * @param amount defines the interpolation factor
  2683. * @returns a new Vector2
  2684. */
  2685. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2686. var squared = amount * amount;
  2687. var cubed = amount * squared;
  2688. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2689. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2690. var part3 = (cubed - (2.0 * squared)) + amount;
  2691. var part4 = cubed - squared;
  2692. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2693. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2694. return new Vector2(x, y);
  2695. };
  2696. /**
  2697. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2698. * @param start defines the start vector
  2699. * @param end defines the end vector
  2700. * @param amount defines the interpolation factor
  2701. * @returns a new Vector2
  2702. */
  2703. Vector2.Lerp = function (start, end, amount) {
  2704. var x = start.x + ((end.x - start.x) * amount);
  2705. var y = start.y + ((end.y - start.y) * amount);
  2706. return new Vector2(x, y);
  2707. };
  2708. /**
  2709. * Gets the dot product of the vector "left" and the vector "right"
  2710. * @param left defines first vector
  2711. * @param right defines second vector
  2712. * @returns the dot product (float)
  2713. */
  2714. Vector2.Dot = function (left, right) {
  2715. return left.x * right.x + left.y * right.y;
  2716. };
  2717. /**
  2718. * Returns a new Vector2 equal to the normalized given vector
  2719. * @param vector defines the vector to normalize
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Normalize = function (vector) {
  2723. var newVector = vector.clone();
  2724. newVector.normalize();
  2725. return newVector;
  2726. };
  2727. /**
  2728. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2729. * @param left defines 1st vector
  2730. * @param right defines 2nd vector
  2731. * @returns a new Vector2
  2732. */
  2733. Vector2.Minimize = function (left, right) {
  2734. var x = (left.x < right.x) ? left.x : right.x;
  2735. var y = (left.y < right.y) ? left.y : right.y;
  2736. return new Vector2(x, y);
  2737. };
  2738. /**
  2739. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2740. * @param left defines 1st vector
  2741. * @param right defines 2nd vector
  2742. * @returns a new Vector2
  2743. */
  2744. Vector2.Maximize = function (left, right) {
  2745. var x = (left.x > right.x) ? left.x : right.x;
  2746. var y = (left.y > right.y) ? left.y : right.y;
  2747. return new Vector2(x, y);
  2748. };
  2749. /**
  2750. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2751. * @param vector defines the vector to transform
  2752. * @param transformation defines the matrix to apply
  2753. * @returns a new Vector2
  2754. */
  2755. Vector2.Transform = function (vector, transformation) {
  2756. var r = Vector2.Zero();
  2757. Vector2.TransformToRef(vector, transformation, r);
  2758. return r;
  2759. };
  2760. /**
  2761. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2762. * @param vector defines the vector to transform
  2763. * @param transformation defines the matrix to apply
  2764. * @param result defines the target vector
  2765. */
  2766. Vector2.TransformToRef = function (vector, transformation, result) {
  2767. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2768. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2769. result.x = x;
  2770. result.y = y;
  2771. };
  2772. /**
  2773. * Determines if a given vector is included in a triangle
  2774. * @param p defines the vector to test
  2775. * @param p0 defines 1st triangle point
  2776. * @param p1 defines 2nd triangle point
  2777. * @param p2 defines 3rd triangle point
  2778. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2779. */
  2780. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2781. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2782. var sign = a < 0 ? -1 : 1;
  2783. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2784. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2785. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2786. };
  2787. /**
  2788. * Gets the distance between the vectors "value1" and "value2"
  2789. * @param value1 defines first vector
  2790. * @param value2 defines second vector
  2791. * @returns the distance between vectors
  2792. */
  2793. Vector2.Distance = function (value1, value2) {
  2794. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2795. };
  2796. /**
  2797. * Returns the squared distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the squared distance between vectors
  2801. */
  2802. Vector2.DistanceSquared = function (value1, value2) {
  2803. var x = value1.x - value2.x;
  2804. var y = value1.y - value2.y;
  2805. return (x * x) + (y * y);
  2806. };
  2807. /**
  2808. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2809. * @param value1 defines first vector
  2810. * @param value2 defines second vector
  2811. * @returns a new Vector2
  2812. */
  2813. Vector2.Center = function (value1, value2) {
  2814. var center = value1.add(value2);
  2815. center.scaleInPlace(0.5);
  2816. return center;
  2817. };
  2818. /**
  2819. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2820. * @param p defines the middle point
  2821. * @param segA defines one point of the segment
  2822. * @param segB defines the other point of the segment
  2823. * @returns the shortest distance
  2824. */
  2825. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2826. var l2 = Vector2.DistanceSquared(segA, segB);
  2827. if (l2 === 0.0) {
  2828. return Vector2.Distance(p, segA);
  2829. }
  2830. var v = segB.subtract(segA);
  2831. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2832. var proj = segA.add(v.multiplyByFloats(t, t));
  2833. return Vector2.Distance(p, proj);
  2834. };
  2835. return Vector2;
  2836. }());
  2837. BABYLON.Vector2 = Vector2;
  2838. /**
  2839. * Classed used to store (x,y,z) vector representation
  2840. * A Vector3 is the main object used in 3D geometry
  2841. * It can represent etiher the coordinates of a point the space, either a direction
  2842. * Reminder: Babylon.js uses a left handed forward facing system
  2843. */
  2844. var Vector3 = /** @class */ (function () {
  2845. /**
  2846. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2847. * @param x defines the first coordinates (on X axis)
  2848. * @param y defines the second coordinates (on Y axis)
  2849. * @param z defines the third coordinates (on Z axis)
  2850. */
  2851. function Vector3(
  2852. /**
  2853. * Defines the first coordinates (on X axis)
  2854. */
  2855. x,
  2856. /**
  2857. * Defines the second coordinates (on Y axis)
  2858. */
  2859. y,
  2860. /**
  2861. * Defines the third coordinates (on Z axis)
  2862. */
  2863. z) {
  2864. if (x === void 0) { x = 0; }
  2865. if (y === void 0) { y = 0; }
  2866. if (z === void 0) { z = 0; }
  2867. this.x = x;
  2868. this.y = y;
  2869. this.z = z;
  2870. }
  2871. /**
  2872. * Creates a string representation of the Vector3
  2873. * @returns a string with the Vector3 coordinates.
  2874. */
  2875. Vector3.prototype.toString = function () {
  2876. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2877. };
  2878. /**
  2879. * Gets the class name
  2880. * @returns the string "Vector3"
  2881. */
  2882. Vector3.prototype.getClassName = function () {
  2883. return "Vector3";
  2884. };
  2885. /**
  2886. * Creates the Vector3 hash code
  2887. * @returns a number which tends to be unique between Vector3 instances
  2888. */
  2889. Vector3.prototype.getHashCode = function () {
  2890. var hash = this.x || 0;
  2891. hash = (hash * 397) ^ (this.y || 0);
  2892. hash = (hash * 397) ^ (this.z || 0);
  2893. return hash;
  2894. };
  2895. // Operators
  2896. /**
  2897. * Creates an array containing three elements : the coordinates of the Vector3
  2898. * @returns a new array of numbers
  2899. */
  2900. Vector3.prototype.asArray = function () {
  2901. var result = [];
  2902. this.toArray(result, 0);
  2903. return result;
  2904. };
  2905. /**
  2906. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2907. * @param array defines the destination array
  2908. * @param index defines the offset in the destination array
  2909. * @returns the current Vector3
  2910. */
  2911. Vector3.prototype.toArray = function (array, index) {
  2912. if (index === void 0) { index = 0; }
  2913. array[index] = this.x;
  2914. array[index + 1] = this.y;
  2915. array[index + 2] = this.z;
  2916. return this;
  2917. };
  2918. /**
  2919. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2920. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2921. */
  2922. Vector3.prototype.toQuaternion = function () {
  2923. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2924. };
  2925. /**
  2926. * Adds the given vector to the current Vector3
  2927. * @param otherVector defines the second operand
  2928. * @returns the current updated Vector3
  2929. */
  2930. Vector3.prototype.addInPlace = function (otherVector) {
  2931. this.x += otherVector.x;
  2932. this.y += otherVector.y;
  2933. this.z += otherVector.z;
  2934. return this;
  2935. };
  2936. /**
  2937. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2938. * @param otherVector defines the second operand
  2939. * @returns the resulting Vector3
  2940. */
  2941. Vector3.prototype.add = function (otherVector) {
  2942. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2943. };
  2944. /**
  2945. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2946. * @param otherVector defines the second operand
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the current Vector3
  2949. */
  2950. Vector3.prototype.addToRef = function (otherVector, result) {
  2951. result.x = this.x + otherVector.x;
  2952. result.y = this.y + otherVector.y;
  2953. result.z = this.z + otherVector.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Subtract the given vector from the current Vector3
  2958. * @param otherVector defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.subtractInPlace = function (otherVector) {
  2962. this.x -= otherVector.x;
  2963. this.y -= otherVector.y;
  2964. this.z -= otherVector.z;
  2965. return this;
  2966. };
  2967. /**
  2968. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2969. * @param otherVector defines the second operand
  2970. * @returns the resulting Vector3
  2971. */
  2972. Vector3.prototype.subtract = function (otherVector) {
  2973. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2974. };
  2975. /**
  2976. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2977. * @param otherVector defines the second operand
  2978. * @param result defines the Vector3 object where to store the result
  2979. * @returns the current Vector3
  2980. */
  2981. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2982. result.x = this.x - otherVector.x;
  2983. result.y = this.y - otherVector.y;
  2984. result.z = this.z - otherVector.z;
  2985. return this;
  2986. };
  2987. /**
  2988. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2989. * @param x defines the x coordinate of the operand
  2990. * @param y defines the y coordinate of the operand
  2991. * @param z defines the z coordinate of the operand
  2992. * @returns the resulting Vector3
  2993. */
  2994. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2995. return new Vector3(this.x - x, this.y - y, this.z - z);
  2996. };
  2997. /**
  2998. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @param result defines the Vector3 object where to store the result
  3003. * @returns the current Vector3
  3004. */
  3005. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3006. result.x = this.x - x;
  3007. result.y = this.y - y;
  3008. result.z = this.z - z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3013. * @returns a new Vector3
  3014. */
  3015. Vector3.prototype.negate = function () {
  3016. return new Vector3(-this.x, -this.y, -this.z);
  3017. };
  3018. /**
  3019. * Multiplies the Vector3 coordinates by the float "scale"
  3020. * @param scale defines the multiplier factor
  3021. * @returns the current updated Vector3
  3022. */
  3023. Vector3.prototype.scaleInPlace = function (scale) {
  3024. this.x *= scale;
  3025. this.y *= scale;
  3026. this.z *= scale;
  3027. return this;
  3028. };
  3029. /**
  3030. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3031. * @param scale defines the multiplier factor
  3032. * @returns a new Vector3
  3033. */
  3034. Vector3.prototype.scale = function (scale) {
  3035. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3036. };
  3037. /**
  3038. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3039. * @param scale defines the multiplier factor
  3040. * @param result defines the Vector3 object where to store the result
  3041. * @returns the current Vector3
  3042. */
  3043. Vector3.prototype.scaleToRef = function (scale, result) {
  3044. result.x = this.x * scale;
  3045. result.y = this.y * scale;
  3046. result.z = this.z * scale;
  3047. return this;
  3048. };
  3049. /**
  3050. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3051. * @param scale defines the scale factor
  3052. * @param result defines the Vector3 object where to store the result
  3053. * @returns the unmodified current Vector3
  3054. */
  3055. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3056. result.x += this.x * scale;
  3057. result.y += this.y * scale;
  3058. result.z += this.z * scale;
  3059. return this;
  3060. };
  3061. /**
  3062. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3063. * @param otherVector defines the second operand
  3064. * @returns true if both vectors are equals
  3065. */
  3066. Vector3.prototype.equals = function (otherVector) {
  3067. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3068. };
  3069. /**
  3070. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3071. * @param otherVector defines the second operand
  3072. * @param epsilon defines the minimal distance to define values as equals
  3073. * @returns true if both vectors are distant less than epsilon
  3074. */
  3075. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3076. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3077. 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);
  3078. };
  3079. /**
  3080. * Returns true if the current Vector3 coordinates equals the given floats
  3081. * @param x defines the x coordinate of the operand
  3082. * @param y defines the y coordinate of the operand
  3083. * @param z defines the z coordinate of the operand
  3084. * @returns true if both vectors are equals
  3085. */
  3086. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3087. return this.x === x && this.y === y && this.z === z;
  3088. };
  3089. /**
  3090. * Multiplies the current Vector3 coordinates by the given ones
  3091. * @param otherVector defines the second operand
  3092. * @returns the current updated Vector3
  3093. */
  3094. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3095. this.x *= otherVector.x;
  3096. this.y *= otherVector.y;
  3097. this.z *= otherVector.z;
  3098. return this;
  3099. };
  3100. /**
  3101. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3102. * @param otherVector defines the second operand
  3103. * @returns the new Vector3
  3104. */
  3105. Vector3.prototype.multiply = function (otherVector) {
  3106. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3107. };
  3108. /**
  3109. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3110. * @param otherVector defines the second operand
  3111. * @param result defines the Vector3 object where to store the result
  3112. * @returns the current Vector3
  3113. */
  3114. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3115. result.x = this.x * otherVector.x;
  3116. result.y = this.y * otherVector.y;
  3117. result.z = this.z * otherVector.z;
  3118. return this;
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3122. * @param x defines the x coordinate of the operand
  3123. * @param y defines the y coordinate of the operand
  3124. * @param z defines the z coordinate of the operand
  3125. * @returns the new Vector3
  3126. */
  3127. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3128. return new Vector3(this.x * x, this.y * y, this.z * z);
  3129. };
  3130. /**
  3131. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3132. * @param otherVector defines the second operand
  3133. * @returns the new Vector3
  3134. */
  3135. Vector3.prototype.divide = function (otherVector) {
  3136. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3137. };
  3138. /**
  3139. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3140. * @param otherVector defines the second operand
  3141. * @param result defines the Vector3 object where to store the result
  3142. * @returns the current Vector3
  3143. */
  3144. Vector3.prototype.divideToRef = function (otherVector, result) {
  3145. result.x = this.x / otherVector.x;
  3146. result.y = this.y / otherVector.y;
  3147. result.z = this.z / otherVector.z;
  3148. return this;
  3149. };
  3150. /**
  3151. * Divides the current Vector3 coordinates by the given ones.
  3152. * @param otherVector defines the second operand
  3153. * @returns the current updated Vector3
  3154. */
  3155. Vector3.prototype.divideInPlace = function (otherVector) {
  3156. return this.divideToRef(otherVector, this);
  3157. };
  3158. /**
  3159. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3160. * @param other defines the second operand
  3161. * @returns the current updated Vector3
  3162. */
  3163. Vector3.prototype.minimizeInPlace = function (other) {
  3164. if (other.x < this.x)
  3165. this.x = other.x;
  3166. if (other.y < this.y)
  3167. this.y = other.y;
  3168. if (other.z < this.z)
  3169. this.z = other.z;
  3170. return this;
  3171. };
  3172. /**
  3173. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3174. * @param other defines the second operand
  3175. * @returns the current updated Vector3
  3176. */
  3177. Vector3.prototype.maximizeInPlace = function (other) {
  3178. if (other.x > this.x)
  3179. this.x = other.x;
  3180. if (other.y > this.y)
  3181. this.y = other.y;
  3182. if (other.z > this.z)
  3183. this.z = other.z;
  3184. return this;
  3185. };
  3186. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3187. /**
  3188. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3189. */
  3190. get: function () {
  3191. var absX = Math.abs(this.x);
  3192. var absY = Math.abs(this.y);
  3193. if (absX !== absY) {
  3194. return true;
  3195. }
  3196. var absZ = Math.abs(this.z);
  3197. if (absX !== absZ) {
  3198. return true;
  3199. }
  3200. if (absY !== absZ) {
  3201. return true;
  3202. }
  3203. return false;
  3204. },
  3205. enumerable: true,
  3206. configurable: true
  3207. });
  3208. /**
  3209. * Gets a new Vector3 from current Vector3 floored values
  3210. * @returns a new Vector3
  3211. */
  3212. Vector3.prototype.floor = function () {
  3213. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3214. };
  3215. /**
  3216. * Gets a new Vector3 from current Vector3 floored values
  3217. * @returns a new Vector3
  3218. */
  3219. Vector3.prototype.fract = function () {
  3220. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3221. };
  3222. // Properties
  3223. /**
  3224. * Gets the length of the Vector3
  3225. * @returns the length of the Vecto3
  3226. */
  3227. Vector3.prototype.length = function () {
  3228. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3229. };
  3230. /**
  3231. * Gets the squared length of the Vector3
  3232. * @returns squared length of the Vector3
  3233. */
  3234. Vector3.prototype.lengthSquared = function () {
  3235. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3236. };
  3237. /**
  3238. * Normalize the current Vector3.
  3239. * Please note that this is an in place operation.
  3240. * @returns the current updated Vector3
  3241. */
  3242. Vector3.prototype.normalize = function () {
  3243. var len = this.length();
  3244. if (len === 0 || len === 1.0)
  3245. return this;
  3246. var num = 1.0 / len;
  3247. this.x *= num;
  3248. this.y *= num;
  3249. this.z *= num;
  3250. return this;
  3251. };
  3252. /**
  3253. * Normalize the current Vector3 to a new vector
  3254. * @returns the new Vector3
  3255. */
  3256. Vector3.prototype.normalizeToNew = function () {
  3257. var normalized = new Vector3(0, 0, 0);
  3258. this.normalizeToRef(normalized);
  3259. return normalized;
  3260. };
  3261. /**
  3262. * Normalize the current Vector3 to the reference
  3263. * @param reference define the Vector3 to update
  3264. * @returns the updated Vector3
  3265. */
  3266. Vector3.prototype.normalizeToRef = function (reference) {
  3267. var len = this.length();
  3268. if (len === 0 || len === 1.0) {
  3269. reference.set(this.x, this.y, this.z);
  3270. return reference;
  3271. }
  3272. var scale = 1.0 / len;
  3273. this.scaleToRef(scale, reference);
  3274. return reference;
  3275. };
  3276. /**
  3277. * Creates a new Vector3 copied from the current Vector3
  3278. * @returns the new Vector3
  3279. */
  3280. Vector3.prototype.clone = function () {
  3281. return new Vector3(this.x, this.y, this.z);
  3282. };
  3283. /**
  3284. * Copies the given vector coordinates to the current Vector3 ones
  3285. * @param source defines the source Vector3
  3286. * @returns the current updated Vector3
  3287. */
  3288. Vector3.prototype.copyFrom = function (source) {
  3289. this.x = source.x;
  3290. this.y = source.y;
  3291. this.z = source.z;
  3292. return this;
  3293. };
  3294. /**
  3295. * Copies the given floats to the current Vector3 coordinates
  3296. * @param x defines the x coordinate of the operand
  3297. * @param y defines the y coordinate of the operand
  3298. * @param z defines the z coordinate of the operand
  3299. * @returns the current updated Vector3
  3300. */
  3301. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3302. this.x = x;
  3303. this.y = y;
  3304. this.z = z;
  3305. return this;
  3306. };
  3307. /**
  3308. * Copies the given floats to the current Vector3 coordinates
  3309. * @param x defines the x coordinate of the operand
  3310. * @param y defines the y coordinate of the operand
  3311. * @param z defines the z coordinate of the operand
  3312. * @returns the current updated Vector3
  3313. */
  3314. Vector3.prototype.set = function (x, y, z) {
  3315. return this.copyFromFloats(x, y, z);
  3316. };
  3317. // Statics
  3318. /**
  3319. * Get the clip factor between two vectors
  3320. * @param vector0 defines the first operand
  3321. * @param vector1 defines the second operand
  3322. * @param axis defines the axis to use
  3323. * @param size defines the size along the axis
  3324. * @returns the clip factor
  3325. */
  3326. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3327. var d0 = Vector3.Dot(vector0, axis) - size;
  3328. var d1 = Vector3.Dot(vector1, axis) - size;
  3329. var s = d0 / (d0 - d1);
  3330. return s;
  3331. };
  3332. /**
  3333. * Get angle between two vectors
  3334. * @param vector0 angle between vector0 and vector1
  3335. * @param vector1 angle between vector0 and vector1
  3336. * @param normal direction of the normal
  3337. * @return the angle between vector0 and vector1
  3338. */
  3339. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3340. var v0 = vector0.clone().normalize();
  3341. var v1 = vector1.clone().normalize();
  3342. var dot = Vector3.Dot(v0, v1);
  3343. var n = Vector3.Cross(v0, v1);
  3344. if (Vector3.Dot(n, normal) > 0) {
  3345. return Math.acos(dot);
  3346. }
  3347. return -Math.acos(dot);
  3348. };
  3349. /**
  3350. * Returns a new Vector3 set from the index "offset" of the given array
  3351. * @param array defines the source array
  3352. * @param offset defines the offset in the source array
  3353. * @returns the new Vector3
  3354. */
  3355. Vector3.FromArray = function (array, offset) {
  3356. if (!offset) {
  3357. offset = 0;
  3358. }
  3359. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3360. };
  3361. /**
  3362. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3363. * This function is deprecated. Use FromArray instead
  3364. * @param array defines the source array
  3365. * @param offset defines the offset in the source array
  3366. * @returns the new Vector3
  3367. */
  3368. Vector3.FromFloatArray = function (array, offset) {
  3369. return Vector3.FromArray(array, offset);
  3370. };
  3371. /**
  3372. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3373. * @param array defines the source array
  3374. * @param offset defines the offset in the source array
  3375. * @param result defines the Vector3 where to store the result
  3376. */
  3377. Vector3.FromArrayToRef = function (array, offset, result) {
  3378. result.x = array[offset];
  3379. result.y = array[offset + 1];
  3380. result.z = array[offset + 2];
  3381. };
  3382. /**
  3383. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3384. * This function is deprecated. Use FromArrayToRef instead.
  3385. * @param array defines the source array
  3386. * @param offset defines the offset in the source array
  3387. * @param result defines the Vector3 where to store the result
  3388. */
  3389. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3390. return Vector3.FromArrayToRef(array, offset, result);
  3391. };
  3392. /**
  3393. * Sets the given vector "result" with the given floats.
  3394. * @param x defines the x coordinate of the source
  3395. * @param y defines the y coordinate of the source
  3396. * @param z defines the z coordinate of the source
  3397. * @param result defines the Vector3 where to store the result
  3398. */
  3399. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3400. result.x = x;
  3401. result.y = y;
  3402. result.z = z;
  3403. };
  3404. /**
  3405. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3406. * @returns a new empty Vector3
  3407. */
  3408. Vector3.Zero = function () {
  3409. return new Vector3(0.0, 0.0, 0.0);
  3410. };
  3411. /**
  3412. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3413. * @returns a new unit Vector3
  3414. */
  3415. Vector3.One = function () {
  3416. return new Vector3(1.0, 1.0, 1.0);
  3417. };
  3418. /**
  3419. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3420. * @returns a new up Vector3
  3421. */
  3422. Vector3.Up = function () {
  3423. return new Vector3(0.0, 1.0, 0.0);
  3424. };
  3425. /**
  3426. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3427. * @returns a new down Vector3
  3428. */
  3429. Vector3.Down = function () {
  3430. return new Vector3(0.0, -1.0, 0.0);
  3431. };
  3432. /**
  3433. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3434. * @returns a new forward Vector3
  3435. */
  3436. Vector3.Forward = function () {
  3437. return new Vector3(0.0, 0.0, 1.0);
  3438. };
  3439. /**
  3440. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3441. * @returns a new forward Vector3
  3442. */
  3443. Vector3.Backward = function () {
  3444. return new Vector3(0.0, 0.0, -1.0);
  3445. };
  3446. /**
  3447. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3448. * @returns a new right Vector3
  3449. */
  3450. Vector3.Right = function () {
  3451. return new Vector3(1.0, 0.0, 0.0);
  3452. };
  3453. /**
  3454. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3455. * @returns a new left Vector3
  3456. */
  3457. Vector3.Left = function () {
  3458. return new Vector3(-1.0, 0.0, 0.0);
  3459. };
  3460. /**
  3461. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3462. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @returns the transformed Vector3
  3466. */
  3467. Vector3.TransformCoordinates = function (vector, transformation) {
  3468. var result = Vector3.Zero();
  3469. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3470. return result;
  3471. };
  3472. /**
  3473. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3474. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3475. * @param vector defines the Vector3 to transform
  3476. * @param transformation defines the transformation matrix
  3477. * @param result defines the Vector3 where to store the result
  3478. */
  3479. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3480. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3481. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3482. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3483. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3484. result.x = x / w;
  3485. result.y = y / w;
  3486. result.z = z / w;
  3487. };
  3488. /**
  3489. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3490. * This method computes tranformed coordinates only, not transformed direction vectors
  3491. * @param x define the x coordinate of the source vector
  3492. * @param y define the y coordinate of the source vector
  3493. * @param z define the z coordinate of the source vector
  3494. * @param transformation defines the transformation matrix
  3495. * @param result defines the Vector3 where to store the result
  3496. */
  3497. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3498. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3499. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3500. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3501. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3502. result.x = rx / rw;
  3503. result.y = ry / rw;
  3504. result.z = rz / rw;
  3505. };
  3506. /**
  3507. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param vector defines the Vector3 to transform
  3510. * @param transformation defines the transformation matrix
  3511. * @returns the new Vector3
  3512. */
  3513. Vector3.TransformNormal = function (vector, transformation) {
  3514. var result = Vector3.Zero();
  3515. Vector3.TransformNormalToRef(vector, transformation, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3520. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3521. * @param vector defines the Vector3 to transform
  3522. * @param transformation defines the transformation matrix
  3523. * @param result defines the Vector3 where to store the result
  3524. */
  3525. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3526. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3527. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3528. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3529. result.x = x;
  3530. result.y = y;
  3531. result.z = z;
  3532. };
  3533. /**
  3534. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3535. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3536. * @param x define the x coordinate of the source vector
  3537. * @param y define the y coordinate of the source vector
  3538. * @param z define the z coordinate of the source vector
  3539. * @param transformation defines the transformation matrix
  3540. * @param result defines the Vector3 where to store the result
  3541. */
  3542. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3543. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3544. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3545. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3546. };
  3547. /**
  3548. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3549. * @param value1 defines the first control point
  3550. * @param value2 defines the second control point
  3551. * @param value3 defines the third control point
  3552. * @param value4 defines the fourth control point
  3553. * @param amount defines the amount on the spline to use
  3554. * @returns the new Vector3
  3555. */
  3556. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3557. var squared = amount * amount;
  3558. var cubed = amount * squared;
  3559. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3560. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3561. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3562. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3563. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3564. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3565. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3566. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3567. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3568. return new Vector3(x, y, z);
  3569. };
  3570. /**
  3571. * 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"
  3572. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3573. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3574. * @param value defines the current value
  3575. * @param min defines the lower range value
  3576. * @param max defines the upper range value
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.Clamp = function (value, min, max) {
  3580. var x = value.x;
  3581. x = (x > max.x) ? max.x : x;
  3582. x = (x < min.x) ? min.x : x;
  3583. var y = value.y;
  3584. y = (y > max.y) ? max.y : y;
  3585. y = (y < min.y) ? min.y : y;
  3586. var z = value.z;
  3587. z = (z > max.z) ? max.z : z;
  3588. z = (z < min.z) ? min.z : z;
  3589. return new Vector3(x, y, z);
  3590. };
  3591. /**
  3592. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3593. * @param value1 defines the first control point
  3594. * @param tangent1 defines the first tangent vector
  3595. * @param value2 defines the second control point
  3596. * @param tangent2 defines the second tangent vector
  3597. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3598. * @returns the new Vector3
  3599. */
  3600. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3601. var squared = amount * amount;
  3602. var cubed = amount * squared;
  3603. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3604. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3605. var part3 = (cubed - (2.0 * squared)) + amount;
  3606. var part4 = cubed - squared;
  3607. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3608. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3609. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3610. return new Vector3(x, y, z);
  3611. };
  3612. /**
  3613. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3614. * @param start defines the start value
  3615. * @param end defines the end value
  3616. * @param amount max defines amount between both (between 0 and 1)
  3617. * @returns the new Vector3
  3618. */
  3619. Vector3.Lerp = function (start, end, amount) {
  3620. var result = new Vector3(0, 0, 0);
  3621. Vector3.LerpToRef(start, end, amount, result);
  3622. return result;
  3623. };
  3624. /**
  3625. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3626. * @param start defines the start value
  3627. * @param end defines the end value
  3628. * @param amount max defines amount between both (between 0 and 1)
  3629. * @param result defines the Vector3 where to store the result
  3630. */
  3631. Vector3.LerpToRef = function (start, end, amount, result) {
  3632. result.x = start.x + ((end.x - start.x) * amount);
  3633. result.y = start.y + ((end.y - start.y) * amount);
  3634. result.z = start.z + ((end.z - start.z) * amount);
  3635. };
  3636. /**
  3637. * Returns the dot product (float) between the vectors "left" and "right"
  3638. * @param left defines the left operand
  3639. * @param right defines the right operand
  3640. * @returns the dot product
  3641. */
  3642. Vector3.Dot = function (left, right) {
  3643. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3644. };
  3645. /**
  3646. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3647. * The cross product is then orthogonal to both "left" and "right"
  3648. * @param left defines the left operand
  3649. * @param right defines the right operand
  3650. * @returns the cross product
  3651. */
  3652. Vector3.Cross = function (left, right) {
  3653. var result = Vector3.Zero();
  3654. Vector3.CrossToRef(left, right, result);
  3655. return result;
  3656. };
  3657. /**
  3658. * Sets the given vector "result" with the cross product of "left" and "right"
  3659. * The cross product is then orthogonal to both "left" and "right"
  3660. * @param left defines the left operand
  3661. * @param right defines the right operand
  3662. * @param result defines the Vector3 where to store the result
  3663. */
  3664. Vector3.CrossToRef = function (left, right, result) {
  3665. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3666. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3667. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3668. result.copyFrom(MathTmp.Vector3[0]);
  3669. };
  3670. /**
  3671. * Returns a new Vector3 as the normalization of the given vector
  3672. * @param vector defines the Vector3 to normalize
  3673. * @returns the new Vector3
  3674. */
  3675. Vector3.Normalize = function (vector) {
  3676. var result = Vector3.Zero();
  3677. Vector3.NormalizeToRef(vector, result);
  3678. return result;
  3679. };
  3680. /**
  3681. * Sets the given vector "result" with the normalization of the given first vector
  3682. * @param vector defines the Vector3 to normalize
  3683. * @param result defines the Vector3 where to store the result
  3684. */
  3685. Vector3.NormalizeToRef = function (vector, result) {
  3686. result.copyFrom(vector);
  3687. result.normalize();
  3688. };
  3689. /**
  3690. * Project a Vector3 onto screen space
  3691. * @param vector defines the Vector3 to project
  3692. * @param world defines the world matrix to use
  3693. * @param transform defines the transform (view x projection) matrix to use
  3694. * @param viewport defines the screen viewport to use
  3695. * @returns the new Vector3
  3696. */
  3697. Vector3.Project = function (vector, world, transform, viewport) {
  3698. var cw = viewport.width;
  3699. var ch = viewport.height;
  3700. var cx = viewport.x;
  3701. var cy = viewport.y;
  3702. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3703. 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);
  3704. var matrix = MathTmp.Matrix[0];
  3705. world.multiplyToRef(transform, matrix);
  3706. matrix.multiplyToRef(viewportMatrix, matrix);
  3707. return Vector3.TransformCoordinates(vector, matrix);
  3708. };
  3709. /**
  3710. * Unproject from screen space to object space
  3711. * @param source defines the screen space Vector3 to use
  3712. * @param viewportWidth defines the current width of the viewport
  3713. * @param viewportHeight defines the current height of the viewport
  3714. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3715. * @param transform defines the transform (view x projection) matrix to use
  3716. * @returns the new Vector3
  3717. */
  3718. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3719. var matrix = MathTmp.Matrix[0];
  3720. world.multiplyToRef(transform, matrix);
  3721. matrix.invert();
  3722. source.x = source.x / viewportWidth * 2 - 1;
  3723. source.y = -(source.y / viewportHeight * 2 - 1);
  3724. var vector = Vector3.TransformCoordinates(source, matrix);
  3725. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3726. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3727. vector = vector.scale(1.0 / num);
  3728. }
  3729. return vector;
  3730. };
  3731. /**
  3732. * Unproject from screen space to object space
  3733. * @param source defines the screen space Vector3 to use
  3734. * @param viewportWidth defines the current width of the viewport
  3735. * @param viewportHeight defines the current height of the viewport
  3736. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3737. * @param view defines the view matrix to use
  3738. * @param projection defines the projection matrix to use
  3739. * @returns the new Vector3
  3740. */
  3741. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3742. var result = Vector3.Zero();
  3743. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3744. return result;
  3745. };
  3746. /**
  3747. * Unproject from screen space to object space
  3748. * @param source defines the screen space Vector3 to use
  3749. * @param viewportWidth defines the current width of the viewport
  3750. * @param viewportHeight defines the current height of the viewport
  3751. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3752. * @param view defines the view matrix to use
  3753. * @param projection defines the projection matrix to use
  3754. * @param result defines the Vector3 where to store the result
  3755. */
  3756. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3757. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3758. };
  3759. /**
  3760. * Unproject from screen space to object space
  3761. * @param sourceX defines the screen space x coordinate to use
  3762. * @param sourceY defines the screen space y coordinate to use
  3763. * @param sourceZ defines the screen space z coordinate to use
  3764. * @param viewportWidth defines the current width of the viewport
  3765. * @param viewportHeight defines the current height of the viewport
  3766. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3767. * @param view defines the view matrix to use
  3768. * @param projection defines the projection matrix to use
  3769. * @param result defines the Vector3 where to store the result
  3770. */
  3771. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3772. var matrix = MathTmp.Matrix[0];
  3773. world.multiplyToRef(view, matrix);
  3774. matrix.multiplyToRef(projection, matrix);
  3775. matrix.invert();
  3776. var screenSource = MathTmp.Vector3[0];
  3777. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3778. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3779. screenSource.z = 2 * sourceZ - 1.0;
  3780. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3781. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3782. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3783. result.scaleInPlace(1.0 / num);
  3784. }
  3785. };
  3786. /**
  3787. * Gets the minimal coordinate values between two Vector3
  3788. * @param left defines the first operand
  3789. * @param right defines the second operand
  3790. * @returns the new Vector3
  3791. */
  3792. Vector3.Minimize = function (left, right) {
  3793. var min = left.clone();
  3794. min.minimizeInPlace(right);
  3795. return min;
  3796. };
  3797. /**
  3798. * Gets the maximal coordinate values between two Vector3
  3799. * @param left defines the first operand
  3800. * @param right defines the second operand
  3801. * @returns the new Vector3
  3802. */
  3803. Vector3.Maximize = function (left, right) {
  3804. var max = left.clone();
  3805. max.maximizeInPlace(right);
  3806. return max;
  3807. };
  3808. /**
  3809. * Returns the distance between the vectors "value1" and "value2"
  3810. * @param value1 defines the first operand
  3811. * @param value2 defines the second operand
  3812. * @returns the distance
  3813. */
  3814. Vector3.Distance = function (value1, value2) {
  3815. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3816. };
  3817. /**
  3818. * Returns the squared distance between the vectors "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the squared distance
  3822. */
  3823. Vector3.DistanceSquared = function (value1, value2) {
  3824. var x = value1.x - value2.x;
  3825. var y = value1.y - value2.y;
  3826. var z = value1.z - value2.z;
  3827. return (x * x) + (y * y) + (z * z);
  3828. };
  3829. /**
  3830. * Returns a new Vector3 located at the center between "value1" and "value2"
  3831. * @param value1 defines the first operand
  3832. * @param value2 defines the second operand
  3833. * @returns the new Vector3
  3834. */
  3835. Vector3.Center = function (value1, value2) {
  3836. var center = value1.add(value2);
  3837. center.scaleInPlace(0.5);
  3838. return center;
  3839. };
  3840. /**
  3841. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3842. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3843. * to something in order to rotate it from its local system to the given target system
  3844. * Note: axis1, axis2 and axis3 are normalized during this operation
  3845. * @param axis1 defines the first axis
  3846. * @param axis2 defines the second axis
  3847. * @param axis3 defines the third axis
  3848. * @returns a new Vector3
  3849. */
  3850. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3851. var rotation = Vector3.Zero();
  3852. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3853. return rotation;
  3854. };
  3855. /**
  3856. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3857. * @param axis1 defines the first axis
  3858. * @param axis2 defines the second axis
  3859. * @param axis3 defines the third axis
  3860. * @param ref defines the Vector3 where to store the result
  3861. */
  3862. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3863. var quat = MathTmp.Quaternion[0];
  3864. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3865. quat.toEulerAnglesToRef(ref);
  3866. };
  3867. return Vector3;
  3868. }());
  3869. BABYLON.Vector3 = Vector3;
  3870. //Vector4 class created for EulerAngle class conversion to Quaternion
  3871. var Vector4 = /** @class */ (function () {
  3872. /**
  3873. * Creates a Vector4 object from the given floats.
  3874. */
  3875. function Vector4(x, y, z, w) {
  3876. this.x = x;
  3877. this.y = y;
  3878. this.z = z;
  3879. this.w = w;
  3880. }
  3881. /**
  3882. * Returns the string with the Vector4 coordinates.
  3883. */
  3884. Vector4.prototype.toString = function () {
  3885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3886. };
  3887. /**
  3888. * Returns the string "Vector4".
  3889. */
  3890. Vector4.prototype.getClassName = function () {
  3891. return "Vector4";
  3892. };
  3893. /**
  3894. * Returns the Vector4 hash code.
  3895. */
  3896. Vector4.prototype.getHashCode = function () {
  3897. var hash = this.x || 0;
  3898. hash = (hash * 397) ^ (this.y || 0);
  3899. hash = (hash * 397) ^ (this.z || 0);
  3900. hash = (hash * 397) ^ (this.w || 0);
  3901. return hash;
  3902. };
  3903. // Operators
  3904. /**
  3905. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3906. */
  3907. Vector4.prototype.asArray = function () {
  3908. var result = new Array();
  3909. this.toArray(result, 0);
  3910. return result;
  3911. };
  3912. /**
  3913. * Populates the given array from the given index with the Vector4 coordinates.
  3914. * Returns the Vector4.
  3915. */
  3916. Vector4.prototype.toArray = function (array, index) {
  3917. if (index === undefined) {
  3918. index = 0;
  3919. }
  3920. array[index] = this.x;
  3921. array[index + 1] = this.y;
  3922. array[index + 2] = this.z;
  3923. array[index + 3] = this.w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Adds the given vector to the current Vector4.
  3928. * Returns the updated Vector4.
  3929. */
  3930. Vector4.prototype.addInPlace = function (otherVector) {
  3931. this.x += otherVector.x;
  3932. this.y += otherVector.y;
  3933. this.z += otherVector.z;
  3934. this.w += otherVector.w;
  3935. return this;
  3936. };
  3937. /**
  3938. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3939. */
  3940. Vector4.prototype.add = function (otherVector) {
  3941. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3942. };
  3943. /**
  3944. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3945. * Returns the current Vector4.
  3946. */
  3947. Vector4.prototype.addToRef = function (otherVector, result) {
  3948. result.x = this.x + otherVector.x;
  3949. result.y = this.y + otherVector.y;
  3950. result.z = this.z + otherVector.z;
  3951. result.w = this.w + otherVector.w;
  3952. return this;
  3953. };
  3954. /**
  3955. * Subtract in place the given vector from the current Vector4.
  3956. * Returns the updated Vector4.
  3957. */
  3958. Vector4.prototype.subtractInPlace = function (otherVector) {
  3959. this.x -= otherVector.x;
  3960. this.y -= otherVector.y;
  3961. this.z -= otherVector.z;
  3962. this.w -= otherVector.w;
  3963. return this;
  3964. };
  3965. /**
  3966. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3967. */
  3968. Vector4.prototype.subtract = function (otherVector) {
  3969. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3970. };
  3971. /**
  3972. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3973. * Returns the current Vector4.
  3974. */
  3975. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3976. result.x = this.x - otherVector.x;
  3977. result.y = this.y - otherVector.y;
  3978. result.z = this.z - otherVector.z;
  3979. result.w = this.w - otherVector.w;
  3980. return this;
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3984. */
  3985. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3986. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3987. };
  3988. /**
  3989. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3993. result.x = this.x - x;
  3994. result.y = this.y - y;
  3995. result.z = this.z - z;
  3996. result.w = this.w - w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4001. */
  4002. Vector4.prototype.negate = function () {
  4003. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4004. };
  4005. /**
  4006. * Multiplies the current Vector4 coordinates by scale (float).
  4007. * Returns the updated Vector4.
  4008. */
  4009. Vector4.prototype.scaleInPlace = function (scale) {
  4010. this.x *= scale;
  4011. this.y *= scale;
  4012. this.z *= scale;
  4013. this.w *= scale;
  4014. return this;
  4015. };
  4016. /**
  4017. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4018. */
  4019. Vector4.prototype.scale = function (scale) {
  4020. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4021. };
  4022. /**
  4023. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4024. * Returns the current Vector4.
  4025. */
  4026. Vector4.prototype.scaleToRef = function (scale, result) {
  4027. result.x = this.x * scale;
  4028. result.y = this.y * scale;
  4029. result.z = this.z * scale;
  4030. result.w = this.w * scale;
  4031. return this;
  4032. };
  4033. /**
  4034. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4035. * @param scale defines the scale factor
  4036. * @param result defines the Vector4 object where to store the result
  4037. * @returns the unmodified current Vector4
  4038. */
  4039. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4040. result.x += this.x * scale;
  4041. result.y += this.y * scale;
  4042. result.z += this.z * scale;
  4043. result.w += this.w * scale;
  4044. return this;
  4045. };
  4046. /**
  4047. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4048. */
  4049. Vector4.prototype.equals = function (otherVector) {
  4050. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4051. };
  4052. /**
  4053. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4054. */
  4055. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4056. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4057. return otherVector
  4058. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4059. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4060. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4061. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4062. };
  4063. /**
  4064. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4065. */
  4066. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4067. return this.x === x && this.y === y && this.z === z && this.w === w;
  4068. };
  4069. /**
  4070. * Multiplies in place the current Vector4 by the given one.
  4071. * Returns the updated Vector4.
  4072. */
  4073. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4074. this.x *= otherVector.x;
  4075. this.y *= otherVector.y;
  4076. this.z *= otherVector.z;
  4077. this.w *= otherVector.w;
  4078. return this;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4082. */
  4083. Vector4.prototype.multiply = function (otherVector) {
  4084. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4085. };
  4086. /**
  4087. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4088. * Returns the current Vector4.
  4089. */
  4090. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4091. result.x = this.x * otherVector.x;
  4092. result.y = this.y * otherVector.y;
  4093. result.z = this.z * otherVector.z;
  4094. result.w = this.w * otherVector.w;
  4095. return this;
  4096. };
  4097. /**
  4098. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4099. */
  4100. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4101. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4102. };
  4103. /**
  4104. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4105. */
  4106. Vector4.prototype.divide = function (otherVector) {
  4107. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4108. };
  4109. /**
  4110. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4111. * Returns the current Vector4.
  4112. */
  4113. Vector4.prototype.divideToRef = function (otherVector, result) {
  4114. result.x = this.x / otherVector.x;
  4115. result.y = this.y / otherVector.y;
  4116. result.z = this.z / otherVector.z;
  4117. result.w = this.w / otherVector.w;
  4118. return this;
  4119. };
  4120. /**
  4121. * Divides the current Vector3 coordinates by the given ones.
  4122. * @returns the updated Vector3.
  4123. */
  4124. Vector4.prototype.divideInPlace = function (otherVector) {
  4125. return this.divideToRef(otherVector, this);
  4126. };
  4127. /**
  4128. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4129. * @param other defines the second operand
  4130. * @returns the current updated Vector4
  4131. */
  4132. Vector4.prototype.minimizeInPlace = function (other) {
  4133. if (other.x < this.x)
  4134. this.x = other.x;
  4135. if (other.y < this.y)
  4136. this.y = other.y;
  4137. if (other.z < this.z)
  4138. this.z = other.z;
  4139. if (other.w < this.w)
  4140. this.w = other.w;
  4141. return this;
  4142. };
  4143. /**
  4144. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4145. * @param other defines the second operand
  4146. * @returns the current updated Vector4
  4147. */
  4148. Vector4.prototype.maximizeInPlace = function (other) {
  4149. if (other.x > this.x)
  4150. this.x = other.x;
  4151. if (other.y > this.y)
  4152. this.y = other.y;
  4153. if (other.z > this.z)
  4154. this.z = other.z;
  4155. if (other.w > this.w)
  4156. this.w = other.w;
  4157. return this;
  4158. };
  4159. /**
  4160. * Gets a new Vector4 from current Vector4 floored values
  4161. * @returns a new Vector4
  4162. */
  4163. Vector4.prototype.floor = function () {
  4164. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4165. };
  4166. /**
  4167. * Gets a new Vector4 from current Vector3 floored values
  4168. * @returns a new Vector4
  4169. */
  4170. Vector4.prototype.fract = function () {
  4171. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4172. };
  4173. // Properties
  4174. /**
  4175. * Returns the Vector4 length (float).
  4176. */
  4177. Vector4.prototype.length = function () {
  4178. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4179. };
  4180. /**
  4181. * Returns the Vector4 squared length (float).
  4182. */
  4183. Vector4.prototype.lengthSquared = function () {
  4184. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4185. };
  4186. // Methods
  4187. /**
  4188. * Normalizes in place the Vector4.
  4189. * Returns the updated Vector4.
  4190. */
  4191. Vector4.prototype.normalize = function () {
  4192. var len = this.length();
  4193. if (len === 0)
  4194. return this;
  4195. var num = 1.0 / len;
  4196. this.x *= num;
  4197. this.y *= num;
  4198. this.z *= num;
  4199. this.w *= num;
  4200. return this;
  4201. };
  4202. /**
  4203. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4204. */
  4205. Vector4.prototype.toVector3 = function () {
  4206. return new Vector3(this.x, this.y, this.z);
  4207. };
  4208. /**
  4209. * Returns a new Vector4 copied from the current one.
  4210. */
  4211. Vector4.prototype.clone = function () {
  4212. return new Vector4(this.x, this.y, this.z, this.w);
  4213. };
  4214. /**
  4215. * Updates the current Vector4 with the given one coordinates.
  4216. * Returns the updated Vector4.
  4217. */
  4218. Vector4.prototype.copyFrom = function (source) {
  4219. this.x = source.x;
  4220. this.y = source.y;
  4221. this.z = source.z;
  4222. this.w = source.w;
  4223. return this;
  4224. };
  4225. /**
  4226. * Updates the current Vector4 coordinates with the given floats.
  4227. * Returns the updated Vector4.
  4228. */
  4229. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4230. this.x = x;
  4231. this.y = y;
  4232. this.z = z;
  4233. this.w = w;
  4234. return this;
  4235. };
  4236. /**
  4237. * Updates the current Vector4 coordinates with the given floats.
  4238. * Returns the updated Vector4.
  4239. */
  4240. Vector4.prototype.set = function (x, y, z, w) {
  4241. return this.copyFromFloats(x, y, z, w);
  4242. };
  4243. // Statics
  4244. /**
  4245. * Returns a new Vector4 set from the starting index of the given array.
  4246. */
  4247. Vector4.FromArray = function (array, offset) {
  4248. if (!offset) {
  4249. offset = 0;
  4250. }
  4251. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4252. };
  4253. /**
  4254. * Updates the given vector "result" from the starting index of the given array.
  4255. */
  4256. Vector4.FromArrayToRef = function (array, offset, result) {
  4257. result.x = array[offset];
  4258. result.y = array[offset + 1];
  4259. result.z = array[offset + 2];
  4260. result.w = array[offset + 3];
  4261. };
  4262. /**
  4263. * Updates the given vector "result" from the starting index of the given Float32Array.
  4264. */
  4265. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4266. Vector4.FromArrayToRef(array, offset, result);
  4267. };
  4268. /**
  4269. * Updates the given vector "result" coordinates from the given floats.
  4270. */
  4271. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4272. result.x = x;
  4273. result.y = y;
  4274. result.z = z;
  4275. result.w = w;
  4276. };
  4277. /**
  4278. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4279. */
  4280. Vector4.Zero = function () {
  4281. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4282. };
  4283. /**
  4284. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4285. */
  4286. Vector4.One = function () {
  4287. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4288. };
  4289. /**
  4290. * Returns a new normalized Vector4 from the given one.
  4291. */
  4292. Vector4.Normalize = function (vector) {
  4293. var result = Vector4.Zero();
  4294. Vector4.NormalizeToRef(vector, result);
  4295. return result;
  4296. };
  4297. /**
  4298. * Updates the given vector "result" from the normalization of the given one.
  4299. */
  4300. Vector4.NormalizeToRef = function (vector, result) {
  4301. result.copyFrom(vector);
  4302. result.normalize();
  4303. };
  4304. Vector4.Minimize = function (left, right) {
  4305. var min = left.clone();
  4306. min.minimizeInPlace(right);
  4307. return min;
  4308. };
  4309. Vector4.Maximize = function (left, right) {
  4310. var max = left.clone();
  4311. max.maximizeInPlace(right);
  4312. return max;
  4313. };
  4314. /**
  4315. * Returns the distance (float) between the vectors "value1" and "value2".
  4316. */
  4317. Vector4.Distance = function (value1, value2) {
  4318. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4319. };
  4320. /**
  4321. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4322. */
  4323. Vector4.DistanceSquared = function (value1, value2) {
  4324. var x = value1.x - value2.x;
  4325. var y = value1.y - value2.y;
  4326. var z = value1.z - value2.z;
  4327. var w = value1.w - value2.w;
  4328. return (x * x) + (y * y) + (z * z) + (w * w);
  4329. };
  4330. /**
  4331. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4332. */
  4333. Vector4.Center = function (value1, value2) {
  4334. var center = value1.add(value2);
  4335. center.scaleInPlace(0.5);
  4336. return center;
  4337. };
  4338. /**
  4339. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4340. * This methods computes transformed normalized direction vectors only.
  4341. */
  4342. Vector4.TransformNormal = function (vector, transformation) {
  4343. var result = Vector4.Zero();
  4344. Vector4.TransformNormalToRef(vector, transformation, result);
  4345. return result;
  4346. };
  4347. /**
  4348. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4349. * This methods computes transformed normalized direction vectors only.
  4350. */
  4351. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4352. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4353. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4354. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4355. result.x = x;
  4356. result.y = y;
  4357. result.z = z;
  4358. result.w = vector.w;
  4359. };
  4360. /**
  4361. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4362. * This methods computes transformed normalized direction vectors only.
  4363. */
  4364. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4365. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4366. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4367. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4368. result.w = w;
  4369. };
  4370. return Vector4;
  4371. }());
  4372. BABYLON.Vector4 = Vector4;
  4373. var Size = /** @class */ (function () {
  4374. /**
  4375. * Creates a Size object from the given width and height (floats).
  4376. */
  4377. function Size(width, height) {
  4378. this.width = width;
  4379. this.height = height;
  4380. }
  4381. // Returns a string with the Size width and height.
  4382. Size.prototype.toString = function () {
  4383. return "{W: " + this.width + ", H: " + this.height + "}";
  4384. };
  4385. /**
  4386. * Returns the string "Size"
  4387. */
  4388. Size.prototype.getClassName = function () {
  4389. return "Size";
  4390. };
  4391. /**
  4392. * Returns the Size hash code.
  4393. */
  4394. Size.prototype.getHashCode = function () {
  4395. var hash = this.width || 0;
  4396. hash = (hash * 397) ^ (this.height || 0);
  4397. return hash;
  4398. };
  4399. /**
  4400. * Updates the current size from the given one.
  4401. * Returns the updated Size.
  4402. */
  4403. Size.prototype.copyFrom = function (src) {
  4404. this.width = src.width;
  4405. this.height = src.height;
  4406. };
  4407. /**
  4408. * Updates in place the current Size from the given floats.
  4409. * Returns the updated Size.
  4410. */
  4411. Size.prototype.copyFromFloats = function (width, height) {
  4412. this.width = width;
  4413. this.height = height;
  4414. return this;
  4415. };
  4416. /**
  4417. * Updates in place the current Size from the given floats.
  4418. * Returns the updated Size.
  4419. */
  4420. Size.prototype.set = function (width, height) {
  4421. return this.copyFromFloats(width, height);
  4422. };
  4423. /**
  4424. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4425. */
  4426. Size.prototype.multiplyByFloats = function (w, h) {
  4427. return new Size(this.width * w, this.height * h);
  4428. };
  4429. /**
  4430. * Returns a new Size copied from the given one.
  4431. */
  4432. Size.prototype.clone = function () {
  4433. return new Size(this.width, this.height);
  4434. };
  4435. /**
  4436. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4437. */
  4438. Size.prototype.equals = function (other) {
  4439. if (!other) {
  4440. return false;
  4441. }
  4442. return (this.width === other.width) && (this.height === other.height);
  4443. };
  4444. Object.defineProperty(Size.prototype, "surface", {
  4445. /**
  4446. * Returns the surface of the Size : width * height (float).
  4447. */
  4448. get: function () {
  4449. return this.width * this.height;
  4450. },
  4451. enumerable: true,
  4452. configurable: true
  4453. });
  4454. /**
  4455. * Returns a new Size set to (0.0, 0.0)
  4456. */
  4457. Size.Zero = function () {
  4458. return new Size(0.0, 0.0);
  4459. };
  4460. /**
  4461. * Returns a new Size set as the addition result of the current Size and the given one.
  4462. */
  4463. Size.prototype.add = function (otherSize) {
  4464. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4465. return r;
  4466. };
  4467. /**
  4468. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4469. */
  4470. Size.prototype.subtract = function (otherSize) {
  4471. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4472. return r;
  4473. };
  4474. /**
  4475. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4476. */
  4477. Size.Lerp = function (start, end, amount) {
  4478. var w = start.width + ((end.width - start.width) * amount);
  4479. var h = start.height + ((end.height - start.height) * amount);
  4480. return new Size(w, h);
  4481. };
  4482. return Size;
  4483. }());
  4484. BABYLON.Size = Size;
  4485. /**
  4486. * Class used to store quaternion data
  4487. * @see https://en.wikipedia.org/wiki/Quaternion
  4488. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4489. */
  4490. var Quaternion = /** @class */ (function () {
  4491. /**
  4492. * Creates a new Quaternion from the given floats
  4493. * @param x defines the first component (0 by default)
  4494. * @param y defines the second component (0 by default)
  4495. * @param z defines the third component (0 by default)
  4496. * @param w defines the fourth component (1.0 by default)
  4497. */
  4498. function Quaternion(
  4499. /** defines the first component (0 by default) */
  4500. x,
  4501. /** defines the second component (0 by default) */
  4502. y,
  4503. /** defines the third component (0 by default) */
  4504. z,
  4505. /** defines the fourth component (1.0 by default) */
  4506. w) {
  4507. if (x === void 0) { x = 0.0; }
  4508. if (y === void 0) { y = 0.0; }
  4509. if (z === void 0) { z = 0.0; }
  4510. if (w === void 0) { w = 1.0; }
  4511. this.x = x;
  4512. this.y = y;
  4513. this.z = z;
  4514. this.w = w;
  4515. }
  4516. /**
  4517. * Gets a string representation for the current quaternion
  4518. * @returns a string with the Quaternion coordinates
  4519. */
  4520. Quaternion.prototype.toString = function () {
  4521. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4522. };
  4523. /**
  4524. * Gets the class name of the quaternion
  4525. * @returns the string "Quaternion"
  4526. */
  4527. Quaternion.prototype.getClassName = function () {
  4528. return "Quaternion";
  4529. };
  4530. /**
  4531. * Gets a hash code for this quaternion
  4532. * @returns the quaternion hash code
  4533. */
  4534. Quaternion.prototype.getHashCode = function () {
  4535. var hash = this.x || 0;
  4536. hash = (hash * 397) ^ (this.y || 0);
  4537. hash = (hash * 397) ^ (this.z || 0);
  4538. hash = (hash * 397) ^ (this.w || 0);
  4539. return hash;
  4540. };
  4541. /**
  4542. * Copy the quaternion to an array
  4543. * @returns a new array populated with 4 elements from the quaternion coordinates
  4544. */
  4545. Quaternion.prototype.asArray = function () {
  4546. return [this.x, this.y, this.z, this.w];
  4547. };
  4548. /**
  4549. * Check if two quaternions are equals
  4550. * @param otherQuaternion defines the second operand
  4551. * @return true if the current quaternion and the given one coordinates are strictly equals
  4552. */
  4553. Quaternion.prototype.equals = function (otherQuaternion) {
  4554. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4555. };
  4556. /**
  4557. * Clone the current quaternion
  4558. * @returns a new quaternion copied from the current one
  4559. */
  4560. Quaternion.prototype.clone = function () {
  4561. return new Quaternion(this.x, this.y, this.z, this.w);
  4562. };
  4563. /**
  4564. * Copy a quaternion to the current one
  4565. * @param other defines the other quaternion
  4566. * @returns the updated current quaternion
  4567. */
  4568. Quaternion.prototype.copyFrom = function (other) {
  4569. this.x = other.x;
  4570. this.y = other.y;
  4571. this.z = other.z;
  4572. this.w = other.w;
  4573. return this;
  4574. };
  4575. /**
  4576. * Updates the current quaternion with the given float coordinates
  4577. * @param x defines the x coordinate
  4578. * @param y defines the y coordinate
  4579. * @param z defines the z coordinate
  4580. * @param w defines the w coordinate
  4581. * @returns the updated current quaternion
  4582. */
  4583. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4584. this.x = x;
  4585. this.y = y;
  4586. this.z = z;
  4587. this.w = w;
  4588. return this;
  4589. };
  4590. /**
  4591. * Updates the current quaternion from the given float coordinates
  4592. * @param x defines the x coordinate
  4593. * @param y defines the y coordinate
  4594. * @param z defines the z coordinate
  4595. * @param w defines the w coordinate
  4596. * @returns the updated current quaternion
  4597. */
  4598. Quaternion.prototype.set = function (x, y, z, w) {
  4599. return this.copyFromFloats(x, y, z, w);
  4600. };
  4601. /**
  4602. * Adds two quaternions
  4603. * @param other defines the second operand
  4604. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4605. */
  4606. Quaternion.prototype.add = function (other) {
  4607. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4608. };
  4609. /**
  4610. * Add a quaternion to the current one
  4611. * @param other defines the quaternion to add
  4612. * @returns the current quaternion
  4613. */
  4614. Quaternion.prototype.addInPlace = function (other) {
  4615. this.x += other.x;
  4616. this.y += other.y;
  4617. this.z += other.z;
  4618. this.w += other.w;
  4619. return this;
  4620. };
  4621. /**
  4622. * Subtract two quaternions
  4623. * @param other defines the second operand
  4624. * @returns a new quaternion as the subtraction result of the given one from the current one
  4625. */
  4626. Quaternion.prototype.subtract = function (other) {
  4627. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4628. };
  4629. /**
  4630. * Multiplies the current quaternion by a scale factor
  4631. * @param value defines the scale factor
  4632. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4633. */
  4634. Quaternion.prototype.scale = function (value) {
  4635. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4636. };
  4637. /**
  4638. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4639. * @param scale defines the scale factor
  4640. * @param result defines the Quaternion object where to store the result
  4641. * @returns the unmodified current quaternion
  4642. */
  4643. Quaternion.prototype.scaleToRef = function (scale, result) {
  4644. result.x = this.x * scale;
  4645. result.y = this.y * scale;
  4646. result.z = this.z * scale;
  4647. result.w = this.w * scale;
  4648. return this;
  4649. };
  4650. /**
  4651. * Multiplies in place the current quaternion by a scale factor
  4652. * @param value defines the scale factor
  4653. * @returns the current modified quaternion
  4654. */
  4655. Quaternion.prototype.scaleInPlace = function (value) {
  4656. this.x *= value;
  4657. this.y *= value;
  4658. this.z *= value;
  4659. this.w *= value;
  4660. return this;
  4661. };
  4662. /**
  4663. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4664. * @param scale defines the scale factor
  4665. * @param result defines the Quaternion object where to store the result
  4666. * @returns the unmodified current quaternion
  4667. */
  4668. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4669. result.x += this.x * scale;
  4670. result.y += this.y * scale;
  4671. result.z += this.z * scale;
  4672. result.w += this.w * scale;
  4673. return this;
  4674. };
  4675. /**
  4676. * Multiplies two quaternions
  4677. * @param q1 defines the second operand
  4678. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4679. */
  4680. Quaternion.prototype.multiply = function (q1) {
  4681. var result = new Quaternion(0, 0, 0, 1.0);
  4682. this.multiplyToRef(q1, result);
  4683. return result;
  4684. };
  4685. /**
  4686. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4687. * @param q1 defines the second operand
  4688. * @param result defines the target quaternion
  4689. * @returns the current quaternion
  4690. */
  4691. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4692. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4693. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4694. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4695. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4696. result.copyFromFloats(x, y, z, w);
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4701. * @param q1 defines the second operand
  4702. * @returns the currentupdated quaternion
  4703. */
  4704. Quaternion.prototype.multiplyInPlace = function (q1) {
  4705. this.multiplyToRef(q1, this);
  4706. return this;
  4707. };
  4708. /**
  4709. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4710. * @param ref defines the target quaternion
  4711. * @returns the current quaternion
  4712. */
  4713. Quaternion.prototype.conjugateToRef = function (ref) {
  4714. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4715. return this;
  4716. };
  4717. /**
  4718. * Conjugates in place (1-q) the current quaternion
  4719. * @returns the current updated quaternion
  4720. */
  4721. Quaternion.prototype.conjugateInPlace = function () {
  4722. this.x *= -1;
  4723. this.y *= -1;
  4724. this.z *= -1;
  4725. return this;
  4726. };
  4727. /**
  4728. * Conjugates in place (1-q) the current quaternion
  4729. * @returns a new quaternion
  4730. */
  4731. Quaternion.prototype.conjugate = function () {
  4732. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4733. return result;
  4734. };
  4735. /**
  4736. * Gets length of current quaternion
  4737. * @returns the quaternion length (float)
  4738. */
  4739. Quaternion.prototype.length = function () {
  4740. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4741. };
  4742. /**
  4743. * Normalize in place the current quaternion
  4744. * @returns the current updated quaternion
  4745. */
  4746. Quaternion.prototype.normalize = function () {
  4747. var length = 1.0 / this.length();
  4748. this.x *= length;
  4749. this.y *= length;
  4750. this.z *= length;
  4751. this.w *= length;
  4752. return this;
  4753. };
  4754. /**
  4755. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4756. * @param order is a reserved parameter and is ignore for now
  4757. * @returns a new Vector3 containing the Euler angles
  4758. */
  4759. Quaternion.prototype.toEulerAngles = function (order) {
  4760. if (order === void 0) { order = "YZX"; }
  4761. var result = Vector3.Zero();
  4762. this.toEulerAnglesToRef(result, order);
  4763. return result;
  4764. };
  4765. /**
  4766. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4767. * @param result defines the vector which will be filled with the Euler angles
  4768. * @param order is a reserved parameter and is ignore for now
  4769. * @returns the current unchanged quaternion
  4770. */
  4771. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4772. if (order === void 0) { order = "YZX"; }
  4773. var qz = this.z;
  4774. var qx = this.x;
  4775. var qy = this.y;
  4776. var qw = this.w;
  4777. var sqw = qw * qw;
  4778. var sqz = qz * qz;
  4779. var sqx = qx * qx;
  4780. var sqy = qy * qy;
  4781. var zAxisY = qy * qz - qx * qw;
  4782. var limit = .4999999;
  4783. if (zAxisY < -limit) {
  4784. result.y = 2 * Math.atan2(qy, qw);
  4785. result.x = Math.PI / 2;
  4786. result.z = 0;
  4787. }
  4788. else if (zAxisY > limit) {
  4789. result.y = 2 * Math.atan2(qy, qw);
  4790. result.x = -Math.PI / 2;
  4791. result.z = 0;
  4792. }
  4793. else {
  4794. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4795. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4796. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4797. }
  4798. return this;
  4799. };
  4800. /**
  4801. * Updates the given rotation matrix with the current quaternion values
  4802. * @param result defines the target matrix
  4803. * @returns the current unchanged quaternion
  4804. */
  4805. Quaternion.prototype.toRotationMatrix = function (result) {
  4806. var xx = this.x * this.x;
  4807. var yy = this.y * this.y;
  4808. var zz = this.z * this.z;
  4809. var xy = this.x * this.y;
  4810. var zw = this.z * this.w;
  4811. var zx = this.z * this.x;
  4812. var yw = this.y * this.w;
  4813. var yz = this.y * this.z;
  4814. var xw = this.x * this.w;
  4815. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4816. result.m[1] = 2.0 * (xy + zw);
  4817. result.m[2] = 2.0 * (zx - yw);
  4818. result.m[3] = 0;
  4819. result.m[4] = 2.0 * (xy - zw);
  4820. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4821. result.m[6] = 2.0 * (yz + xw);
  4822. result.m[7] = 0;
  4823. result.m[8] = 2.0 * (zx + yw);
  4824. result.m[9] = 2.0 * (yz - xw);
  4825. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4826. result.m[11] = 0;
  4827. result.m[12] = 0;
  4828. result.m[13] = 0;
  4829. result.m[14] = 0;
  4830. result.m[15] = 1.0;
  4831. result._markAsUpdated();
  4832. return this;
  4833. };
  4834. /**
  4835. * Updates the current quaternion from the given rotation matrix values
  4836. * @param matrix defines the source matrix
  4837. * @returns the current updated quaternion
  4838. */
  4839. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4840. Quaternion.FromRotationMatrixToRef(matrix, this);
  4841. return this;
  4842. };
  4843. // Statics
  4844. /**
  4845. * Creates a new quaternion from a rotation matrix
  4846. * @param matrix defines the source matrix
  4847. * @returns a new quaternion created from the given rotation matrix values
  4848. */
  4849. Quaternion.FromRotationMatrix = function (matrix) {
  4850. var result = new Quaternion();
  4851. Quaternion.FromRotationMatrixToRef(matrix, result);
  4852. return result;
  4853. };
  4854. /**
  4855. * Updates the given quaternion with the given rotation matrix values
  4856. * @param matrix defines the source matrix
  4857. * @param result defines the target quaternion
  4858. */
  4859. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4860. var data = matrix.m;
  4861. var m11 = data[0], m12 = data[4], m13 = data[8];
  4862. var m21 = data[1], m22 = data[5], m23 = data[9];
  4863. var m31 = data[2], m32 = data[6], m33 = data[10];
  4864. var trace = m11 + m22 + m33;
  4865. var s;
  4866. if (trace > 0) {
  4867. s = 0.5 / Math.sqrt(trace + 1.0);
  4868. result.w = 0.25 / s;
  4869. result.x = (m32 - m23) * s;
  4870. result.y = (m13 - m31) * s;
  4871. result.z = (m21 - m12) * s;
  4872. }
  4873. else if (m11 > m22 && m11 > m33) {
  4874. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4875. result.w = (m32 - m23) / s;
  4876. result.x = 0.25 * s;
  4877. result.y = (m12 + m21) / s;
  4878. result.z = (m13 + m31) / s;
  4879. }
  4880. else if (m22 > m33) {
  4881. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4882. result.w = (m13 - m31) / s;
  4883. result.x = (m12 + m21) / s;
  4884. result.y = 0.25 * s;
  4885. result.z = (m23 + m32) / s;
  4886. }
  4887. else {
  4888. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4889. result.w = (m21 - m12) / s;
  4890. result.x = (m13 + m31) / s;
  4891. result.y = (m23 + m32) / s;
  4892. result.z = 0.25 * s;
  4893. }
  4894. };
  4895. /**
  4896. * Returns the dot product (float) between the quaternions "left" and "right"
  4897. * @param left defines the left operand
  4898. * @param right defines the right operand
  4899. * @returns the dot product
  4900. */
  4901. Quaternion.Dot = function (left, right) {
  4902. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4903. };
  4904. /**
  4905. * Checks if the two quaternions are close to each other
  4906. * @param quat0 defines the first quaternion to check
  4907. * @param quat1 defines the second quaternion to check
  4908. * @returns true if the two quaternions are close to each other
  4909. */
  4910. Quaternion.AreClose = function (quat0, quat1) {
  4911. var dot = Quaternion.Dot(quat0, quat1);
  4912. return dot >= 0;
  4913. };
  4914. /**
  4915. * Creates an empty quaternion
  4916. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4917. */
  4918. Quaternion.Zero = function () {
  4919. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4920. };
  4921. /**
  4922. * Inverse a given quaternion
  4923. * @param q defines the source quaternion
  4924. * @returns a new quaternion as the inverted current quaternion
  4925. */
  4926. Quaternion.Inverse = function (q) {
  4927. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4928. };
  4929. /**
  4930. * Creates an identity quaternion
  4931. * @returns the identity quaternion
  4932. */
  4933. Quaternion.Identity = function () {
  4934. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4935. };
  4936. /**
  4937. * Gets a boolean indicating if the given quaternion is identity
  4938. * @param quaternion defines the quaternion to check
  4939. * @returns true if the quaternion is identity
  4940. */
  4941. Quaternion.IsIdentity = function (quaternion) {
  4942. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4943. };
  4944. /**
  4945. * Creates a quaternion from a rotation around an axis
  4946. * @param axis defines the axis to use
  4947. * @param angle defines the angle to use
  4948. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4949. */
  4950. Quaternion.RotationAxis = function (axis, angle) {
  4951. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4952. };
  4953. /**
  4954. * Creates a rotation around an axis and stores it into the given quaternion
  4955. * @param axis defines the axis to use
  4956. * @param angle defines the angle to use
  4957. * @param result defines the target quaternion
  4958. * @returns the target quaternion
  4959. */
  4960. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4961. var sin = Math.sin(angle / 2);
  4962. axis.normalize();
  4963. result.w = Math.cos(angle / 2);
  4964. result.x = axis.x * sin;
  4965. result.y = axis.y * sin;
  4966. result.z = axis.z * sin;
  4967. return result;
  4968. };
  4969. /**
  4970. * Creates a new quaternion from data stored into an array
  4971. * @param array defines the data source
  4972. * @param offset defines the offset in the source array where the data starts
  4973. * @returns a new quaternion
  4974. */
  4975. Quaternion.FromArray = function (array, offset) {
  4976. if (!offset) {
  4977. offset = 0;
  4978. }
  4979. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4980. };
  4981. /**
  4982. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4983. * @param yaw defines the rotation around Y axis
  4984. * @param pitch defines the rotation around X axis
  4985. * @param roll defines the rotation around Z axis
  4986. * @returns the new quaternion
  4987. */
  4988. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4989. var q = new Quaternion();
  4990. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4991. return q;
  4992. };
  4993. /**
  4994. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4995. * @param yaw defines the rotation around Y axis
  4996. * @param pitch defines the rotation around X axis
  4997. * @param roll defines the rotation around Z axis
  4998. * @param result defines the target quaternion
  4999. */
  5000. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5001. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5002. var halfRoll = roll * 0.5;
  5003. var halfPitch = pitch * 0.5;
  5004. var halfYaw = yaw * 0.5;
  5005. var sinRoll = Math.sin(halfRoll);
  5006. var cosRoll = Math.cos(halfRoll);
  5007. var sinPitch = Math.sin(halfPitch);
  5008. var cosPitch = Math.cos(halfPitch);
  5009. var sinYaw = Math.sin(halfYaw);
  5010. var cosYaw = Math.cos(halfYaw);
  5011. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5012. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5013. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5014. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5015. };
  5016. /**
  5017. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5018. * @param alpha defines the rotation around first axis
  5019. * @param beta defines the rotation around second axis
  5020. * @param gamma defines the rotation around third axis
  5021. * @returns the new quaternion
  5022. */
  5023. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5024. var result = new Quaternion();
  5025. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5026. return result;
  5027. };
  5028. /**
  5029. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5030. * @param alpha defines the rotation around first axis
  5031. * @param beta defines the rotation around second axis
  5032. * @param gamma defines the rotation around third axis
  5033. * @param result defines the target quaternion
  5034. */
  5035. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5036. // Produces a quaternion from Euler angles in the z-x-z orientation
  5037. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5038. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5039. var halfBeta = beta * 0.5;
  5040. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5041. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5042. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5043. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5044. };
  5045. /**
  5046. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5047. * @param axis1 defines the first axis
  5048. * @param axis2 defines the second axis
  5049. * @param axis3 defines the third axis
  5050. * @returns the new quaternion
  5051. */
  5052. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5053. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5054. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5055. return quat;
  5056. };
  5057. /**
  5058. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5059. * @param axis1 defines the first axis
  5060. * @param axis2 defines the second axis
  5061. * @param axis3 defines the third axis
  5062. * @param ref defines the target quaternion
  5063. */
  5064. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5065. var rotMat = MathTmp.Matrix[0];
  5066. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5067. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5068. };
  5069. /**
  5070. * Interpolates between two quaternions
  5071. * @param left defines first quaternion
  5072. * @param right defines second quaternion
  5073. * @param amount defines the gradient to use
  5074. * @returns the new interpolated quaternion
  5075. */
  5076. Quaternion.Slerp = function (left, right, amount) {
  5077. var result = Quaternion.Identity();
  5078. Quaternion.SlerpToRef(left, right, amount, result);
  5079. return result;
  5080. };
  5081. /**
  5082. * Interpolates between two quaternions and stores it into a target quaternion
  5083. * @param left defines first quaternion
  5084. * @param right defines second quaternion
  5085. * @param amount defines the gradient to use
  5086. * @param result defines the target quaternion
  5087. */
  5088. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5089. var num2;
  5090. var num3;
  5091. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5092. var flag = false;
  5093. if (num4 < 0) {
  5094. flag = true;
  5095. num4 = -num4;
  5096. }
  5097. if (num4 > 0.999999) {
  5098. num3 = 1 - amount;
  5099. num2 = flag ? -amount : amount;
  5100. }
  5101. else {
  5102. var num5 = Math.acos(num4);
  5103. var num6 = (1.0 / Math.sin(num5));
  5104. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5105. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5106. }
  5107. result.x = (num3 * left.x) + (num2 * right.x);
  5108. result.y = (num3 * left.y) + (num2 * right.y);
  5109. result.z = (num3 * left.z) + (num2 * right.z);
  5110. result.w = (num3 * left.w) + (num2 * right.w);
  5111. };
  5112. /**
  5113. * Interpolate between two quaternions using Hermite interpolation
  5114. * @param value1 defines first quaternion
  5115. * @param tangent1 defines the incoming tangent
  5116. * @param value2 defines second quaternion
  5117. * @param tangent2 defines the outgoing tangent
  5118. * @param amount defines the target quaternion
  5119. * @returns the new interpolated quaternion
  5120. */
  5121. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5122. var squared = amount * amount;
  5123. var cubed = amount * squared;
  5124. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5125. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5126. var part3 = (cubed - (2.0 * squared)) + amount;
  5127. var part4 = cubed - squared;
  5128. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5129. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5130. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5131. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5132. return new Quaternion(x, y, z, w);
  5133. };
  5134. return Quaternion;
  5135. }());
  5136. BABYLON.Quaternion = Quaternion;
  5137. /**
  5138. * Class used to store matrix data (4x4)
  5139. */
  5140. var Matrix = /** @class */ (function () {
  5141. /**
  5142. * Creates an empty matrix (filled with zeros)
  5143. */
  5144. function Matrix() {
  5145. this._isIdentity = false;
  5146. this._isIdentityDirty = true;
  5147. /**
  5148. * Gets or sets the internal data of the matrix
  5149. */
  5150. this.m = new Float32Array(16);
  5151. this._markAsUpdated();
  5152. }
  5153. /** @hidden */
  5154. Matrix.prototype._markAsUpdated = function () {
  5155. this.updateFlag = Matrix._updateFlagSeed++;
  5156. this._isIdentityDirty = true;
  5157. };
  5158. // Properties
  5159. /**
  5160. * Check if the current matrix is indentity
  5161. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5162. * @returns true is the matrix is the identity matrix
  5163. */
  5164. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5165. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5166. if (this._isIdentityDirty) {
  5167. this._isIdentityDirty = false;
  5168. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5169. this._isIdentity = false;
  5170. }
  5171. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5172. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5173. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5174. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5175. this._isIdentity = false;
  5176. }
  5177. else {
  5178. this._isIdentity = true;
  5179. }
  5180. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5181. this._isIdentity = false;
  5182. }
  5183. }
  5184. return this._isIdentity;
  5185. };
  5186. /**
  5187. * Gets the determinant of the matrix
  5188. * @returns the matrix determinant
  5189. */
  5190. Matrix.prototype.determinant = function () {
  5191. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5192. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5193. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5194. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5195. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5196. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5197. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5198. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5199. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5200. };
  5201. // Methods
  5202. /**
  5203. * Returns the matrix as a Float32Array
  5204. * @returns the matrix underlying array
  5205. */
  5206. Matrix.prototype.toArray = function () {
  5207. return this.m;
  5208. };
  5209. /**
  5210. * Returns the matrix as a Float32Array
  5211. * @returns the matrix underlying array.
  5212. */
  5213. Matrix.prototype.asArray = function () {
  5214. return this.toArray();
  5215. };
  5216. /**
  5217. * Inverts the current matrix in place
  5218. * @returns the current inverted matrix
  5219. */
  5220. Matrix.prototype.invert = function () {
  5221. this.invertToRef(this);
  5222. return this;
  5223. };
  5224. /**
  5225. * Sets all the matrix elements to zero
  5226. * @returns the current matrix
  5227. */
  5228. Matrix.prototype.reset = function () {
  5229. for (var index = 0; index < 16; index++) {
  5230. this.m[index] = 0.0;
  5231. }
  5232. this._markAsUpdated();
  5233. return this;
  5234. };
  5235. /**
  5236. * Adds the current matrix with a second one
  5237. * @param other defines the matrix to add
  5238. * @returns a new matrix as the addition of the current matrix and the given one
  5239. */
  5240. Matrix.prototype.add = function (other) {
  5241. var result = new Matrix();
  5242. this.addToRef(other, result);
  5243. return result;
  5244. };
  5245. /**
  5246. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5247. * @param other defines the matrix to add
  5248. * @param result defines the target matrix
  5249. * @returns the current matrix
  5250. */
  5251. Matrix.prototype.addToRef = function (other, result) {
  5252. for (var index = 0; index < 16; index++) {
  5253. result.m[index] = this.m[index] + other.m[index];
  5254. }
  5255. result._markAsUpdated();
  5256. return this;
  5257. };
  5258. /**
  5259. * Adds in place the given matrix to the current matrix
  5260. * @param other defines the second operand
  5261. * @returns the current updated matrix
  5262. */
  5263. Matrix.prototype.addToSelf = function (other) {
  5264. for (var index = 0; index < 16; index++) {
  5265. this.m[index] += other.m[index];
  5266. }
  5267. this._markAsUpdated();
  5268. return this;
  5269. };
  5270. /**
  5271. * Sets the given matrix to the current inverted Matrix
  5272. * @param other defines the target matrix
  5273. * @returns the unmodified current matrix
  5274. */
  5275. Matrix.prototype.invertToRef = function (other) {
  5276. var l1 = this.m[0];
  5277. var l2 = this.m[1];
  5278. var l3 = this.m[2];
  5279. var l4 = this.m[3];
  5280. var l5 = this.m[4];
  5281. var l6 = this.m[5];
  5282. var l7 = this.m[6];
  5283. var l8 = this.m[7];
  5284. var l9 = this.m[8];
  5285. var l10 = this.m[9];
  5286. var l11 = this.m[10];
  5287. var l12 = this.m[11];
  5288. var l13 = this.m[12];
  5289. var l14 = this.m[13];
  5290. var l15 = this.m[14];
  5291. var l16 = this.m[15];
  5292. var l17 = (l11 * l16) - (l12 * l15);
  5293. var l18 = (l10 * l16) - (l12 * l14);
  5294. var l19 = (l10 * l15) - (l11 * l14);
  5295. var l20 = (l9 * l16) - (l12 * l13);
  5296. var l21 = (l9 * l15) - (l11 * l13);
  5297. var l22 = (l9 * l14) - (l10 * l13);
  5298. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5299. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5300. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5301. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5302. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5303. var l28 = (l7 * l16) - (l8 * l15);
  5304. var l29 = (l6 * l16) - (l8 * l14);
  5305. var l30 = (l6 * l15) - (l7 * l14);
  5306. var l31 = (l5 * l16) - (l8 * l13);
  5307. var l32 = (l5 * l15) - (l7 * l13);
  5308. var l33 = (l5 * l14) - (l6 * l13);
  5309. var l34 = (l7 * l12) - (l8 * l11);
  5310. var l35 = (l6 * l12) - (l8 * l10);
  5311. var l36 = (l6 * l11) - (l7 * l10);
  5312. var l37 = (l5 * l12) - (l8 * l9);
  5313. var l38 = (l5 * l11) - (l7 * l9);
  5314. var l39 = (l5 * l10) - (l6 * l9);
  5315. other.m[0] = l23 * l27;
  5316. other.m[4] = l24 * l27;
  5317. other.m[8] = l25 * l27;
  5318. other.m[12] = l26 * l27;
  5319. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5320. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5321. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5322. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5323. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5324. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5325. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5326. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5327. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5328. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5329. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5330. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5331. other._markAsUpdated();
  5332. return this;
  5333. };
  5334. /**
  5335. * Inserts the translation vector (using 3 floats) in the current matrix
  5336. * @param x defines the 1st component of the translation
  5337. * @param y defines the 2nd component of the translation
  5338. * @param z defines the 3rd component of the translation
  5339. * @returns the current updated matrix
  5340. */
  5341. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5342. this.m[12] = x;
  5343. this.m[13] = y;
  5344. this.m[14] = z;
  5345. this._markAsUpdated();
  5346. return this;
  5347. };
  5348. /**
  5349. * Inserts the translation vector in the current matrix
  5350. * @param vector3 defines the translation to insert
  5351. * @returns the current updated matrix
  5352. */
  5353. Matrix.prototype.setTranslation = function (vector3) {
  5354. this.m[12] = vector3.x;
  5355. this.m[13] = vector3.y;
  5356. this.m[14] = vector3.z;
  5357. this._markAsUpdated();
  5358. return this;
  5359. };
  5360. /**
  5361. * Gets the translation value of the current matrix
  5362. * @returns a new Vector3 as the extracted translation from the matrix
  5363. */
  5364. Matrix.prototype.getTranslation = function () {
  5365. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5366. };
  5367. /**
  5368. * Fill a Vector3 with the extracted translation from the matrix
  5369. * @param result defines the Vector3 where to store the translation
  5370. * @returns the current matrix
  5371. */
  5372. Matrix.prototype.getTranslationToRef = function (result) {
  5373. result.x = this.m[12];
  5374. result.y = this.m[13];
  5375. result.z = this.m[14];
  5376. return this;
  5377. };
  5378. /**
  5379. * Remove rotation and scaling part from the matrix
  5380. * @returns the updated matrix
  5381. */
  5382. Matrix.prototype.removeRotationAndScaling = function () {
  5383. this.setRowFromFloats(0, 1, 0, 0, 0);
  5384. this.setRowFromFloats(1, 0, 1, 0, 0);
  5385. this.setRowFromFloats(2, 0, 0, 1, 0);
  5386. return this;
  5387. };
  5388. /**
  5389. * Multiply two matrices
  5390. * @param other defines the second operand
  5391. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5392. */
  5393. Matrix.prototype.multiply = function (other) {
  5394. var result = new Matrix();
  5395. this.multiplyToRef(other, result);
  5396. return result;
  5397. };
  5398. /**
  5399. * Copy the current matrix from the given one
  5400. * @param other defines the source matrix
  5401. * @returns the current updated matrix
  5402. */
  5403. Matrix.prototype.copyFrom = function (other) {
  5404. for (var index = 0; index < 16; index++) {
  5405. this.m[index] = other.m[index];
  5406. }
  5407. this._markAsUpdated();
  5408. return this;
  5409. };
  5410. /**
  5411. * Populates the given array from the starting index with the current matrix values
  5412. * @param array defines the target array
  5413. * @param offset defines the offset in the target array where to start storing values
  5414. * @returns the current matrix
  5415. */
  5416. Matrix.prototype.copyToArray = function (array, offset) {
  5417. if (offset === void 0) { offset = 0; }
  5418. for (var index = 0; index < 16; index++) {
  5419. array[offset + index] = this.m[index];
  5420. }
  5421. return this;
  5422. };
  5423. /**
  5424. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5425. * @param other defines the second operand
  5426. * @param result defines the matrix where to store the multiplication
  5427. * @returns the current matrix
  5428. */
  5429. Matrix.prototype.multiplyToRef = function (other, result) {
  5430. this.multiplyToArray(other, result.m, 0);
  5431. result._markAsUpdated();
  5432. return this;
  5433. };
  5434. /**
  5435. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5436. * @param other defines the second operand
  5437. * @param result defines the array where to store the multiplication
  5438. * @param offset defines the offset in the target array where to start storing values
  5439. * @returns the current matrix
  5440. */
  5441. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5442. var tm0 = this.m[0];
  5443. var tm1 = this.m[1];
  5444. var tm2 = this.m[2];
  5445. var tm3 = this.m[3];
  5446. var tm4 = this.m[4];
  5447. var tm5 = this.m[5];
  5448. var tm6 = this.m[6];
  5449. var tm7 = this.m[7];
  5450. var tm8 = this.m[8];
  5451. var tm9 = this.m[9];
  5452. var tm10 = this.m[10];
  5453. var tm11 = this.m[11];
  5454. var tm12 = this.m[12];
  5455. var tm13 = this.m[13];
  5456. var tm14 = this.m[14];
  5457. var tm15 = this.m[15];
  5458. var om0 = other.m[0];
  5459. var om1 = other.m[1];
  5460. var om2 = other.m[2];
  5461. var om3 = other.m[3];
  5462. var om4 = other.m[4];
  5463. var om5 = other.m[5];
  5464. var om6 = other.m[6];
  5465. var om7 = other.m[7];
  5466. var om8 = other.m[8];
  5467. var om9 = other.m[9];
  5468. var om10 = other.m[10];
  5469. var om11 = other.m[11];
  5470. var om12 = other.m[12];
  5471. var om13 = other.m[13];
  5472. var om14 = other.m[14];
  5473. var om15 = other.m[15];
  5474. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5475. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5476. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5477. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5478. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5479. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5480. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5481. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5482. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5483. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5484. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5485. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5486. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5487. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5488. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5489. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5490. return this;
  5491. };
  5492. /**
  5493. * Check equality between this matrix and a second one
  5494. * @param value defines the second matrix to compare
  5495. * @returns true is the current matrix and the given one values are strictly equal
  5496. */
  5497. Matrix.prototype.equals = function (value) {
  5498. return value &&
  5499. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5500. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5501. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5502. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5503. };
  5504. /**
  5505. * Clone the current matrix
  5506. * @returns a new matrix from the current matrix
  5507. */
  5508. Matrix.prototype.clone = function () {
  5509. 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]);
  5510. };
  5511. /**
  5512. * Returns the name of the current matrix class
  5513. * @returns the string "Matrix"
  5514. */
  5515. Matrix.prototype.getClassName = function () {
  5516. return "Matrix";
  5517. };
  5518. /**
  5519. * Gets the hash code of the current matrix
  5520. * @returns the hash code
  5521. */
  5522. Matrix.prototype.getHashCode = function () {
  5523. var hash = this.m[0] || 0;
  5524. for (var i = 1; i < 16; i++) {
  5525. hash = (hash * 397) ^ (this.m[i] || 0);
  5526. }
  5527. return hash;
  5528. };
  5529. /**
  5530. * Decomposes the current Matrix into a translation, rotation and scaling components
  5531. * @param scale defines the scale vector3 given as a reference to update
  5532. * @param rotation defines the rotation quaternion given as a reference to update
  5533. * @param translation defines the translation vector3 given as a reference to update
  5534. * @returns true if operation was successful
  5535. */
  5536. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5537. if (translation) {
  5538. translation.x = this.m[12];
  5539. translation.y = this.m[13];
  5540. translation.z = this.m[14];
  5541. }
  5542. scale = scale || MathTmp.Vector3[0];
  5543. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5544. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5545. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5546. if (this.determinant() <= 0) {
  5547. scale.y *= -1;
  5548. }
  5549. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5550. if (rotation) {
  5551. rotation.x = 0;
  5552. rotation.y = 0;
  5553. rotation.z = 0;
  5554. rotation.w = 1;
  5555. }
  5556. return false;
  5557. }
  5558. if (rotation) {
  5559. 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]);
  5560. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5561. }
  5562. return true;
  5563. };
  5564. /**
  5565. * Gets specific row of the matrix
  5566. * @param index defines the number of the row to get
  5567. * @returns the index-th row of the current matrix as a new Vector4
  5568. */
  5569. Matrix.prototype.getRow = function (index) {
  5570. if (index < 0 || index > 3) {
  5571. return null;
  5572. }
  5573. var i = index * 4;
  5574. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5575. };
  5576. /**
  5577. * Sets the index-th row of the current matrix to the vector4 values
  5578. * @param index defines the number of the row to set
  5579. * @param row defines the target vector4
  5580. * @returns the updated current matrix
  5581. */
  5582. Matrix.prototype.setRow = function (index, row) {
  5583. if (index < 0 || index > 3) {
  5584. return this;
  5585. }
  5586. var i = index * 4;
  5587. this.m[i + 0] = row.x;
  5588. this.m[i + 1] = row.y;
  5589. this.m[i + 2] = row.z;
  5590. this.m[i + 3] = row.w;
  5591. this._markAsUpdated();
  5592. return this;
  5593. };
  5594. /**
  5595. * Compute the transpose of the matrix
  5596. * @returns the new transposed matrix
  5597. */
  5598. Matrix.prototype.transpose = function () {
  5599. return Matrix.Transpose(this);
  5600. };
  5601. /**
  5602. * Compute the transpose of the matrix and store it in a given matrix
  5603. * @param result defines the target matrix
  5604. * @returns the current matrix
  5605. */
  5606. Matrix.prototype.transposeToRef = function (result) {
  5607. Matrix.TransposeToRef(this, result);
  5608. return this;
  5609. };
  5610. /**
  5611. * Sets the index-th row of the current matrix with the given 4 x float values
  5612. * @param index defines the row index
  5613. * @param x defines the x component to set
  5614. * @param y defines the y component to set
  5615. * @param z defines the z component to set
  5616. * @param w defines the w component to set
  5617. * @returns the updated current matrix
  5618. */
  5619. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5620. if (index < 0 || index > 3) {
  5621. return this;
  5622. }
  5623. var i = index * 4;
  5624. this.m[i + 0] = x;
  5625. this.m[i + 1] = y;
  5626. this.m[i + 2] = z;
  5627. this.m[i + 3] = w;
  5628. this._markAsUpdated();
  5629. return this;
  5630. };
  5631. /**
  5632. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5633. * @param scale defines the scale factor
  5634. * @returns a new matrix
  5635. */
  5636. Matrix.prototype.scale = function (scale) {
  5637. var result = new Matrix();
  5638. this.scaleToRef(scale, result);
  5639. return result;
  5640. };
  5641. /**
  5642. * Scale the current matrix values by a factor to a given result matrix
  5643. * @param scale defines the scale factor
  5644. * @param result defines the matrix to store the result
  5645. * @returns the current matrix
  5646. */
  5647. Matrix.prototype.scaleToRef = function (scale, result) {
  5648. for (var index = 0; index < 16; index++) {
  5649. result.m[index] = this.m[index] * scale;
  5650. }
  5651. result._markAsUpdated();
  5652. return this;
  5653. };
  5654. /**
  5655. * Scale the current matrix values by a factor and add the result to a given matrix
  5656. * @param scale defines the scale factor
  5657. * @param result defines the Matrix to store the result
  5658. * @returns the current matrix
  5659. */
  5660. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5661. for (var index = 0; index < 16; index++) {
  5662. result.m[index] += this.m[index] * scale;
  5663. }
  5664. result._markAsUpdated();
  5665. return this;
  5666. };
  5667. /**
  5668. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5669. * @param ref matrix to store the result
  5670. */
  5671. Matrix.prototype.toNormalMatrix = function (ref) {
  5672. this.invertToRef(ref);
  5673. ref.transpose();
  5674. var m = ref.m;
  5675. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5676. };
  5677. /**
  5678. * Gets only rotation part of the current matrix
  5679. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5680. */
  5681. Matrix.prototype.getRotationMatrix = function () {
  5682. var result = Matrix.Identity();
  5683. this.getRotationMatrixToRef(result);
  5684. return result;
  5685. };
  5686. /**
  5687. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5688. * @param result defines the target matrix to store data to
  5689. * @returns the current matrix
  5690. */
  5691. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5692. var m = this.m;
  5693. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5694. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5695. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5696. if (this.determinant() <= 0) {
  5697. sy *= -1;
  5698. }
  5699. if (sx === 0 || sy === 0 || sz === 0) {
  5700. Matrix.IdentityToRef(result);
  5701. }
  5702. else {
  5703. 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);
  5704. }
  5705. return this;
  5706. };
  5707. // Statics
  5708. /**
  5709. * Creates a matrix from an array
  5710. * @param array defines the source array
  5711. * @param offset defines an offset in the source array
  5712. * @returns a new Matrix set from the starting index of the given array
  5713. */
  5714. Matrix.FromArray = function (array, offset) {
  5715. var result = new Matrix();
  5716. if (!offset) {
  5717. offset = 0;
  5718. }
  5719. Matrix.FromArrayToRef(array, offset, result);
  5720. return result;
  5721. };
  5722. /**
  5723. * Copy the content of an array into a given matrix
  5724. * @param array defines the source array
  5725. * @param offset defines an offset in the source array
  5726. * @param result defines the target matrix
  5727. */
  5728. Matrix.FromArrayToRef = function (array, offset, result) {
  5729. for (var index = 0; index < 16; index++) {
  5730. result.m[index] = array[index + offset];
  5731. }
  5732. result._markAsUpdated();
  5733. };
  5734. /**
  5735. * Stores an array into a matrix after having multiplied each component by a given factor
  5736. * @param array defines the source array
  5737. * @param offset defines the offset in the source array
  5738. * @param scale defines the scaling factor
  5739. * @param result defines the target matrix
  5740. */
  5741. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5742. for (var index = 0; index < 16; index++) {
  5743. result.m[index] = array[index + offset] * scale;
  5744. }
  5745. result._markAsUpdated();
  5746. };
  5747. /**
  5748. * Stores a list of values (16) inside a given matrix
  5749. * @param initialM11 defines 1st value of 1st row
  5750. * @param initialM12 defines 2nd value of 1st row
  5751. * @param initialM13 defines 3rd value of 1st row
  5752. * @param initialM14 defines 4th value of 1st row
  5753. * @param initialM21 defines 1st value of 2nd row
  5754. * @param initialM22 defines 2nd value of 2nd row
  5755. * @param initialM23 defines 3rd value of 2nd row
  5756. * @param initialM24 defines 4th value of 2nd row
  5757. * @param initialM31 defines 1st value of 3rd row
  5758. * @param initialM32 defines 2nd value of 3rd row
  5759. * @param initialM33 defines 3rd value of 3rd row
  5760. * @param initialM34 defines 4th value of 3rd row
  5761. * @param initialM41 defines 1st value of 4th row
  5762. * @param initialM42 defines 2nd value of 4th row
  5763. * @param initialM43 defines 3rd value of 4th row
  5764. * @param initialM44 defines 4th value of 4th row
  5765. * @param result defines the target matrix
  5766. */
  5767. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5768. result.m[0] = initialM11;
  5769. result.m[1] = initialM12;
  5770. result.m[2] = initialM13;
  5771. result.m[3] = initialM14;
  5772. result.m[4] = initialM21;
  5773. result.m[5] = initialM22;
  5774. result.m[6] = initialM23;
  5775. result.m[7] = initialM24;
  5776. result.m[8] = initialM31;
  5777. result.m[9] = initialM32;
  5778. result.m[10] = initialM33;
  5779. result.m[11] = initialM34;
  5780. result.m[12] = initialM41;
  5781. result.m[13] = initialM42;
  5782. result.m[14] = initialM43;
  5783. result.m[15] = initialM44;
  5784. result._markAsUpdated();
  5785. };
  5786. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5787. /**
  5788. * Gets an identity matrix that must not be updated
  5789. */
  5790. get: function () {
  5791. return Matrix._identityReadOnly;
  5792. },
  5793. enumerable: true,
  5794. configurable: true
  5795. });
  5796. /**
  5797. * Creates new matrix from a list of values (16)
  5798. * @param initialM11 defines 1st value of 1st row
  5799. * @param initialM12 defines 2nd value of 1st row
  5800. * @param initialM13 defines 3rd value of 1st row
  5801. * @param initialM14 defines 4th value of 1st row
  5802. * @param initialM21 defines 1st value of 2nd row
  5803. * @param initialM22 defines 2nd value of 2nd row
  5804. * @param initialM23 defines 3rd value of 2nd row
  5805. * @param initialM24 defines 4th value of 2nd row
  5806. * @param initialM31 defines 1st value of 3rd row
  5807. * @param initialM32 defines 2nd value of 3rd row
  5808. * @param initialM33 defines 3rd value of 3rd row
  5809. * @param initialM34 defines 4th value of 3rd row
  5810. * @param initialM41 defines 1st value of 4th row
  5811. * @param initialM42 defines 2nd value of 4th row
  5812. * @param initialM43 defines 3rd value of 4th row
  5813. * @param initialM44 defines 4th value of 4th row
  5814. * @returns the new matrix
  5815. */
  5816. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5817. var result = new Matrix();
  5818. result.m[0] = initialM11;
  5819. result.m[1] = initialM12;
  5820. result.m[2] = initialM13;
  5821. result.m[3] = initialM14;
  5822. result.m[4] = initialM21;
  5823. result.m[5] = initialM22;
  5824. result.m[6] = initialM23;
  5825. result.m[7] = initialM24;
  5826. result.m[8] = initialM31;
  5827. result.m[9] = initialM32;
  5828. result.m[10] = initialM33;
  5829. result.m[11] = initialM34;
  5830. result.m[12] = initialM41;
  5831. result.m[13] = initialM42;
  5832. result.m[14] = initialM43;
  5833. result.m[15] = initialM44;
  5834. return result;
  5835. };
  5836. /**
  5837. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5838. * @param scale defines the scale vector3
  5839. * @param rotation defines the rotation quaternion
  5840. * @param translation defines the translation vector3
  5841. * @returns a new matrix
  5842. */
  5843. Matrix.Compose = function (scale, rotation, translation) {
  5844. var result = Matrix.Identity();
  5845. Matrix.ComposeToRef(scale, rotation, translation, result);
  5846. return result;
  5847. };
  5848. /**
  5849. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5850. * @param scale defines the scale vector3
  5851. * @param rotation defines the rotation quaternion
  5852. * @param translation defines the translation vector3
  5853. * @param result defines the target matrix
  5854. */
  5855. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5856. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5857. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5858. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5859. result.setTranslation(translation);
  5860. };
  5861. /**
  5862. * Creates a new identity matrix
  5863. * @returns a new identity matrix
  5864. */
  5865. Matrix.Identity = function () {
  5866. 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);
  5867. };
  5868. /**
  5869. * Creates a new identity matrix and stores the result in a given matrix
  5870. * @param result defines the target matrix
  5871. */
  5872. Matrix.IdentityToRef = function (result) {
  5873. 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);
  5874. };
  5875. /**
  5876. * Creates a new zero matrix
  5877. * @returns a new zero matrix
  5878. */
  5879. Matrix.Zero = function () {
  5880. 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);
  5881. };
  5882. /**
  5883. * Creates a new rotation matrix for "angle" radians around the X axis
  5884. * @param angle defines the angle (in radians) to use
  5885. * @return the new matrix
  5886. */
  5887. Matrix.RotationX = function (angle) {
  5888. var result = new Matrix();
  5889. Matrix.RotationXToRef(angle, result);
  5890. return result;
  5891. };
  5892. /**
  5893. * Creates a new matrix as the invert of a given matrix
  5894. * @param source defines the source matrix
  5895. * @returns the new matrix
  5896. */
  5897. Matrix.Invert = function (source) {
  5898. var result = new Matrix();
  5899. source.invertToRef(result);
  5900. return result;
  5901. };
  5902. /**
  5903. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5904. * @param angle defines the angle (in radians) to use
  5905. * @param result defines the target matrix
  5906. */
  5907. Matrix.RotationXToRef = function (angle, result) {
  5908. var s = Math.sin(angle);
  5909. var c = Math.cos(angle);
  5910. result.m[0] = 1.0;
  5911. result.m[15] = 1.0;
  5912. result.m[5] = c;
  5913. result.m[10] = c;
  5914. result.m[9] = -s;
  5915. result.m[6] = s;
  5916. result.m[1] = 0.0;
  5917. result.m[2] = 0.0;
  5918. result.m[3] = 0.0;
  5919. result.m[4] = 0.0;
  5920. result.m[7] = 0.0;
  5921. result.m[8] = 0.0;
  5922. result.m[11] = 0.0;
  5923. result.m[12] = 0.0;
  5924. result.m[13] = 0.0;
  5925. result.m[14] = 0.0;
  5926. result._markAsUpdated();
  5927. };
  5928. /**
  5929. * Creates a new rotation matrix for "angle" radians around the Y axis
  5930. * @param angle defines the angle (in radians) to use
  5931. * @return the new matrix
  5932. */
  5933. Matrix.RotationY = function (angle) {
  5934. var result = new Matrix();
  5935. Matrix.RotationYToRef(angle, result);
  5936. return result;
  5937. };
  5938. /**
  5939. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5940. * @param angle defines the angle (in radians) to use
  5941. * @param result defines the target matrix
  5942. */
  5943. Matrix.RotationYToRef = function (angle, result) {
  5944. var s = Math.sin(angle);
  5945. var c = Math.cos(angle);
  5946. result.m[5] = 1.0;
  5947. result.m[15] = 1.0;
  5948. result.m[0] = c;
  5949. result.m[2] = -s;
  5950. result.m[8] = s;
  5951. result.m[10] = c;
  5952. result.m[1] = 0.0;
  5953. result.m[3] = 0.0;
  5954. result.m[4] = 0.0;
  5955. result.m[6] = 0.0;
  5956. result.m[7] = 0.0;
  5957. result.m[9] = 0.0;
  5958. result.m[11] = 0.0;
  5959. result.m[12] = 0.0;
  5960. result.m[13] = 0.0;
  5961. result.m[14] = 0.0;
  5962. result._markAsUpdated();
  5963. };
  5964. /**
  5965. * Creates a new rotation matrix for "angle" radians around the Z axis
  5966. * @param angle defines the angle (in radians) to use
  5967. * @return the new matrix
  5968. */
  5969. Matrix.RotationZ = function (angle) {
  5970. var result = new Matrix();
  5971. Matrix.RotationZToRef(angle, result);
  5972. return result;
  5973. };
  5974. /**
  5975. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5976. * @param angle defines the angle (in radians) to use
  5977. * @param result defines the target matrix
  5978. */
  5979. Matrix.RotationZToRef = function (angle, result) {
  5980. var s = Math.sin(angle);
  5981. var c = Math.cos(angle);
  5982. result.m[10] = 1.0;
  5983. result.m[15] = 1.0;
  5984. result.m[0] = c;
  5985. result.m[1] = s;
  5986. result.m[4] = -s;
  5987. result.m[5] = c;
  5988. result.m[2] = 0.0;
  5989. result.m[3] = 0.0;
  5990. result.m[6] = 0.0;
  5991. result.m[7] = 0.0;
  5992. result.m[8] = 0.0;
  5993. result.m[9] = 0.0;
  5994. result.m[11] = 0.0;
  5995. result.m[12] = 0.0;
  5996. result.m[13] = 0.0;
  5997. result.m[14] = 0.0;
  5998. result._markAsUpdated();
  5999. };
  6000. /**
  6001. * Creates a new rotation matrix for "angle" radians around the given axis
  6002. * @param axis defines the axis to use
  6003. * @param angle defines the angle (in radians) to use
  6004. * @return the new matrix
  6005. */
  6006. Matrix.RotationAxis = function (axis, angle) {
  6007. var result = Matrix.Zero();
  6008. Matrix.RotationAxisToRef(axis, angle, result);
  6009. return result;
  6010. };
  6011. /**
  6012. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6013. * @param axis defines the axis to use
  6014. * @param angle defines the angle (in radians) to use
  6015. * @param result defines the target matrix
  6016. */
  6017. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6018. var s = Math.sin(-angle);
  6019. var c = Math.cos(-angle);
  6020. var c1 = 1 - c;
  6021. axis.normalize();
  6022. result.m[0] = (axis.x * axis.x) * c1 + c;
  6023. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6024. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6025. result.m[3] = 0.0;
  6026. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6027. result.m[5] = (axis.y * axis.y) * c1 + c;
  6028. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6029. result.m[7] = 0.0;
  6030. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6031. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6032. result.m[10] = (axis.z * axis.z) * c1 + c;
  6033. result.m[11] = 0.0;
  6034. result.m[15] = 1.0;
  6035. result._markAsUpdated();
  6036. };
  6037. /**
  6038. * Creates a rotation matrix
  6039. * @param yaw defines the yaw angle in radians (Y axis)
  6040. * @param pitch defines the pitch angle in radians (X axis)
  6041. * @param roll defines the roll angle in radians (X axis)
  6042. * @returns the new rotation matrix
  6043. */
  6044. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6045. var result = new Matrix();
  6046. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6047. return result;
  6048. };
  6049. /**
  6050. * Creates a rotation matrix and stores it in a given matrix
  6051. * @param yaw defines the yaw angle in radians (Y axis)
  6052. * @param pitch defines the pitch angle in radians (X axis)
  6053. * @param roll defines the roll angle in radians (X axis)
  6054. * @param result defines the target matrix
  6055. */
  6056. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6057. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6058. this._tempQuaternion.toRotationMatrix(result);
  6059. };
  6060. /**
  6061. * Creates a scaling matrix
  6062. * @param x defines the scale factor on X axis
  6063. * @param y defines the scale factor on Y axis
  6064. * @param z defines the scale factor on Z axis
  6065. * @returns the new matrix
  6066. */
  6067. Matrix.Scaling = function (x, y, z) {
  6068. var result = Matrix.Zero();
  6069. Matrix.ScalingToRef(x, y, z, result);
  6070. return result;
  6071. };
  6072. /**
  6073. * Creates a scaling matrix and stores it in a given matrix
  6074. * @param x defines the scale factor on X axis
  6075. * @param y defines the scale factor on Y axis
  6076. * @param z defines the scale factor on Z axis
  6077. * @param result defines the target matrix
  6078. */
  6079. Matrix.ScalingToRef = function (x, y, z, result) {
  6080. result.m[0] = x;
  6081. result.m[1] = 0.0;
  6082. result.m[2] = 0.0;
  6083. result.m[3] = 0.0;
  6084. result.m[4] = 0.0;
  6085. result.m[5] = y;
  6086. result.m[6] = 0.0;
  6087. result.m[7] = 0.0;
  6088. result.m[8] = 0.0;
  6089. result.m[9] = 0.0;
  6090. result.m[10] = z;
  6091. result.m[11] = 0.0;
  6092. result.m[12] = 0.0;
  6093. result.m[13] = 0.0;
  6094. result.m[14] = 0.0;
  6095. result.m[15] = 1.0;
  6096. result._markAsUpdated();
  6097. };
  6098. /**
  6099. * Creates a translation matrix
  6100. * @param x defines the translation on X axis
  6101. * @param y defines the translation on Y axis
  6102. * @param z defines the translationon Z axis
  6103. * @returns the new matrix
  6104. */
  6105. Matrix.Translation = function (x, y, z) {
  6106. var result = Matrix.Identity();
  6107. Matrix.TranslationToRef(x, y, z, result);
  6108. return result;
  6109. };
  6110. /**
  6111. * Creates a translation matrix and stores it in a given matrix
  6112. * @param x defines the translation on X axis
  6113. * @param y defines the translation on Y axis
  6114. * @param z defines the translationon Z axis
  6115. * @param result defines the target matrix
  6116. */
  6117. Matrix.TranslationToRef = function (x, y, z, result) {
  6118. 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);
  6119. };
  6120. /**
  6121. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6122. * @param startValue defines the start value
  6123. * @param endValue defines the end value
  6124. * @param gradient defines the gradient factor
  6125. * @returns the new matrix
  6126. */
  6127. Matrix.Lerp = function (startValue, endValue, gradient) {
  6128. var result = Matrix.Zero();
  6129. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6130. return result;
  6131. };
  6132. /**
  6133. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6134. * @param startValue defines the start value
  6135. * @param endValue defines the end value
  6136. * @param gradient defines the gradient factor
  6137. * @param result defines the Matrix object where to store data
  6138. */
  6139. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6140. for (var index = 0; index < 16; index++) {
  6141. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6142. }
  6143. result._markAsUpdated();
  6144. };
  6145. /**
  6146. * Builds a new matrix whose values are computed by:
  6147. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6148. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6149. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6150. * @param startValue defines the first matrix
  6151. * @param endValue defines the second matrix
  6152. * @param gradient defines the gradient between the two matrices
  6153. * @returns the new matrix
  6154. */
  6155. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6156. var result = Matrix.Zero();
  6157. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6158. return result;
  6159. };
  6160. /**
  6161. * Update a matrix to values which are computed by:
  6162. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6163. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6164. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6165. * @param startValue defines the first matrix
  6166. * @param endValue defines the second matrix
  6167. * @param gradient defines the gradient between the two matrices
  6168. * @param result defines the target matrix
  6169. */
  6170. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6171. var startScale = MathTmp.Vector3[0];
  6172. var startRotation = MathTmp.Quaternion[0];
  6173. var startTranslation = MathTmp.Vector3[1];
  6174. startValue.decompose(startScale, startRotation, startTranslation);
  6175. var endScale = MathTmp.Vector3[2];
  6176. var endRotation = MathTmp.Quaternion[1];
  6177. var endTranslation = MathTmp.Vector3[3];
  6178. endValue.decompose(endScale, endRotation, endTranslation);
  6179. var resultScale = MathTmp.Vector3[4];
  6180. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6181. var resultRotation = MathTmp.Quaternion[2];
  6182. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6183. var resultTranslation = MathTmp.Vector3[5];
  6184. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6185. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6186. };
  6187. /**
  6188. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6189. * This function works in left handed mode
  6190. * @param eye defines the final position of the entity
  6191. * @param target defines where the entity should look at
  6192. * @param up defines the up vector for the entity
  6193. * @returns the new matrix
  6194. */
  6195. Matrix.LookAtLH = function (eye, target, up) {
  6196. var result = Matrix.Zero();
  6197. Matrix.LookAtLHToRef(eye, target, up, result);
  6198. return result;
  6199. };
  6200. /**
  6201. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6202. * This function works in left handed mode
  6203. * @param eye defines the final position of the entity
  6204. * @param target defines where the entity should look at
  6205. * @param up defines the up vector for the entity
  6206. * @param result defines the target matrix
  6207. */
  6208. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6209. // Z axis
  6210. target.subtractToRef(eye, this._zAxis);
  6211. this._zAxis.normalize();
  6212. // X axis
  6213. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6214. if (this._xAxis.lengthSquared() === 0) {
  6215. this._xAxis.x = 1.0;
  6216. }
  6217. else {
  6218. this._xAxis.normalize();
  6219. }
  6220. // Y axis
  6221. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6222. this._yAxis.normalize();
  6223. // Eye angles
  6224. var ex = -Vector3.Dot(this._xAxis, eye);
  6225. var ey = -Vector3.Dot(this._yAxis, eye);
  6226. var ez = -Vector3.Dot(this._zAxis, eye);
  6227. 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);
  6228. };
  6229. /**
  6230. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6231. * This function works in right handed mode
  6232. * @param eye defines the final position of the entity
  6233. * @param target defines where the entity should look at
  6234. * @param up defines the up vector for the entity
  6235. * @returns the new matrix
  6236. */
  6237. Matrix.LookAtRH = function (eye, target, up) {
  6238. var result = Matrix.Zero();
  6239. Matrix.LookAtRHToRef(eye, target, up, result);
  6240. return result;
  6241. };
  6242. /**
  6243. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6244. * This function works in right handed mode
  6245. * @param eye defines the final position of the entity
  6246. * @param target defines where the entity should look at
  6247. * @param up defines the up vector for the entity
  6248. * @param result defines the target matrix
  6249. */
  6250. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6251. // Z axis
  6252. eye.subtractToRef(target, this._zAxis);
  6253. this._zAxis.normalize();
  6254. // X axis
  6255. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6256. if (this._xAxis.lengthSquared() === 0) {
  6257. this._xAxis.x = 1.0;
  6258. }
  6259. else {
  6260. this._xAxis.normalize();
  6261. }
  6262. // Y axis
  6263. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6264. this._yAxis.normalize();
  6265. // Eye angles
  6266. var ex = -Vector3.Dot(this._xAxis, eye);
  6267. var ey = -Vector3.Dot(this._yAxis, eye);
  6268. var ez = -Vector3.Dot(this._zAxis, eye);
  6269. 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);
  6270. };
  6271. /**
  6272. * Create a left-handed orthographic projection matrix
  6273. * @param width defines the viewport width
  6274. * @param height defines the viewport height
  6275. * @param znear defines the near clip plane
  6276. * @param zfar defines the far clip plane
  6277. * @returns a new matrix as a left-handed orthographic projection matrix
  6278. */
  6279. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6280. var matrix = Matrix.Zero();
  6281. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6282. return matrix;
  6283. };
  6284. /**
  6285. * Store a left-handed orthographic projection to a given matrix
  6286. * @param width defines the viewport width
  6287. * @param height defines the viewport height
  6288. * @param znear defines the near clip plane
  6289. * @param zfar defines the far clip plane
  6290. * @param result defines the target matrix
  6291. */
  6292. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6293. var n = znear;
  6294. var f = zfar;
  6295. var a = 2.0 / width;
  6296. var b = 2.0 / height;
  6297. var c = 2.0 / (f - n);
  6298. var d = -(f + n) / (f - n);
  6299. 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);
  6300. };
  6301. /**
  6302. * Create a left-handed orthographic projection matrix
  6303. * @param left defines the viewport left coordinate
  6304. * @param right defines the viewport right coordinate
  6305. * @param bottom defines the viewport bottom coordinate
  6306. * @param top defines the viewport top coordinate
  6307. * @param znear defines the near clip plane
  6308. * @param zfar defines the far clip plane
  6309. * @returns a new matrix as a left-handed orthographic projection matrix
  6310. */
  6311. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6312. var matrix = Matrix.Zero();
  6313. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6314. return matrix;
  6315. };
  6316. /**
  6317. * Stores a left-handed orthographic projection into a given matrix
  6318. * @param left defines the viewport left coordinate
  6319. * @param right defines the viewport right coordinate
  6320. * @param bottom defines the viewport bottom coordinate
  6321. * @param top defines the viewport top coordinate
  6322. * @param znear defines the near clip plane
  6323. * @param zfar defines the far clip plane
  6324. * @param result defines the target matrix
  6325. */
  6326. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6327. var n = znear;
  6328. var f = zfar;
  6329. var a = 2.0 / (right - left);
  6330. var b = 2.0 / (top - bottom);
  6331. var c = 2.0 / (f - n);
  6332. var d = -(f + n) / (f - n);
  6333. var i0 = (left + right) / (left - right);
  6334. var i1 = (top + bottom) / (bottom - top);
  6335. 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);
  6336. };
  6337. /**
  6338. * Creates a right-handed orthographic projection matrix
  6339. * @param left defines the viewport left coordinate
  6340. * @param right defines the viewport right coordinate
  6341. * @param bottom defines the viewport bottom coordinate
  6342. * @param top defines the viewport top coordinate
  6343. * @param znear defines the near clip plane
  6344. * @param zfar defines the far clip plane
  6345. * @returns a new matrix as a right-handed orthographic projection matrix
  6346. */
  6347. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6350. return matrix;
  6351. };
  6352. /**
  6353. * Stores a right-handed orthographic projection into a given matrix
  6354. * @param left defines the viewport left coordinate
  6355. * @param right defines the viewport right coordinate
  6356. * @param bottom defines the viewport bottom coordinate
  6357. * @param top defines the viewport top coordinate
  6358. * @param znear defines the near clip plane
  6359. * @param zfar defines the far clip plane
  6360. * @param result defines the target matrix
  6361. */
  6362. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6363. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6364. result.m[10] *= -1.0;
  6365. };
  6366. /**
  6367. * Creates a left-handed perspective projection matrix
  6368. * @param width defines the viewport width
  6369. * @param height defines the viewport height
  6370. * @param znear defines the near clip plane
  6371. * @param zfar defines the far clip plane
  6372. * @returns a new matrix as a left-handed perspective projection matrix
  6373. */
  6374. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6375. var matrix = Matrix.Zero();
  6376. var n = znear;
  6377. var f = zfar;
  6378. var a = 2.0 * n / width;
  6379. var b = 2.0 * n / height;
  6380. var c = (f + n) / (f - n);
  6381. var d = -2.0 * f * n / (f - n);
  6382. 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);
  6383. return matrix;
  6384. };
  6385. /**
  6386. * Creates a left-handed perspective projection matrix
  6387. * @param fov defines the horizontal field of view
  6388. * @param aspect defines the aspect ratio
  6389. * @param znear defines the near clip plane
  6390. * @param zfar defines the far clip plane
  6391. * @returns a new matrix as a left-handed perspective projection matrix
  6392. */
  6393. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6394. var matrix = Matrix.Zero();
  6395. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6396. return matrix;
  6397. };
  6398. /**
  6399. * Stores a left-handed perspective projection into a given matrix
  6400. * @param fov defines the horizontal field of view
  6401. * @param aspect defines the aspect ratio
  6402. * @param znear defines the near clip plane
  6403. * @param zfar defines the far clip plane
  6404. * @param result defines the target matrix
  6405. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6406. */
  6407. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6408. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6409. var n = znear;
  6410. var f = zfar;
  6411. var t = 1.0 / (Math.tan(fov * 0.5));
  6412. var a = isVerticalFovFixed ? (t / aspect) : t;
  6413. var b = isVerticalFovFixed ? t : (t * aspect);
  6414. var c = (f + n) / (f - n);
  6415. var d = -2.0 * f * n / (f - n);
  6416. 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);
  6417. };
  6418. /**
  6419. * Creates a right-handed perspective projection matrix
  6420. * @param fov defines the horizontal field of view
  6421. * @param aspect defines the aspect ratio
  6422. * @param znear defines the near clip plane
  6423. * @param zfar defines the far clip plane
  6424. * @returns a new matrix as a right-handed perspective projection matrix
  6425. */
  6426. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6427. var matrix = Matrix.Zero();
  6428. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6429. return matrix;
  6430. };
  6431. /**
  6432. * Stores a right-handed perspective projection into a given matrix
  6433. * @param fov defines the horizontal field of view
  6434. * @param aspect defines the aspect ratio
  6435. * @param znear defines the near clip plane
  6436. * @param zfar defines the far clip plane
  6437. * @param result defines the target matrix
  6438. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6439. */
  6440. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6441. //alternatively this could be expressed as:
  6442. // m = PerspectiveFovLHToRef
  6443. // m[10] *= -1.0;
  6444. // m[11] *= -1.0;
  6445. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6446. var n = znear;
  6447. var f = zfar;
  6448. var t = 1.0 / (Math.tan(fov * 0.5));
  6449. var a = isVerticalFovFixed ? (t / aspect) : t;
  6450. var b = isVerticalFovFixed ? t : (t * aspect);
  6451. var c = -(f + n) / (f - n);
  6452. var d = -2 * f * n / (f - n);
  6453. 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);
  6454. };
  6455. /**
  6456. * Stores a perspective projection for WebVR info a given matrix
  6457. * @param fov defines the field of view
  6458. * @param znear defines the near clip plane
  6459. * @param zfar defines the far clip plane
  6460. * @param result defines the target matrix
  6461. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6462. */
  6463. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6464. if (rightHanded === void 0) { rightHanded = false; }
  6465. var rightHandedFactor = rightHanded ? -1 : 1;
  6466. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6467. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6468. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6469. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6470. var xScale = 2.0 / (leftTan + rightTan);
  6471. var yScale = 2.0 / (upTan + downTan);
  6472. result.m[0] = xScale;
  6473. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6474. result.m[5] = yScale;
  6475. result.m[6] = result.m[7] = 0.0;
  6476. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6477. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6478. result.m[10] = -zfar / (znear - zfar);
  6479. result.m[11] = 1.0 * rightHandedFactor;
  6480. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6481. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6482. result._markAsUpdated();
  6483. };
  6484. /**
  6485. * Computes a complete transformation matrix
  6486. * @param viewport defines the viewport to use
  6487. * @param world defines the world matrix
  6488. * @param view defines the view matrix
  6489. * @param projection defines the projection matrix
  6490. * @param zmin defines the near clip plane
  6491. * @param zmax defines the far clip plane
  6492. * @returns the transformation matrix
  6493. */
  6494. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6495. var cw = viewport.width;
  6496. var ch = viewport.height;
  6497. var cx = viewport.x;
  6498. var cy = viewport.y;
  6499. 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);
  6500. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6501. };
  6502. /**
  6503. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6504. * @param matrix defines the matrix to use
  6505. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6506. */
  6507. Matrix.GetAsMatrix2x2 = function (matrix) {
  6508. return new Float32Array([
  6509. matrix.m[0], matrix.m[1],
  6510. matrix.m[4], matrix.m[5]
  6511. ]);
  6512. };
  6513. /**
  6514. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6515. * @param matrix defines the matrix to use
  6516. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6517. */
  6518. Matrix.GetAsMatrix3x3 = function (matrix) {
  6519. return new Float32Array([
  6520. matrix.m[0], matrix.m[1], matrix.m[2],
  6521. matrix.m[4], matrix.m[5], matrix.m[6],
  6522. matrix.m[8], matrix.m[9], matrix.m[10]
  6523. ]);
  6524. };
  6525. /**
  6526. * Compute the transpose of a given matrix
  6527. * @param matrix defines the matrix to transpose
  6528. * @returns the new matrix
  6529. */
  6530. Matrix.Transpose = function (matrix) {
  6531. var result = new Matrix();
  6532. Matrix.TransposeToRef(matrix, result);
  6533. return result;
  6534. };
  6535. /**
  6536. * Compute the transpose of a matrix and store it in a target matrix
  6537. * @param matrix defines the matrix to transpose
  6538. * @param result defines the target matrix
  6539. */
  6540. Matrix.TransposeToRef = function (matrix, result) {
  6541. result.m[0] = matrix.m[0];
  6542. result.m[1] = matrix.m[4];
  6543. result.m[2] = matrix.m[8];
  6544. result.m[3] = matrix.m[12];
  6545. result.m[4] = matrix.m[1];
  6546. result.m[5] = matrix.m[5];
  6547. result.m[6] = matrix.m[9];
  6548. result.m[7] = matrix.m[13];
  6549. result.m[8] = matrix.m[2];
  6550. result.m[9] = matrix.m[6];
  6551. result.m[10] = matrix.m[10];
  6552. result.m[11] = matrix.m[14];
  6553. result.m[12] = matrix.m[3];
  6554. result.m[13] = matrix.m[7];
  6555. result.m[14] = matrix.m[11];
  6556. result.m[15] = matrix.m[15];
  6557. };
  6558. /**
  6559. * Computes a reflection matrix from a plane
  6560. * @param plane defines the reflection plane
  6561. * @returns a new matrix
  6562. */
  6563. Matrix.Reflection = function (plane) {
  6564. var matrix = new Matrix();
  6565. Matrix.ReflectionToRef(plane, matrix);
  6566. return matrix;
  6567. };
  6568. /**
  6569. * Computes a reflection matrix from a plane
  6570. * @param plane defines the reflection plane
  6571. * @param result defines the target matrix
  6572. */
  6573. Matrix.ReflectionToRef = function (plane, result) {
  6574. plane.normalize();
  6575. var x = plane.normal.x;
  6576. var y = plane.normal.y;
  6577. var z = plane.normal.z;
  6578. var temp = -2 * x;
  6579. var temp2 = -2 * y;
  6580. var temp3 = -2 * z;
  6581. result.m[0] = (temp * x) + 1;
  6582. result.m[1] = temp2 * x;
  6583. result.m[2] = temp3 * x;
  6584. result.m[3] = 0.0;
  6585. result.m[4] = temp * y;
  6586. result.m[5] = (temp2 * y) + 1;
  6587. result.m[6] = temp3 * y;
  6588. result.m[7] = 0.0;
  6589. result.m[8] = temp * z;
  6590. result.m[9] = temp2 * z;
  6591. result.m[10] = (temp3 * z) + 1;
  6592. result.m[11] = 0.0;
  6593. result.m[12] = temp * plane.d;
  6594. result.m[13] = temp2 * plane.d;
  6595. result.m[14] = temp3 * plane.d;
  6596. result.m[15] = 1.0;
  6597. result._markAsUpdated();
  6598. };
  6599. /**
  6600. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6601. * @param xaxis defines the value of the 1st axis
  6602. * @param yaxis defines the value of the 2nd axis
  6603. * @param zaxis defines the value of the 3rd axis
  6604. * @param result defines the target matrix
  6605. */
  6606. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6607. result.m[0] = xaxis.x;
  6608. result.m[1] = xaxis.y;
  6609. result.m[2] = xaxis.z;
  6610. result.m[3] = 0.0;
  6611. result.m[4] = yaxis.x;
  6612. result.m[5] = yaxis.y;
  6613. result.m[6] = yaxis.z;
  6614. result.m[7] = 0.0;
  6615. result.m[8] = zaxis.x;
  6616. result.m[9] = zaxis.y;
  6617. result.m[10] = zaxis.z;
  6618. result.m[11] = 0.0;
  6619. result.m[12] = 0.0;
  6620. result.m[13] = 0.0;
  6621. result.m[14] = 0.0;
  6622. result.m[15] = 1.0;
  6623. result._markAsUpdated();
  6624. };
  6625. /**
  6626. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6627. * @param quat defines the quaternion to use
  6628. * @param result defines the target matrix
  6629. */
  6630. Matrix.FromQuaternionToRef = function (quat, result) {
  6631. var xx = quat.x * quat.x;
  6632. var yy = quat.y * quat.y;
  6633. var zz = quat.z * quat.z;
  6634. var xy = quat.x * quat.y;
  6635. var zw = quat.z * quat.w;
  6636. var zx = quat.z * quat.x;
  6637. var yw = quat.y * quat.w;
  6638. var yz = quat.y * quat.z;
  6639. var xw = quat.x * quat.w;
  6640. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6641. result.m[1] = 2.0 * (xy + zw);
  6642. result.m[2] = 2.0 * (zx - yw);
  6643. result.m[3] = 0.0;
  6644. result.m[4] = 2.0 * (xy - zw);
  6645. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6646. result.m[6] = 2.0 * (yz + xw);
  6647. result.m[7] = 0.0;
  6648. result.m[8] = 2.0 * (zx + yw);
  6649. result.m[9] = 2.0 * (yz - xw);
  6650. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6651. result.m[11] = 0.0;
  6652. result.m[12] = 0.0;
  6653. result.m[13] = 0.0;
  6654. result.m[14] = 0.0;
  6655. result.m[15] = 1.0;
  6656. result._markAsUpdated();
  6657. };
  6658. Matrix._tempQuaternion = new Quaternion();
  6659. Matrix._xAxis = Vector3.Zero();
  6660. Matrix._yAxis = Vector3.Zero();
  6661. Matrix._zAxis = Vector3.Zero();
  6662. Matrix._updateFlagSeed = 0;
  6663. Matrix._identityReadOnly = Matrix.Identity();
  6664. return Matrix;
  6665. }());
  6666. BABYLON.Matrix = Matrix;
  6667. var Plane = /** @class */ (function () {
  6668. /**
  6669. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6670. */
  6671. function Plane(a, b, c, d) {
  6672. this.normal = new Vector3(a, b, c);
  6673. this.d = d;
  6674. }
  6675. /**
  6676. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6677. */
  6678. Plane.prototype.asArray = function () {
  6679. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6680. };
  6681. // Methods
  6682. /**
  6683. * Returns a new plane copied from the current Plane.
  6684. */
  6685. Plane.prototype.clone = function () {
  6686. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6687. };
  6688. /**
  6689. * Returns the string "Plane".
  6690. */
  6691. Plane.prototype.getClassName = function () {
  6692. return "Plane";
  6693. };
  6694. /**
  6695. * Returns the Plane hash code.
  6696. */
  6697. Plane.prototype.getHashCode = function () {
  6698. var hash = this.normal.getHashCode();
  6699. hash = (hash * 397) ^ (this.d || 0);
  6700. return hash;
  6701. };
  6702. /**
  6703. * Normalize the current Plane in place.
  6704. * Returns the updated Plane.
  6705. */
  6706. Plane.prototype.normalize = function () {
  6707. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6708. var magnitude = 0.0;
  6709. if (norm !== 0) {
  6710. magnitude = 1.0 / norm;
  6711. }
  6712. this.normal.x *= magnitude;
  6713. this.normal.y *= magnitude;
  6714. this.normal.z *= magnitude;
  6715. this.d *= magnitude;
  6716. return this;
  6717. };
  6718. /**
  6719. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6720. */
  6721. Plane.prototype.transform = function (transformation) {
  6722. var transposedMatrix = Matrix.Transpose(transformation);
  6723. var x = this.normal.x;
  6724. var y = this.normal.y;
  6725. var z = this.normal.z;
  6726. var d = this.d;
  6727. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6728. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6729. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6730. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6731. return new Plane(normalX, normalY, normalZ, finalD);
  6732. };
  6733. /**
  6734. * Returns the dot product (float) of the point coordinates and the plane normal.
  6735. */
  6736. Plane.prototype.dotCoordinate = function (point) {
  6737. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6738. };
  6739. /**
  6740. * Updates the current Plane from the plane defined by the three given points.
  6741. * Returns the updated Plane.
  6742. */
  6743. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6744. var x1 = point2.x - point1.x;
  6745. var y1 = point2.y - point1.y;
  6746. var z1 = point2.z - point1.z;
  6747. var x2 = point3.x - point1.x;
  6748. var y2 = point3.y - point1.y;
  6749. var z2 = point3.z - point1.z;
  6750. var yz = (y1 * z2) - (z1 * y2);
  6751. var xz = (z1 * x2) - (x1 * z2);
  6752. var xy = (x1 * y2) - (y1 * x2);
  6753. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6754. var invPyth;
  6755. if (pyth !== 0) {
  6756. invPyth = 1.0 / pyth;
  6757. }
  6758. else {
  6759. invPyth = 0.0;
  6760. }
  6761. this.normal.x = yz * invPyth;
  6762. this.normal.y = xz * invPyth;
  6763. this.normal.z = xy * invPyth;
  6764. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6765. return this;
  6766. };
  6767. /**
  6768. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6769. */
  6770. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6771. var dot = Vector3.Dot(this.normal, direction);
  6772. return (dot <= epsilon);
  6773. };
  6774. /**
  6775. * Returns the signed distance (float) from the given point to the Plane.
  6776. */
  6777. Plane.prototype.signedDistanceTo = function (point) {
  6778. return Vector3.Dot(point, this.normal) + this.d;
  6779. };
  6780. // Statics
  6781. /**
  6782. * Returns a new Plane from the given array.
  6783. */
  6784. Plane.FromArray = function (array) {
  6785. return new Plane(array[0], array[1], array[2], array[3]);
  6786. };
  6787. /**
  6788. * Returns a new Plane defined by the three given points.
  6789. */
  6790. Plane.FromPoints = function (point1, point2, point3) {
  6791. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6792. result.copyFromPoints(point1, point2, point3);
  6793. return result;
  6794. };
  6795. /**
  6796. * Returns a new Plane the normal vector to this plane at the given origin point.
  6797. * Note : the vector "normal" is updated because normalized.
  6798. */
  6799. Plane.FromPositionAndNormal = function (origin, normal) {
  6800. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6801. normal.normalize();
  6802. result.normal = normal;
  6803. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6804. return result;
  6805. };
  6806. /**
  6807. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6808. */
  6809. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6810. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6811. return Vector3.Dot(point, normal) + d;
  6812. };
  6813. return Plane;
  6814. }());
  6815. BABYLON.Plane = Plane;
  6816. var Viewport = /** @class */ (function () {
  6817. /**
  6818. * Creates a Viewport object located at (x, y) and sized (width, height).
  6819. */
  6820. function Viewport(x, y, width, height) {
  6821. this.x = x;
  6822. this.y = y;
  6823. this.width = width;
  6824. this.height = height;
  6825. }
  6826. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6827. if (renderWidthOrEngine.getRenderWidth) {
  6828. var engine = renderWidthOrEngine;
  6829. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6830. }
  6831. var renderWidth = renderWidthOrEngine;
  6832. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6833. };
  6834. /**
  6835. * Returns a new Viewport copied from the current one.
  6836. */
  6837. Viewport.prototype.clone = function () {
  6838. return new Viewport(this.x, this.y, this.width, this.height);
  6839. };
  6840. return Viewport;
  6841. }());
  6842. BABYLON.Viewport = Viewport;
  6843. var Frustum = /** @class */ (function () {
  6844. function Frustum() {
  6845. }
  6846. /**
  6847. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6848. */
  6849. Frustum.GetPlanes = function (transform) {
  6850. var frustumPlanes = [];
  6851. for (var index = 0; index < 6; index++) {
  6852. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6853. }
  6854. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6855. return frustumPlanes;
  6856. };
  6857. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6858. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6859. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6860. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6861. frustumPlane.d = transform.m[15] + transform.m[14];
  6862. frustumPlane.normalize();
  6863. };
  6864. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6865. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6866. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6867. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6868. frustumPlane.d = transform.m[15] - transform.m[14];
  6869. frustumPlane.normalize();
  6870. };
  6871. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6872. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6873. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6874. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6875. frustumPlane.d = transform.m[15] + transform.m[12];
  6876. frustumPlane.normalize();
  6877. };
  6878. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6879. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6880. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6881. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6882. frustumPlane.d = transform.m[15] - transform.m[12];
  6883. frustumPlane.normalize();
  6884. };
  6885. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6886. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6887. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6888. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6889. frustumPlane.d = transform.m[15] - transform.m[13];
  6890. frustumPlane.normalize();
  6891. };
  6892. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6893. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6894. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6895. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6896. frustumPlane.d = transform.m[15] + transform.m[13];
  6897. frustumPlane.normalize();
  6898. };
  6899. /**
  6900. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6901. */
  6902. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6903. // Near
  6904. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6905. // Far
  6906. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6907. // Left
  6908. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6909. // Right
  6910. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6911. // Top
  6912. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6913. // Bottom
  6914. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6915. };
  6916. return Frustum;
  6917. }());
  6918. BABYLON.Frustum = Frustum;
  6919. /** Defines supported spaces */
  6920. var Space;
  6921. (function (Space) {
  6922. /** Local (object) space */
  6923. Space[Space["LOCAL"] = 0] = "LOCAL";
  6924. /** World space */
  6925. Space[Space["WORLD"] = 1] = "WORLD";
  6926. /** Bone space */
  6927. Space[Space["BONE"] = 2] = "BONE";
  6928. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6929. /** Defines the 3 main axes */
  6930. var Axis = /** @class */ (function () {
  6931. function Axis() {
  6932. }
  6933. /** X axis */
  6934. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6935. /** Y axis */
  6936. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6937. /** Z axis */
  6938. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6939. return Axis;
  6940. }());
  6941. BABYLON.Axis = Axis;
  6942. ;
  6943. var BezierCurve = /** @class */ (function () {
  6944. function BezierCurve() {
  6945. }
  6946. /**
  6947. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6948. */
  6949. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6950. // Extract X (which is equal to time here)
  6951. var f0 = 1 - 3 * x2 + 3 * x1;
  6952. var f1 = 3 * x2 - 6 * x1;
  6953. var f2 = 3 * x1;
  6954. var refinedT = t;
  6955. for (var i = 0; i < 5; i++) {
  6956. var refinedT2 = refinedT * refinedT;
  6957. var refinedT3 = refinedT2 * refinedT;
  6958. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6959. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6960. refinedT -= (x - t) * slope;
  6961. refinedT = Math.min(1, Math.max(0, refinedT));
  6962. }
  6963. // Resolve cubic bezier for the given x
  6964. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6965. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6966. Math.pow(refinedT, 3);
  6967. };
  6968. return BezierCurve;
  6969. }());
  6970. BABYLON.BezierCurve = BezierCurve;
  6971. /**
  6972. * Defines potential orientation for back face culling
  6973. */
  6974. var Orientation;
  6975. (function (Orientation) {
  6976. /**
  6977. * Clockwise
  6978. */
  6979. Orientation[Orientation["CW"] = 0] = "CW";
  6980. /** Counter clockwise */
  6981. Orientation[Orientation["CCW"] = 1] = "CCW";
  6982. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6983. /**
  6984. * Defines angle representation
  6985. */
  6986. var Angle = /** @class */ (function () {
  6987. /**
  6988. * Creates an Angle object of "radians" radians (float).
  6989. */
  6990. function Angle(radians) {
  6991. this._radians = radians;
  6992. if (this._radians < 0.0)
  6993. this._radians += (2.0 * Math.PI);
  6994. }
  6995. /**
  6996. * Get value in degrees
  6997. * @returns the Angle value in degrees (float)
  6998. */
  6999. Angle.prototype.degrees = function () {
  7000. return this._radians * 180.0 / Math.PI;
  7001. };
  7002. /**
  7003. * Get value in radians
  7004. * @returns the Angle value in radians (float)
  7005. */
  7006. Angle.prototype.radians = function () {
  7007. return this._radians;
  7008. };
  7009. /**
  7010. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7011. * @param a defines first vector
  7012. * @param b defines second vector
  7013. * @returns a new Angle
  7014. */
  7015. Angle.BetweenTwoPoints = function (a, b) {
  7016. var delta = b.subtract(a);
  7017. var theta = Math.atan2(delta.y, delta.x);
  7018. return new Angle(theta);
  7019. };
  7020. /**
  7021. * Gets a new Angle object from the given float in radians
  7022. * @param radians defines the angle value in radians
  7023. * @returns a new Angle
  7024. */
  7025. Angle.FromRadians = function (radians) {
  7026. return new Angle(radians);
  7027. };
  7028. /**
  7029. * Gets a new Angle object from the given float in degrees
  7030. * @param degrees defines the angle value in degrees
  7031. * @returns a new Angle
  7032. */
  7033. Angle.FromDegrees = function (degrees) {
  7034. return new Angle(degrees * Math.PI / 180.0);
  7035. };
  7036. return Angle;
  7037. }());
  7038. BABYLON.Angle = Angle;
  7039. /**
  7040. * This represents an arc in a 2d space.
  7041. */
  7042. var Arc2 = /** @class */ (function () {
  7043. /**
  7044. * Creates an Arc object from the three given points : start, middle and end.
  7045. * @param startPoint Defines the start point of the arc
  7046. * @param midPoint Defines the midlle point of the arc
  7047. * @param endPoint Defines the end point of the arc
  7048. */
  7049. function Arc2(
  7050. /** Defines the start point of the arc */
  7051. startPoint,
  7052. /** Defines the mid point of the arc */
  7053. midPoint,
  7054. /** Defines the end point of the arc */
  7055. endPoint) {
  7056. this.startPoint = startPoint;
  7057. this.midPoint = midPoint;
  7058. this.endPoint = endPoint;
  7059. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7060. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7061. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7062. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7063. 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);
  7064. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7065. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7066. var a1 = this.startAngle.degrees();
  7067. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7068. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7069. // angles correction
  7070. if (a2 - a1 > +180.0)
  7071. a2 -= 360.0;
  7072. if (a2 - a1 < -180.0)
  7073. a2 += 360.0;
  7074. if (a3 - a2 > +180.0)
  7075. a3 -= 360.0;
  7076. if (a3 - a2 < -180.0)
  7077. a3 += 360.0;
  7078. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7079. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7080. }
  7081. return Arc2;
  7082. }());
  7083. BABYLON.Arc2 = Arc2;
  7084. var Path2 = /** @class */ (function () {
  7085. /**
  7086. * Creates a Path2 object from the starting 2D coordinates x and y.
  7087. */
  7088. function Path2(x, y) {
  7089. this._points = new Array();
  7090. this._length = 0.0;
  7091. this.closed = false;
  7092. this._points.push(new Vector2(x, y));
  7093. }
  7094. /**
  7095. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7096. * Returns the updated Path2.
  7097. */
  7098. Path2.prototype.addLineTo = function (x, y) {
  7099. if (this.closed) {
  7100. return this;
  7101. }
  7102. var newPoint = new Vector2(x, y);
  7103. var previousPoint = this._points[this._points.length - 1];
  7104. this._points.push(newPoint);
  7105. this._length += newPoint.subtract(previousPoint).length();
  7106. return this;
  7107. };
  7108. /**
  7109. * 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.
  7110. * Returns the updated Path2.
  7111. */
  7112. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7113. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7114. if (this.closed) {
  7115. return this;
  7116. }
  7117. var startPoint = this._points[this._points.length - 1];
  7118. var midPoint = new Vector2(midX, midY);
  7119. var endPoint = new Vector2(endX, endY);
  7120. var arc = new Arc2(startPoint, midPoint, endPoint);
  7121. var increment = arc.angle.radians() / numberOfSegments;
  7122. if (arc.orientation === Orientation.CW)
  7123. increment *= -1;
  7124. var currentAngle = arc.startAngle.radians() + increment;
  7125. for (var i = 0; i < numberOfSegments; i++) {
  7126. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7127. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7128. this.addLineTo(x, y);
  7129. currentAngle += increment;
  7130. }
  7131. return this;
  7132. };
  7133. /**
  7134. * Closes the Path2.
  7135. * Returns the Path2.
  7136. */
  7137. Path2.prototype.close = function () {
  7138. this.closed = true;
  7139. return this;
  7140. };
  7141. /**
  7142. * Returns the Path2 total length (float).
  7143. */
  7144. Path2.prototype.length = function () {
  7145. var result = this._length;
  7146. if (!this.closed) {
  7147. var lastPoint = this._points[this._points.length - 1];
  7148. var firstPoint = this._points[0];
  7149. result += (firstPoint.subtract(lastPoint).length());
  7150. }
  7151. return result;
  7152. };
  7153. /**
  7154. * Returns the Path2 internal array of points.
  7155. */
  7156. Path2.prototype.getPoints = function () {
  7157. return this._points;
  7158. };
  7159. /**
  7160. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7161. */
  7162. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7163. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7164. return Vector2.Zero();
  7165. }
  7166. var lengthPosition = normalizedLengthPosition * this.length();
  7167. var previousOffset = 0;
  7168. for (var i = 0; i < this._points.length; i++) {
  7169. var j = (i + 1) % this._points.length;
  7170. var a = this._points[i];
  7171. var b = this._points[j];
  7172. var bToA = b.subtract(a);
  7173. var nextOffset = (bToA.length() + previousOffset);
  7174. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7175. var dir = bToA.normalize();
  7176. var localOffset = lengthPosition - previousOffset;
  7177. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7178. }
  7179. previousOffset = nextOffset;
  7180. }
  7181. return Vector2.Zero();
  7182. };
  7183. /**
  7184. * Returns a new Path2 starting at the coordinates (x, y).
  7185. */
  7186. Path2.StartingAt = function (x, y) {
  7187. return new Path2(x, y);
  7188. };
  7189. return Path2;
  7190. }());
  7191. BABYLON.Path2 = Path2;
  7192. var Path3D = /** @class */ (function () {
  7193. /**
  7194. * new Path3D(path, normal, raw)
  7195. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7196. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7197. * path : an array of Vector3, the curve axis of the Path3D
  7198. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7199. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7200. */
  7201. function Path3D(path, firstNormal, raw) {
  7202. if (firstNormal === void 0) { firstNormal = null; }
  7203. this.path = path;
  7204. this._curve = new Array();
  7205. this._distances = new Array();
  7206. this._tangents = new Array();
  7207. this._normals = new Array();
  7208. this._binormals = new Array();
  7209. for (var p = 0; p < path.length; p++) {
  7210. this._curve[p] = path[p].clone(); // hard copy
  7211. }
  7212. this._raw = raw || false;
  7213. this._compute(firstNormal);
  7214. }
  7215. /**
  7216. * Returns the Path3D array of successive Vector3 designing its curve.
  7217. */
  7218. Path3D.prototype.getCurve = function () {
  7219. return this._curve;
  7220. };
  7221. /**
  7222. * Returns an array populated with tangent vectors on each Path3D curve point.
  7223. */
  7224. Path3D.prototype.getTangents = function () {
  7225. return this._tangents;
  7226. };
  7227. /**
  7228. * Returns an array populated with normal vectors on each Path3D curve point.
  7229. */
  7230. Path3D.prototype.getNormals = function () {
  7231. return this._normals;
  7232. };
  7233. /**
  7234. * Returns an array populated with binormal vectors on each Path3D curve point.
  7235. */
  7236. Path3D.prototype.getBinormals = function () {
  7237. return this._binormals;
  7238. };
  7239. /**
  7240. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7241. */
  7242. Path3D.prototype.getDistances = function () {
  7243. return this._distances;
  7244. };
  7245. /**
  7246. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7247. * Returns the same object updated.
  7248. */
  7249. Path3D.prototype.update = function (path, firstNormal) {
  7250. if (firstNormal === void 0) { firstNormal = null; }
  7251. for (var p = 0; p < path.length; p++) {
  7252. this._curve[p].x = path[p].x;
  7253. this._curve[p].y = path[p].y;
  7254. this._curve[p].z = path[p].z;
  7255. }
  7256. this._compute(firstNormal);
  7257. return this;
  7258. };
  7259. // private function compute() : computes tangents, normals and binormals
  7260. Path3D.prototype._compute = function (firstNormal) {
  7261. var l = this._curve.length;
  7262. // first and last tangents
  7263. this._tangents[0] = this._getFirstNonNullVector(0);
  7264. if (!this._raw) {
  7265. this._tangents[0].normalize();
  7266. }
  7267. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7268. if (!this._raw) {
  7269. this._tangents[l - 1].normalize();
  7270. }
  7271. // normals and binormals at first point : arbitrary vector with _normalVector()
  7272. var tg0 = this._tangents[0];
  7273. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7274. this._normals[0] = pp0;
  7275. if (!this._raw) {
  7276. this._normals[0].normalize();
  7277. }
  7278. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7279. if (!this._raw) {
  7280. this._binormals[0].normalize();
  7281. }
  7282. this._distances[0] = 0.0;
  7283. // normals and binormals : next points
  7284. var prev; // previous vector (segment)
  7285. var cur; // current vector (segment)
  7286. var curTang; // current tangent
  7287. // previous normal
  7288. var prevBinor; // previous binormal
  7289. for (var i = 1; i < l; i++) {
  7290. // tangents
  7291. prev = this._getLastNonNullVector(i);
  7292. if (i < l - 1) {
  7293. cur = this._getFirstNonNullVector(i);
  7294. this._tangents[i] = prev.add(cur);
  7295. this._tangents[i].normalize();
  7296. }
  7297. this._distances[i] = this._distances[i - 1] + prev.length();
  7298. // normals and binormals
  7299. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7300. curTang = this._tangents[i];
  7301. prevBinor = this._binormals[i - 1];
  7302. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7303. if (!this._raw) {
  7304. this._normals[i].normalize();
  7305. }
  7306. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7307. if (!this._raw) {
  7308. this._binormals[i].normalize();
  7309. }
  7310. }
  7311. };
  7312. // private function getFirstNonNullVector(index)
  7313. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7314. Path3D.prototype._getFirstNonNullVector = function (index) {
  7315. var i = 1;
  7316. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7317. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7318. i++;
  7319. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7320. }
  7321. return nNVector;
  7322. };
  7323. // private function getLastNonNullVector(index)
  7324. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7325. Path3D.prototype._getLastNonNullVector = function (index) {
  7326. var i = 1;
  7327. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7328. while (nLVector.length() === 0 && index > i + 1) {
  7329. i++;
  7330. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7331. }
  7332. return nLVector;
  7333. };
  7334. // private function normalVector(v0, vt, va) :
  7335. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7336. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7337. Path3D.prototype._normalVector = function (v0, vt, va) {
  7338. var normal0;
  7339. var tgl = vt.length();
  7340. if (tgl === 0.0) {
  7341. tgl = 1.0;
  7342. }
  7343. if (va === undefined || va === null) {
  7344. var point;
  7345. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7346. point = new Vector3(0.0, -1.0, 0.0);
  7347. }
  7348. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7349. point = new Vector3(1.0, 0.0, 0.0);
  7350. }
  7351. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7352. point = new Vector3(0.0, 0.0, 1.0);
  7353. }
  7354. else {
  7355. point = Vector3.Zero();
  7356. }
  7357. normal0 = Vector3.Cross(vt, point);
  7358. }
  7359. else {
  7360. normal0 = Vector3.Cross(vt, va);
  7361. Vector3.CrossToRef(normal0, vt, normal0);
  7362. }
  7363. normal0.normalize();
  7364. return normal0;
  7365. };
  7366. return Path3D;
  7367. }());
  7368. BABYLON.Path3D = Path3D;
  7369. var Curve3 = /** @class */ (function () {
  7370. /**
  7371. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7372. * A Curve3 is designed from a series of successive Vector3.
  7373. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7374. */
  7375. function Curve3(points) {
  7376. this._length = 0.0;
  7377. this._points = points;
  7378. this._length = this._computeLength(points);
  7379. }
  7380. /**
  7381. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7382. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7383. * @param v1 (Vector3) the control point
  7384. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7385. * @param nbPoints (integer) the wanted number of points in the curve
  7386. */
  7387. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7388. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7389. var bez = new Array();
  7390. var equation = function (t, val0, val1, val2) {
  7391. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7392. return res;
  7393. };
  7394. for (var i = 0; i <= nbPoints; i++) {
  7395. 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)));
  7396. }
  7397. return new Curve3(bez);
  7398. };
  7399. /**
  7400. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7401. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7402. * @param v1 (Vector3) the first control point
  7403. * @param v2 (Vector3) the second control point
  7404. * @param v3 (Vector3) the end point of the Cubic Bezier
  7405. * @param nbPoints (integer) the wanted number of points in the curve
  7406. */
  7407. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7408. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7409. var bez = new Array();
  7410. var equation = function (t, val0, val1, val2, val3) {
  7411. 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;
  7412. return res;
  7413. };
  7414. for (var i = 0; i <= nbPoints; i++) {
  7415. 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)));
  7416. }
  7417. return new Curve3(bez);
  7418. };
  7419. /**
  7420. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7421. * @param p1 (Vector3) the origin point of the Hermite Spline
  7422. * @param t1 (Vector3) the tangent vector at the origin point
  7423. * @param p2 (Vector3) the end point of the Hermite Spline
  7424. * @param t2 (Vector3) the tangent vector at the end point
  7425. * @param nbPoints (integer) the wanted number of points in the curve
  7426. */
  7427. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7428. var hermite = new Array();
  7429. var step = 1.0 / nbPoints;
  7430. for (var i = 0; i <= nbPoints; i++) {
  7431. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7432. }
  7433. return new Curve3(hermite);
  7434. };
  7435. /**
  7436. * Returns a Curve3 object along a CatmullRom Spline curve :
  7437. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7438. * @param nbPoints (integer) the wanted number of points between each curve control points
  7439. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7440. */
  7441. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7442. var catmullRom = new Array();
  7443. var step = 1.0 / nbPoints;
  7444. var amount = 0.0;
  7445. if (closed) {
  7446. var pointsCount = points.length;
  7447. for (var i = 0; i < pointsCount; i++) {
  7448. amount = 0;
  7449. for (var c = 0; c < nbPoints; c++) {
  7450. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7451. amount += step;
  7452. }
  7453. }
  7454. catmullRom.push(catmullRom[0]);
  7455. }
  7456. else {
  7457. var totalPoints = new Array();
  7458. totalPoints.push(points[0].clone());
  7459. Array.prototype.push.apply(totalPoints, points);
  7460. totalPoints.push(points[points.length - 1].clone());
  7461. for (var i = 0; i < totalPoints.length - 3; i++) {
  7462. amount = 0;
  7463. for (var c = 0; c < nbPoints; c++) {
  7464. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7465. amount += step;
  7466. }
  7467. }
  7468. i--;
  7469. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7470. }
  7471. return new Curve3(catmullRom);
  7472. };
  7473. /**
  7474. * Returns the Curve3 stored array of successive Vector3
  7475. */
  7476. Curve3.prototype.getPoints = function () {
  7477. return this._points;
  7478. };
  7479. /**
  7480. * Returns the computed length (float) of the curve.
  7481. */
  7482. Curve3.prototype.length = function () {
  7483. return this._length;
  7484. };
  7485. /**
  7486. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7487. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7488. * curveA and curveB keep unchanged.
  7489. */
  7490. Curve3.prototype.continue = function (curve) {
  7491. var lastPoint = this._points[this._points.length - 1];
  7492. var continuedPoints = this._points.slice();
  7493. var curvePoints = curve.getPoints();
  7494. for (var i = 1; i < curvePoints.length; i++) {
  7495. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7496. }
  7497. var continuedCurve = new Curve3(continuedPoints);
  7498. return continuedCurve;
  7499. };
  7500. Curve3.prototype._computeLength = function (path) {
  7501. var l = 0;
  7502. for (var i = 1; i < path.length; i++) {
  7503. l += (path[i].subtract(path[i - 1])).length();
  7504. }
  7505. return l;
  7506. };
  7507. return Curve3;
  7508. }());
  7509. BABYLON.Curve3 = Curve3;
  7510. // Vertex formats
  7511. var PositionNormalVertex = /** @class */ (function () {
  7512. function PositionNormalVertex(position, normal) {
  7513. if (position === void 0) { position = Vector3.Zero(); }
  7514. if (normal === void 0) { normal = Vector3.Up(); }
  7515. this.position = position;
  7516. this.normal = normal;
  7517. }
  7518. PositionNormalVertex.prototype.clone = function () {
  7519. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7520. };
  7521. return PositionNormalVertex;
  7522. }());
  7523. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7524. var PositionNormalTextureVertex = /** @class */ (function () {
  7525. function PositionNormalTextureVertex(position, normal, uv) {
  7526. if (position === void 0) { position = Vector3.Zero(); }
  7527. if (normal === void 0) { normal = Vector3.Up(); }
  7528. if (uv === void 0) { uv = Vector2.Zero(); }
  7529. this.position = position;
  7530. this.normal = normal;
  7531. this.uv = uv;
  7532. }
  7533. PositionNormalTextureVertex.prototype.clone = function () {
  7534. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7535. };
  7536. return PositionNormalTextureVertex;
  7537. }());
  7538. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7539. // Temporary pre-allocated objects for engine internal use
  7540. // usage in any internal function :
  7541. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7542. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7543. var Tmp = /** @class */ (function () {
  7544. function Tmp() {
  7545. }
  7546. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7547. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7548. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7549. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7550. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7551. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7552. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7553. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7554. Matrix.Zero(), Matrix.Zero(),
  7555. Matrix.Zero(), Matrix.Zero(),
  7556. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7557. return Tmp;
  7558. }());
  7559. BABYLON.Tmp = Tmp;
  7560. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7561. var MathTmp = /** @class */ (function () {
  7562. function MathTmp() {
  7563. }
  7564. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7565. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7566. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7567. return MathTmp;
  7568. }());
  7569. })(BABYLON || (BABYLON = {}));
  7570. //# sourceMappingURL=babylon.math.js.map
  7571. var BABYLON;
  7572. (function (BABYLON) {
  7573. var Scalar = /** @class */ (function () {
  7574. function Scalar() {
  7575. }
  7576. /**
  7577. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7578. */
  7579. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7580. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7581. var num = a - b;
  7582. return -epsilon <= num && num <= epsilon;
  7583. };
  7584. /**
  7585. * Returns a string : the upper case translation of the number i to hexadecimal.
  7586. */
  7587. Scalar.ToHex = function (i) {
  7588. var str = i.toString(16);
  7589. if (i <= 15) {
  7590. return ("0" + str).toUpperCase();
  7591. }
  7592. return str.toUpperCase();
  7593. };
  7594. /**
  7595. * Returns -1 if value is negative and +1 is value is positive.
  7596. * Returns the value itself if it's equal to zero.
  7597. */
  7598. Scalar.Sign = function (value) {
  7599. value = +value; // convert to a number
  7600. if (value === 0 || isNaN(value))
  7601. return value;
  7602. return value > 0 ? 1 : -1;
  7603. };
  7604. /**
  7605. * Returns the value itself if it's between min and max.
  7606. * Returns min if the value is lower than min.
  7607. * Returns max if the value is greater than max.
  7608. */
  7609. Scalar.Clamp = function (value, min, max) {
  7610. if (min === void 0) { min = 0; }
  7611. if (max === void 0) { max = 1; }
  7612. return Math.min(max, Math.max(min, value));
  7613. };
  7614. /**
  7615. * Returns the log2 of value.
  7616. */
  7617. Scalar.Log2 = function (value) {
  7618. return Math.log(value) * Math.LOG2E;
  7619. };
  7620. /**
  7621. * Loops the value, so that it is never larger than length and never smaller than 0.
  7622. *
  7623. * This is similar to the modulo operator but it works with floating point numbers.
  7624. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7625. * With t = 5 and length = 2.5, the result would be 0.0.
  7626. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7627. */
  7628. Scalar.Repeat = function (value, length) {
  7629. return value - Math.floor(value / length) * length;
  7630. };
  7631. /**
  7632. * Normalize the value between 0.0 and 1.0 using min and max values
  7633. */
  7634. Scalar.Normalize = function (value, min, max) {
  7635. return (value - min) / (max - min);
  7636. };
  7637. /**
  7638. * Denormalize the value from 0.0 and 1.0 using min and max values
  7639. */
  7640. Scalar.Denormalize = function (normalized, min, max) {
  7641. return (normalized * (max - min) + min);
  7642. };
  7643. /**
  7644. * Calculates the shortest difference between two given angles given in degrees.
  7645. */
  7646. Scalar.DeltaAngle = function (current, target) {
  7647. var num = Scalar.Repeat(target - current, 360.0);
  7648. if (num > 180.0) {
  7649. num -= 360.0;
  7650. }
  7651. return num;
  7652. };
  7653. /**
  7654. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7655. *
  7656. * The returned value will move back and forth between 0 and length
  7657. */
  7658. Scalar.PingPong = function (tx, length) {
  7659. var t = Scalar.Repeat(tx, length * 2.0);
  7660. return length - Math.abs(t - length);
  7661. };
  7662. /**
  7663. * Interpolates between min and max with smoothing at the limits.
  7664. *
  7665. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7666. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7667. */
  7668. Scalar.SmoothStep = function (from, to, tx) {
  7669. var t = Scalar.Clamp(tx);
  7670. t = -2.0 * t * t * t + 3.0 * t * t;
  7671. return to * t + from * (1.0 - t);
  7672. };
  7673. /**
  7674. * Moves a value current towards target.
  7675. *
  7676. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7677. * Negative values of maxDelta pushes the value away from target.
  7678. */
  7679. Scalar.MoveTowards = function (current, target, maxDelta) {
  7680. var result = 0;
  7681. if (Math.abs(target - current) <= maxDelta) {
  7682. result = target;
  7683. }
  7684. else {
  7685. result = current + Scalar.Sign(target - current) * maxDelta;
  7686. }
  7687. return result;
  7688. };
  7689. /**
  7690. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7691. *
  7692. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7693. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7694. */
  7695. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7696. var num = Scalar.DeltaAngle(current, target);
  7697. var result = 0;
  7698. if (-maxDelta < num && num < maxDelta) {
  7699. result = target;
  7700. }
  7701. else {
  7702. target = current + num;
  7703. result = Scalar.MoveTowards(current, target, maxDelta);
  7704. }
  7705. return result;
  7706. };
  7707. /**
  7708. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7709. */
  7710. Scalar.Lerp = function (start, end, amount) {
  7711. return start + ((end - start) * amount);
  7712. };
  7713. /**
  7714. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7715. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7716. */
  7717. Scalar.LerpAngle = function (start, end, amount) {
  7718. var num = Scalar.Repeat(end - start, 360.0);
  7719. if (num > 180.0) {
  7720. num -= 360.0;
  7721. }
  7722. return start + num * Scalar.Clamp(amount);
  7723. };
  7724. /**
  7725. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7726. */
  7727. Scalar.InverseLerp = function (a, b, value) {
  7728. var result = 0;
  7729. if (a != b) {
  7730. result = Scalar.Clamp((value - a) / (b - a));
  7731. }
  7732. else {
  7733. result = 0.0;
  7734. }
  7735. return result;
  7736. };
  7737. /**
  7738. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7739. */
  7740. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7741. var squared = amount * amount;
  7742. var cubed = amount * squared;
  7743. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7744. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7745. var part3 = (cubed - (2.0 * squared)) + amount;
  7746. var part4 = cubed - squared;
  7747. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7748. };
  7749. /**
  7750. * Returns a random float number between and min and max values
  7751. */
  7752. Scalar.RandomRange = function (min, max) {
  7753. if (min === max)
  7754. return min;
  7755. return ((Math.random() * (max - min)) + min);
  7756. };
  7757. /**
  7758. * This function returns percentage of a number in a given range.
  7759. *
  7760. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7761. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7762. */
  7763. Scalar.RangeToPercent = function (number, min, max) {
  7764. return ((number - min) / (max - min));
  7765. };
  7766. /**
  7767. * This function returns number that corresponds to the percentage in a given range.
  7768. *
  7769. * PercentToRange(0.34,0,100) will return 34.
  7770. */
  7771. Scalar.PercentToRange = function (percent, min, max) {
  7772. return ((max - min) * percent + min);
  7773. };
  7774. /**
  7775. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7776. * @param angle The angle to normalize in radian.
  7777. * @return The converted angle.
  7778. */
  7779. Scalar.NormalizeRadians = function (angle) {
  7780. // More precise but slower version kept for reference.
  7781. // angle = angle % Tools.TwoPi;
  7782. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7783. //if (angle > Math.PI) {
  7784. // angle -= Tools.TwoPi;
  7785. //}
  7786. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7787. return angle;
  7788. };
  7789. /**
  7790. * Two pi constants convenient for computation.
  7791. */
  7792. Scalar.TwoPi = Math.PI * 2;
  7793. return Scalar;
  7794. }());
  7795. BABYLON.Scalar = Scalar;
  7796. })(BABYLON || (BABYLON = {}));
  7797. //# sourceMappingURL=babylon.math.scalar.js.map
  7798. //# sourceMappingURL=babylon.mixins.js.map
  7799. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7800. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7801. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7802. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7803. //# sourceMappingURL=babylon.webgl2.js.map
  7804. var BABYLON;
  7805. (function (BABYLON) {
  7806. var __decoratorInitialStore = {};
  7807. var __mergedStore = {};
  7808. var _copySource = function (creationFunction, source, instanciate) {
  7809. var destination = creationFunction();
  7810. // Tags
  7811. if (BABYLON.Tags) {
  7812. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7813. }
  7814. var classStore = getMergedStore(destination);
  7815. // Properties
  7816. for (var property in classStore) {
  7817. var propertyDescriptor = classStore[property];
  7818. var sourceProperty = source[property];
  7819. var propertyType = propertyDescriptor.type;
  7820. if (sourceProperty !== undefined && sourceProperty !== null) {
  7821. switch (propertyType) {
  7822. case 0: // Value
  7823. case 6: // Mesh reference
  7824. case 11: // Camera reference
  7825. destination[property] = sourceProperty;
  7826. break;
  7827. case 1: // Texture
  7828. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7829. break;
  7830. case 2: // Color3
  7831. case 3: // FresnelParameters
  7832. case 4: // Vector2
  7833. case 5: // Vector3
  7834. case 7: // Color Curves
  7835. case 10: // Quaternion
  7836. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7837. break;
  7838. }
  7839. }
  7840. }
  7841. return destination;
  7842. };
  7843. function getDirectStore(target) {
  7844. var classKey = target.getClassName();
  7845. if (!__decoratorInitialStore[classKey]) {
  7846. __decoratorInitialStore[classKey] = {};
  7847. }
  7848. return __decoratorInitialStore[classKey];
  7849. }
  7850. /**
  7851. * Return the list of properties flagged as serializable
  7852. * @param target: host object
  7853. */
  7854. function getMergedStore(target) {
  7855. var classKey = target.getClassName();
  7856. if (__mergedStore[classKey]) {
  7857. return __mergedStore[classKey];
  7858. }
  7859. __mergedStore[classKey] = {};
  7860. var store = __mergedStore[classKey];
  7861. var currentTarget = target;
  7862. var currentKey = classKey;
  7863. while (currentKey) {
  7864. var initialStore = __decoratorInitialStore[currentKey];
  7865. for (var property in initialStore) {
  7866. store[property] = initialStore[property];
  7867. }
  7868. var parent_1 = void 0;
  7869. var done = false;
  7870. do {
  7871. parent_1 = Object.getPrototypeOf(currentTarget);
  7872. if (!parent_1.getClassName) {
  7873. done = true;
  7874. break;
  7875. }
  7876. if (parent_1.getClassName() !== currentKey) {
  7877. break;
  7878. }
  7879. currentTarget = parent_1;
  7880. } while (parent_1);
  7881. if (done) {
  7882. break;
  7883. }
  7884. currentKey = parent_1.getClassName();
  7885. currentTarget = parent_1;
  7886. }
  7887. return store;
  7888. }
  7889. function generateSerializableMember(type, sourceName) {
  7890. return function (target, propertyKey) {
  7891. var classStore = getDirectStore(target);
  7892. if (!classStore[propertyKey]) {
  7893. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7894. }
  7895. };
  7896. }
  7897. function generateExpandMember(setCallback, targetKey) {
  7898. if (targetKey === void 0) { targetKey = null; }
  7899. return function (target, propertyKey) {
  7900. var key = targetKey || ("_" + propertyKey);
  7901. Object.defineProperty(target, propertyKey, {
  7902. get: function () {
  7903. return this[key];
  7904. },
  7905. set: function (value) {
  7906. if (this[key] === value) {
  7907. return;
  7908. }
  7909. this[key] = value;
  7910. target[setCallback].apply(this);
  7911. },
  7912. enumerable: true,
  7913. configurable: true
  7914. });
  7915. };
  7916. }
  7917. function expandToProperty(callback, targetKey) {
  7918. if (targetKey === void 0) { targetKey = null; }
  7919. return generateExpandMember(callback, targetKey);
  7920. }
  7921. BABYLON.expandToProperty = expandToProperty;
  7922. function serialize(sourceName) {
  7923. return generateSerializableMember(0, sourceName); // value member
  7924. }
  7925. BABYLON.serialize = serialize;
  7926. function serializeAsTexture(sourceName) {
  7927. return generateSerializableMember(1, sourceName); // texture member
  7928. }
  7929. BABYLON.serializeAsTexture = serializeAsTexture;
  7930. function serializeAsColor3(sourceName) {
  7931. return generateSerializableMember(2, sourceName); // color3 member
  7932. }
  7933. BABYLON.serializeAsColor3 = serializeAsColor3;
  7934. function serializeAsFresnelParameters(sourceName) {
  7935. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7936. }
  7937. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7938. function serializeAsVector2(sourceName) {
  7939. return generateSerializableMember(4, sourceName); // vector2 member
  7940. }
  7941. BABYLON.serializeAsVector2 = serializeAsVector2;
  7942. function serializeAsVector3(sourceName) {
  7943. return generateSerializableMember(5, sourceName); // vector3 member
  7944. }
  7945. BABYLON.serializeAsVector3 = serializeAsVector3;
  7946. function serializeAsMeshReference(sourceName) {
  7947. return generateSerializableMember(6, sourceName); // mesh reference member
  7948. }
  7949. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7950. function serializeAsColorCurves(sourceName) {
  7951. return generateSerializableMember(7, sourceName); // color curves
  7952. }
  7953. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7954. function serializeAsColor4(sourceName) {
  7955. return generateSerializableMember(8, sourceName); // color 4
  7956. }
  7957. BABYLON.serializeAsColor4 = serializeAsColor4;
  7958. function serializeAsImageProcessingConfiguration(sourceName) {
  7959. return generateSerializableMember(9, sourceName); // image processing
  7960. }
  7961. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7962. function serializeAsQuaternion(sourceName) {
  7963. return generateSerializableMember(10, sourceName); // quaternion member
  7964. }
  7965. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7966. /**
  7967. * Decorator used to define property that can be serialized as reference to a camera
  7968. * @param sourceName defines the name of the property to decorate
  7969. */
  7970. function serializeAsCameraReference(sourceName) {
  7971. return generateSerializableMember(11, sourceName); // camera reference member
  7972. }
  7973. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7974. var SerializationHelper = /** @class */ (function () {
  7975. function SerializationHelper() {
  7976. }
  7977. SerializationHelper.Serialize = function (entity, serializationObject) {
  7978. if (!serializationObject) {
  7979. serializationObject = {};
  7980. }
  7981. // Tags
  7982. if (BABYLON.Tags) {
  7983. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7984. }
  7985. var serializedProperties = getMergedStore(entity);
  7986. // Properties
  7987. for (var property in serializedProperties) {
  7988. var propertyDescriptor = serializedProperties[property];
  7989. var targetPropertyName = propertyDescriptor.sourceName || property;
  7990. var propertyType = propertyDescriptor.type;
  7991. var sourceProperty = entity[property];
  7992. if (sourceProperty !== undefined && sourceProperty !== null) {
  7993. switch (propertyType) {
  7994. case 0: // Value
  7995. serializationObject[targetPropertyName] = sourceProperty;
  7996. break;
  7997. case 1: // Texture
  7998. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7999. break;
  8000. case 2: // Color3
  8001. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8002. break;
  8003. case 3: // FresnelParameters
  8004. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8005. break;
  8006. case 4: // Vector2
  8007. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8008. break;
  8009. case 5: // Vector3
  8010. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8011. break;
  8012. case 6: // Mesh reference
  8013. serializationObject[targetPropertyName] = sourceProperty.id;
  8014. break;
  8015. case 7: // Color Curves
  8016. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8017. break;
  8018. case 8: // Color 4
  8019. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8020. break;
  8021. case 9: // Image Processing
  8022. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8023. break;
  8024. case 10: // Quaternion
  8025. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8026. break;
  8027. case 11: // Camera reference
  8028. serializationObject[targetPropertyName] = sourceProperty.id;
  8029. break;
  8030. }
  8031. }
  8032. }
  8033. return serializationObject;
  8034. };
  8035. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8036. if (rootUrl === void 0) { rootUrl = null; }
  8037. var destination = creationFunction();
  8038. if (!rootUrl) {
  8039. rootUrl = "";
  8040. }
  8041. // Tags
  8042. if (BABYLON.Tags) {
  8043. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8044. }
  8045. var classStore = getMergedStore(destination);
  8046. // Properties
  8047. for (var property in classStore) {
  8048. var propertyDescriptor = classStore[property];
  8049. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8050. var propertyType = propertyDescriptor.type;
  8051. if (sourceProperty !== undefined && sourceProperty !== null) {
  8052. var dest = destination;
  8053. switch (propertyType) {
  8054. case 0: // Value
  8055. dest[property] = sourceProperty;
  8056. break;
  8057. case 1: // Texture
  8058. if (scene) {
  8059. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8060. }
  8061. break;
  8062. case 2: // Color3
  8063. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8064. break;
  8065. case 3: // FresnelParameters
  8066. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8067. break;
  8068. case 4: // Vector2
  8069. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8070. break;
  8071. case 5: // Vector3
  8072. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8073. break;
  8074. case 6: // Mesh reference
  8075. if (scene) {
  8076. dest[property] = scene.getLastMeshByID(sourceProperty);
  8077. }
  8078. break;
  8079. case 7: // Color Curves
  8080. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8081. break;
  8082. case 8: // Color 4
  8083. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8084. break;
  8085. case 9: // Image Processing
  8086. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8087. break;
  8088. case 10: // Quaternion
  8089. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8090. break;
  8091. case 11: // Camera reference
  8092. if (scene) {
  8093. dest[property] = scene.getCameraByID(sourceProperty);
  8094. }
  8095. break;
  8096. }
  8097. }
  8098. }
  8099. return destination;
  8100. };
  8101. SerializationHelper.Clone = function (creationFunction, source) {
  8102. return _copySource(creationFunction, source, false);
  8103. };
  8104. SerializationHelper.Instanciate = function (creationFunction, source) {
  8105. return _copySource(creationFunction, source, true);
  8106. };
  8107. return SerializationHelper;
  8108. }());
  8109. BABYLON.SerializationHelper = SerializationHelper;
  8110. })(BABYLON || (BABYLON = {}));
  8111. //# sourceMappingURL=babylon.decorators.js.map
  8112. var BABYLON;
  8113. (function (BABYLON) {
  8114. /**
  8115. * Wrapper class for promise with external resolve and reject.
  8116. */
  8117. var Deferred = /** @class */ (function () {
  8118. /**
  8119. * Constructor for this deferred object.
  8120. */
  8121. function Deferred() {
  8122. var _this = this;
  8123. this.promise = new Promise(function (resolve, reject) {
  8124. _this._resolve = resolve;
  8125. _this._reject = reject;
  8126. });
  8127. }
  8128. Object.defineProperty(Deferred.prototype, "resolve", {
  8129. /**
  8130. * The resolve method of the promise associated with this deferred object.
  8131. */
  8132. get: function () {
  8133. return this._resolve;
  8134. },
  8135. enumerable: true,
  8136. configurable: true
  8137. });
  8138. Object.defineProperty(Deferred.prototype, "reject", {
  8139. /**
  8140. * The reject method of the promise associated with this deferred object.
  8141. */
  8142. get: function () {
  8143. return this._reject;
  8144. },
  8145. enumerable: true,
  8146. configurable: true
  8147. });
  8148. return Deferred;
  8149. }());
  8150. BABYLON.Deferred = Deferred;
  8151. })(BABYLON || (BABYLON = {}));
  8152. //# sourceMappingURL=babylon.deferred.js.map
  8153. var BABYLON;
  8154. (function (BABYLON) {
  8155. /**
  8156. * A class serves as a medium between the observable and its observers
  8157. */
  8158. var EventState = /** @class */ (function () {
  8159. /**
  8160. * Create a new EventState
  8161. * @param mask defines the mask associated with this state
  8162. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8163. * @param target defines the original target of the state
  8164. * @param currentTarget defines the current target of the state
  8165. */
  8166. function EventState(mask, skipNextObservers, target, currentTarget) {
  8167. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8168. this.initalize(mask, skipNextObservers, target, currentTarget);
  8169. }
  8170. /**
  8171. * Initialize the current event state
  8172. * @param mask defines the mask associated with this state
  8173. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8174. * @param target defines the original target of the state
  8175. * @param currentTarget defines the current target of the state
  8176. * @returns the current event state
  8177. */
  8178. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8179. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8180. this.mask = mask;
  8181. this.skipNextObservers = skipNextObservers;
  8182. this.target = target;
  8183. this.currentTarget = currentTarget;
  8184. return this;
  8185. };
  8186. return EventState;
  8187. }());
  8188. BABYLON.EventState = EventState;
  8189. /**
  8190. * Represent an Observer registered to a given Observable object.
  8191. */
  8192. var Observer = /** @class */ (function () {
  8193. /**
  8194. * Creates a new observer
  8195. * @param callback defines the callback to call when the observer is notified
  8196. * @param mask defines the mask of the observer (used to filter notifications)
  8197. * @param scope defines the current scope used to restore the JS context
  8198. */
  8199. function Observer(
  8200. /**
  8201. * Defines the callback to call when the observer is notified
  8202. */
  8203. callback,
  8204. /**
  8205. * Defines the mask of the observer (used to filter notifications)
  8206. */
  8207. mask,
  8208. /**
  8209. * Defines the current scope used to restore the JS context
  8210. */
  8211. scope) {
  8212. if (scope === void 0) { scope = null; }
  8213. this.callback = callback;
  8214. this.mask = mask;
  8215. this.scope = scope;
  8216. /** @hidden */
  8217. this._willBeUnregistered = false;
  8218. /**
  8219. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8220. */
  8221. this.unregisterOnNextCall = false;
  8222. }
  8223. return Observer;
  8224. }());
  8225. BABYLON.Observer = Observer;
  8226. /**
  8227. * Represent a list of observers registered to multiple Observables object.
  8228. */
  8229. var MultiObserver = /** @class */ (function () {
  8230. function MultiObserver() {
  8231. }
  8232. /**
  8233. * Release associated resources
  8234. */
  8235. MultiObserver.prototype.dispose = function () {
  8236. if (this._observers && this._observables) {
  8237. for (var index = 0; index < this._observers.length; index++) {
  8238. this._observables[index].remove(this._observers[index]);
  8239. }
  8240. }
  8241. this._observers = null;
  8242. this._observables = null;
  8243. };
  8244. /**
  8245. * Raise a callback when one of the observable will notify
  8246. * @param observables defines a list of observables to watch
  8247. * @param callback defines the callback to call on notification
  8248. * @param mask defines the mask used to filter notifications
  8249. * @param scope defines the current scope used to restore the JS context
  8250. * @returns the new MultiObserver
  8251. */
  8252. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8253. if (mask === void 0) { mask = -1; }
  8254. if (scope === void 0) { scope = null; }
  8255. var result = new MultiObserver();
  8256. result._observers = new Array();
  8257. result._observables = observables;
  8258. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8259. var observable = observables_1[_i];
  8260. var observer = observable.add(callback, mask, false, scope);
  8261. if (observer) {
  8262. result._observers.push(observer);
  8263. }
  8264. }
  8265. return result;
  8266. };
  8267. return MultiObserver;
  8268. }());
  8269. BABYLON.MultiObserver = MultiObserver;
  8270. /**
  8271. * The Observable class is a simple implementation of the Observable pattern.
  8272. *
  8273. * 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.
  8274. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8275. * 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).
  8276. * 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.
  8277. */
  8278. var Observable = /** @class */ (function () {
  8279. /**
  8280. * Creates a new observable
  8281. * @param onObserverAdded defines a callback to call when a new observer is added
  8282. */
  8283. function Observable(onObserverAdded) {
  8284. this._observers = new Array();
  8285. this._eventState = new EventState(0);
  8286. if (onObserverAdded) {
  8287. this._onObserverAdded = onObserverAdded;
  8288. }
  8289. }
  8290. /**
  8291. * Create a new Observer with the specified callback
  8292. * @param callback the callback that will be executed for that Observer
  8293. * @param mask the mask used to filter observers
  8294. * @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.
  8295. * @param scope optional scope for the callback to be called from
  8296. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8297. * @returns the new observer created for the callback
  8298. */
  8299. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8300. if (mask === void 0) { mask = -1; }
  8301. if (insertFirst === void 0) { insertFirst = false; }
  8302. if (scope === void 0) { scope = null; }
  8303. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8304. if (!callback) {
  8305. return null;
  8306. }
  8307. var observer = new Observer(callback, mask, scope);
  8308. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8309. if (insertFirst) {
  8310. this._observers.unshift(observer);
  8311. }
  8312. else {
  8313. this._observers.push(observer);
  8314. }
  8315. if (this._onObserverAdded) {
  8316. this._onObserverAdded(observer);
  8317. }
  8318. return observer;
  8319. };
  8320. /**
  8321. * Create a new Observer with the specified callback and unregisters after the next notification
  8322. * @param callback the callback that will be executed for that Observer
  8323. * @returns the new observer created for the callback
  8324. */
  8325. Observable.prototype.addOnce = function (callback) {
  8326. return this.add(callback, undefined, undefined, undefined, true);
  8327. };
  8328. /**
  8329. * Remove an Observer from the Observable object
  8330. * @param observer the instance of the Observer to remove
  8331. * @returns false if it doesn't belong to this Observable
  8332. */
  8333. Observable.prototype.remove = function (observer) {
  8334. if (!observer) {
  8335. return false;
  8336. }
  8337. var index = this._observers.indexOf(observer);
  8338. if (index !== -1) {
  8339. this._deferUnregister(observer);
  8340. return true;
  8341. }
  8342. return false;
  8343. };
  8344. /**
  8345. * Remove a callback from the Observable object
  8346. * @param callback the callback to remove
  8347. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8348. * @returns false if it doesn't belong to this Observable
  8349. */
  8350. Observable.prototype.removeCallback = function (callback, scope) {
  8351. for (var index = 0; index < this._observers.length; index++) {
  8352. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8353. this._deferUnregister(this._observers[index]);
  8354. return true;
  8355. }
  8356. }
  8357. return false;
  8358. };
  8359. Observable.prototype._deferUnregister = function (observer) {
  8360. var _this = this;
  8361. observer.unregisterOnNextCall = false;
  8362. observer._willBeUnregistered = true;
  8363. BABYLON.Tools.SetImmediate(function () {
  8364. _this._remove(observer);
  8365. });
  8366. };
  8367. // This should only be called when not iterating over _observers to avoid callback skipping.
  8368. // Removes an observer from the _observer Array.
  8369. Observable.prototype._remove = function (observer) {
  8370. if (!observer) {
  8371. return false;
  8372. }
  8373. var index = this._observers.indexOf(observer);
  8374. if (index !== -1) {
  8375. this._observers.splice(index, 1);
  8376. return true;
  8377. }
  8378. return false;
  8379. };
  8380. /**
  8381. * Notify all Observers by calling their respective callback with the given data
  8382. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8383. * @param eventData defines the data to send to all observers
  8384. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8385. * @param target defines the original target of the state
  8386. * @param currentTarget defines the current target of the state
  8387. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8388. */
  8389. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8390. if (mask === void 0) { mask = -1; }
  8391. if (!this._observers.length) {
  8392. return true;
  8393. }
  8394. var state = this._eventState;
  8395. state.mask = mask;
  8396. state.target = target;
  8397. state.currentTarget = currentTarget;
  8398. state.skipNextObservers = false;
  8399. state.lastReturnValue = eventData;
  8400. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8401. var obs = _a[_i];
  8402. if (obs._willBeUnregistered) {
  8403. continue;
  8404. }
  8405. if (obs.mask & mask) {
  8406. if (obs.scope) {
  8407. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8408. }
  8409. else {
  8410. state.lastReturnValue = obs.callback(eventData, state);
  8411. }
  8412. if (obs.unregisterOnNextCall) {
  8413. this._deferUnregister(obs);
  8414. }
  8415. }
  8416. if (state.skipNextObservers) {
  8417. return false;
  8418. }
  8419. }
  8420. return true;
  8421. };
  8422. /**
  8423. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8424. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8425. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8426. * and it is crucial that all callbacks will be executed.
  8427. * The order of the callbacks is kept, callbacks are not executed parallel.
  8428. *
  8429. * @param eventData The data to be sent to each callback
  8430. * @param mask is used to filter observers defaults to -1
  8431. * @param target defines the callback target (see EventState)
  8432. * @param currentTarget defines he current object in the bubbling phase
  8433. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8434. */
  8435. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8436. var _this = this;
  8437. if (mask === void 0) { mask = -1; }
  8438. // create an empty promise
  8439. var p = Promise.resolve(eventData);
  8440. // no observers? return this promise.
  8441. if (!this._observers.length) {
  8442. return p;
  8443. }
  8444. var state = this._eventState;
  8445. state.mask = mask;
  8446. state.target = target;
  8447. state.currentTarget = currentTarget;
  8448. state.skipNextObservers = false;
  8449. // execute one callback after another (not using Promise.all, the order is important)
  8450. this._observers.forEach(function (obs) {
  8451. if (state.skipNextObservers) {
  8452. return;
  8453. }
  8454. if (obs._willBeUnregistered) {
  8455. return;
  8456. }
  8457. if (obs.mask & mask) {
  8458. if (obs.scope) {
  8459. p = p.then(function (lastReturnedValue) {
  8460. state.lastReturnValue = lastReturnedValue;
  8461. return obs.callback.apply(obs.scope, [eventData, state]);
  8462. });
  8463. }
  8464. else {
  8465. p = p.then(function (lastReturnedValue) {
  8466. state.lastReturnValue = lastReturnedValue;
  8467. return obs.callback(eventData, state);
  8468. });
  8469. }
  8470. if (obs.unregisterOnNextCall) {
  8471. _this._deferUnregister(obs);
  8472. }
  8473. }
  8474. });
  8475. // return the eventData
  8476. return p.then(function () { return eventData; });
  8477. };
  8478. /**
  8479. * Notify a specific observer
  8480. * @param observer defines the observer to notify
  8481. * @param eventData defines the data to be sent to each callback
  8482. * @param mask is used to filter observers defaults to -1
  8483. */
  8484. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8485. if (mask === void 0) { mask = -1; }
  8486. var state = this._eventState;
  8487. state.mask = mask;
  8488. state.skipNextObservers = false;
  8489. observer.callback(eventData, state);
  8490. };
  8491. /**
  8492. * Gets a boolean indicating if the observable has at least one observer
  8493. * @returns true is the Observable has at least one Observer registered
  8494. */
  8495. Observable.prototype.hasObservers = function () {
  8496. return this._observers.length > 0;
  8497. };
  8498. /**
  8499. * Clear the list of observers
  8500. */
  8501. Observable.prototype.clear = function () {
  8502. this._observers = new Array();
  8503. this._onObserverAdded = null;
  8504. };
  8505. /**
  8506. * Clone the current observable
  8507. * @returns a new observable
  8508. */
  8509. Observable.prototype.clone = function () {
  8510. var result = new Observable();
  8511. result._observers = this._observers.slice(0);
  8512. return result;
  8513. };
  8514. /**
  8515. * Does this observable handles observer registered with a given mask
  8516. * @param mask defines the mask to be tested
  8517. * @return whether or not one observer registered with the given mask is handeled
  8518. **/
  8519. Observable.prototype.hasSpecificMask = function (mask) {
  8520. if (mask === void 0) { mask = -1; }
  8521. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8522. var obs = _a[_i];
  8523. if (obs.mask & mask || obs.mask === mask) {
  8524. return true;
  8525. }
  8526. }
  8527. return false;
  8528. };
  8529. return Observable;
  8530. }());
  8531. BABYLON.Observable = Observable;
  8532. })(BABYLON || (BABYLON = {}));
  8533. //# sourceMappingURL=babylon.observable.js.map
  8534. var BABYLON;
  8535. (function (BABYLON) {
  8536. /**
  8537. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8538. */
  8539. var SmartArray = /** @class */ (function () {
  8540. /**
  8541. * Instantiates a Smart Array.
  8542. * @param capacity defines the default capacity of the array.
  8543. */
  8544. function SmartArray(capacity) {
  8545. /**
  8546. * The active length of the array.
  8547. */
  8548. this.length = 0;
  8549. this.data = new Array(capacity);
  8550. this._id = SmartArray._GlobalId++;
  8551. }
  8552. /**
  8553. * Pushes a value at the end of the active data.
  8554. * @param value defines the object to push in the array.
  8555. */
  8556. SmartArray.prototype.push = function (value) {
  8557. this.data[this.length++] = value;
  8558. if (this.length > this.data.length) {
  8559. this.data.length *= 2;
  8560. }
  8561. };
  8562. /**
  8563. * Iterates over the active data and apply the lambda to them.
  8564. * @param func defines the action to apply on each value.
  8565. */
  8566. SmartArray.prototype.forEach = function (func) {
  8567. for (var index = 0; index < this.length; index++) {
  8568. func(this.data[index]);
  8569. }
  8570. };
  8571. /**
  8572. * Sorts the full sets of data.
  8573. * @param compareFn defines the comparison function to apply.
  8574. */
  8575. SmartArray.prototype.sort = function (compareFn) {
  8576. this.data.sort(compareFn);
  8577. };
  8578. /**
  8579. * Resets the active data to an empty array.
  8580. */
  8581. SmartArray.prototype.reset = function () {
  8582. this.length = 0;
  8583. };
  8584. /**
  8585. * Releases all the data from the array as well as the array.
  8586. */
  8587. SmartArray.prototype.dispose = function () {
  8588. this.reset();
  8589. if (this.data) {
  8590. this.data.length = 0;
  8591. this.data = [];
  8592. }
  8593. };
  8594. /**
  8595. * Concats the active data with a given array.
  8596. * @param array defines the data to concatenate with.
  8597. */
  8598. SmartArray.prototype.concat = function (array) {
  8599. if (array.length === 0) {
  8600. return;
  8601. }
  8602. if (this.length + array.length > this.data.length) {
  8603. this.data.length = (this.length + array.length) * 2;
  8604. }
  8605. for (var index = 0; index < array.length; index++) {
  8606. this.data[this.length++] = (array.data || array)[index];
  8607. }
  8608. };
  8609. /**
  8610. * Returns the position of a value in the active data.
  8611. * @param value defines the value to find the index for
  8612. * @returns the index if found in the active data otherwise -1
  8613. */
  8614. SmartArray.prototype.indexOf = function (value) {
  8615. var position = this.data.indexOf(value);
  8616. if (position >= this.length) {
  8617. return -1;
  8618. }
  8619. return position;
  8620. };
  8621. /**
  8622. * Returns whether an element is part of the active data.
  8623. * @param value defines the value to look for
  8624. * @returns true if found in the active data otherwise false
  8625. */
  8626. SmartArray.prototype.contains = function (value) {
  8627. return this.indexOf(value) !== -1;
  8628. };
  8629. // Statics
  8630. SmartArray._GlobalId = 0;
  8631. return SmartArray;
  8632. }());
  8633. BABYLON.SmartArray = SmartArray;
  8634. /**
  8635. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8636. * The data in this array can only be present once
  8637. */
  8638. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8639. __extends(SmartArrayNoDuplicate, _super);
  8640. function SmartArrayNoDuplicate() {
  8641. var _this = _super !== null && _super.apply(this, arguments) || this;
  8642. _this._duplicateId = 0;
  8643. return _this;
  8644. }
  8645. /**
  8646. * Pushes a value at the end of the active data.
  8647. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8648. * @param value defines the object to push in the array.
  8649. */
  8650. SmartArrayNoDuplicate.prototype.push = function (value) {
  8651. _super.prototype.push.call(this, value);
  8652. if (!value.__smartArrayFlags) {
  8653. value.__smartArrayFlags = {};
  8654. }
  8655. value.__smartArrayFlags[this._id] = this._duplicateId;
  8656. };
  8657. /**
  8658. * Pushes a value at the end of the active data.
  8659. * If the data is already present, it won t be added again
  8660. * @param value defines the object to push in the array.
  8661. * @returns true if added false if it was already present
  8662. */
  8663. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8664. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8665. return false;
  8666. }
  8667. this.push(value);
  8668. return true;
  8669. };
  8670. /**
  8671. * Resets the active data to an empty array.
  8672. */
  8673. SmartArrayNoDuplicate.prototype.reset = function () {
  8674. _super.prototype.reset.call(this);
  8675. this._duplicateId++;
  8676. };
  8677. /**
  8678. * Concats the active data with a given array.
  8679. * This ensures no dupplicate will be present in the result.
  8680. * @param array defines the data to concatenate with.
  8681. */
  8682. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8683. if (array.length === 0) {
  8684. return;
  8685. }
  8686. if (this.length + array.length > this.data.length) {
  8687. this.data.length = (this.length + array.length) * 2;
  8688. }
  8689. for (var index = 0; index < array.length; index++) {
  8690. var item = (array.data || array)[index];
  8691. this.pushNoDuplicate(item);
  8692. }
  8693. };
  8694. return SmartArrayNoDuplicate;
  8695. }(SmartArray));
  8696. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8697. })(BABYLON || (BABYLON = {}));
  8698. //# sourceMappingURL=babylon.smartArray.js.map
  8699. var BABYLON;
  8700. (function (BABYLON) {
  8701. /** Class used to store color4 gradient */
  8702. var ColorGradient = /** @class */ (function () {
  8703. function ColorGradient() {
  8704. }
  8705. /**
  8706. * Will get a color picked randomly between color1 and color2.
  8707. * If color2 is undefined then color1 will be used
  8708. * @param result defines the target Color4 to store the result in
  8709. */
  8710. ColorGradient.prototype.getColorToRef = function (result) {
  8711. if (!this.color2) {
  8712. result.copyFrom(this.color1);
  8713. return;
  8714. }
  8715. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8716. };
  8717. return ColorGradient;
  8718. }());
  8719. BABYLON.ColorGradient = ColorGradient;
  8720. /** Class used to store color 3 gradient */
  8721. var Color3Gradient = /** @class */ (function () {
  8722. function Color3Gradient() {
  8723. }
  8724. return Color3Gradient;
  8725. }());
  8726. BABYLON.Color3Gradient = Color3Gradient;
  8727. /** Class used to store factor gradient */
  8728. var FactorGradient = /** @class */ (function () {
  8729. function FactorGradient() {
  8730. }
  8731. /**
  8732. * Will get a number picked randomly between factor1 and factor2.
  8733. * If factor2 is undefined then factor1 will be used
  8734. * @returns the picked number
  8735. */
  8736. FactorGradient.prototype.getFactor = function () {
  8737. if (this.factor2 === undefined) {
  8738. return this.factor1;
  8739. }
  8740. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8741. };
  8742. return FactorGradient;
  8743. }());
  8744. BABYLON.FactorGradient = FactorGradient;
  8745. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8746. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8747. var LoadFileError = /** @class */ (function (_super) {
  8748. __extends(LoadFileError, _super);
  8749. function LoadFileError(message, request) {
  8750. var _this = _super.call(this, message) || this;
  8751. _this.request = request;
  8752. _this.name = "LoadFileError";
  8753. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8754. return _this;
  8755. }
  8756. // Polyfill for Object.setPrototypeOf if necessary.
  8757. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8758. return LoadFileError;
  8759. }(Error));
  8760. BABYLON.LoadFileError = LoadFileError;
  8761. var RetryStrategy = /** @class */ (function () {
  8762. function RetryStrategy() {
  8763. }
  8764. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8765. if (maxRetries === void 0) { maxRetries = 3; }
  8766. if (baseInterval === void 0) { baseInterval = 500; }
  8767. return function (url, request, retryIndex) {
  8768. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8769. return -1;
  8770. }
  8771. return Math.pow(2, retryIndex) * baseInterval;
  8772. };
  8773. };
  8774. return RetryStrategy;
  8775. }());
  8776. BABYLON.RetryStrategy = RetryStrategy;
  8777. // Screenshots
  8778. var screenshotCanvas;
  8779. var cloneValue = function (source, destinationObject) {
  8780. if (!source)
  8781. return null;
  8782. if (source instanceof BABYLON.Mesh) {
  8783. return null;
  8784. }
  8785. if (source instanceof BABYLON.SubMesh) {
  8786. return source.clone(destinationObject);
  8787. }
  8788. else if (source.clone) {
  8789. return source.clone();
  8790. }
  8791. return null;
  8792. };
  8793. var Tools = /** @class */ (function () {
  8794. function Tools() {
  8795. }
  8796. /**
  8797. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8798. * @param u defines the coordinate on X axis
  8799. * @param v defines the coordinate on Y axis
  8800. * @param width defines the width of the source data
  8801. * @param height defines the height of the source data
  8802. * @param pixels defines the source byte array
  8803. * @param color defines the output color
  8804. */
  8805. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8806. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8807. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8808. var position = (wrappedU + wrappedV * width) * 4;
  8809. color.r = pixels[position] / 255;
  8810. color.g = pixels[position + 1] / 255;
  8811. color.b = pixels[position + 2] / 255;
  8812. color.a = pixels[position + 3] / 255;
  8813. };
  8814. /**
  8815. * Interpolates between a and b via alpha
  8816. * @param a The lower value (returned when alpha = 0)
  8817. * @param b The upper value (returned when alpha = 1)
  8818. * @param alpha The interpolation-factor
  8819. * @return The mixed value
  8820. */
  8821. Tools.Mix = function (a, b, alpha) {
  8822. return a * (1 - alpha) + b * alpha;
  8823. };
  8824. Tools.Instantiate = function (className) {
  8825. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8826. return Tools.RegisteredExternalClasses[className];
  8827. }
  8828. var arr = className.split(".");
  8829. var fn = (window || this);
  8830. for (var i = 0, len = arr.length; i < len; i++) {
  8831. fn = fn[arr[i]];
  8832. }
  8833. if (typeof fn !== "function") {
  8834. return null;
  8835. }
  8836. return fn;
  8837. };
  8838. /**
  8839. * Provides a slice function that will work even on IE
  8840. * @param data defines the array to slice
  8841. * @param start defines the start of the data (optional)
  8842. * @param end defines the end of the data (optional)
  8843. * @returns the new sliced array
  8844. */
  8845. Tools.Slice = function (data, start, end) {
  8846. if (data.slice) {
  8847. return data.slice(start, end);
  8848. }
  8849. return Array.prototype.slice.call(data, start, end);
  8850. };
  8851. Tools.SetImmediate = function (action) {
  8852. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8853. window.setImmediate(action);
  8854. }
  8855. else {
  8856. setTimeout(action, 1);
  8857. }
  8858. };
  8859. Tools.IsExponentOfTwo = function (value) {
  8860. var count = 1;
  8861. do {
  8862. count *= 2;
  8863. } while (count < value);
  8864. return count === value;
  8865. };
  8866. /**
  8867. * Returns the nearest 32-bit single precision float representation of a Number
  8868. * @param value A Number. If the parameter is of a different type, it will get converted
  8869. * to a number or to NaN if it cannot be converted
  8870. * @returns number
  8871. */
  8872. Tools.FloatRound = function (value) {
  8873. if (Math.fround) {
  8874. return Math.fround(value);
  8875. }
  8876. return (Tools._tmpFloatArray[0] = value);
  8877. };
  8878. /**
  8879. * Find the next highest power of two.
  8880. * @param x Number to start search from.
  8881. * @return Next highest power of two.
  8882. */
  8883. Tools.CeilingPOT = function (x) {
  8884. x--;
  8885. x |= x >> 1;
  8886. x |= x >> 2;
  8887. x |= x >> 4;
  8888. x |= x >> 8;
  8889. x |= x >> 16;
  8890. x++;
  8891. return x;
  8892. };
  8893. /**
  8894. * Find the next lowest power of two.
  8895. * @param x Number to start search from.
  8896. * @return Next lowest power of two.
  8897. */
  8898. Tools.FloorPOT = function (x) {
  8899. x = x | (x >> 1);
  8900. x = x | (x >> 2);
  8901. x = x | (x >> 4);
  8902. x = x | (x >> 8);
  8903. x = x | (x >> 16);
  8904. return x - (x >> 1);
  8905. };
  8906. /**
  8907. * Find the nearest power of two.
  8908. * @param x Number to start search from.
  8909. * @return Next nearest power of two.
  8910. */
  8911. Tools.NearestPOT = function (x) {
  8912. var c = Tools.CeilingPOT(x);
  8913. var f = Tools.FloorPOT(x);
  8914. return (c - x) > (x - f) ? f : c;
  8915. };
  8916. Tools.GetExponentOfTwo = function (value, max, mode) {
  8917. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8918. var pot;
  8919. switch (mode) {
  8920. case BABYLON.Engine.SCALEMODE_FLOOR:
  8921. pot = Tools.FloorPOT(value);
  8922. break;
  8923. case BABYLON.Engine.SCALEMODE_NEAREST:
  8924. pot = Tools.NearestPOT(value);
  8925. break;
  8926. case BABYLON.Engine.SCALEMODE_CEILING:
  8927. default:
  8928. pot = Tools.CeilingPOT(value);
  8929. break;
  8930. }
  8931. return Math.min(pot, max);
  8932. };
  8933. Tools.GetFilename = function (path) {
  8934. var index = path.lastIndexOf("/");
  8935. if (index < 0)
  8936. return path;
  8937. return path.substring(index + 1);
  8938. };
  8939. /**
  8940. * Extracts the "folder" part of a path (everything before the filename).
  8941. * @param uri The URI to extract the info from
  8942. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8943. * @returns The "folder" part of the path
  8944. */
  8945. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8946. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8947. var index = uri.lastIndexOf("/");
  8948. if (index < 0) {
  8949. if (returnUnchangedIfNoSlash) {
  8950. return uri;
  8951. }
  8952. return "";
  8953. }
  8954. return uri.substring(0, index + 1);
  8955. };
  8956. Tools.GetDOMTextContent = function (element) {
  8957. var result = "";
  8958. var child = element.firstChild;
  8959. while (child) {
  8960. if (child.nodeType === 3) {
  8961. result += child.textContent;
  8962. }
  8963. child = child.nextSibling;
  8964. }
  8965. return result;
  8966. };
  8967. Tools.ToDegrees = function (angle) {
  8968. return angle * 180 / Math.PI;
  8969. };
  8970. Tools.ToRadians = function (angle) {
  8971. return angle * Math.PI / 180;
  8972. };
  8973. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8974. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8975. var output = "";
  8976. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8977. var i = 0;
  8978. var bytes = new Uint8Array(buffer);
  8979. while (i < bytes.length) {
  8980. chr1 = bytes[i++];
  8981. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8982. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8983. enc1 = chr1 >> 2;
  8984. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8985. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8986. enc4 = chr3 & 63;
  8987. if (isNaN(chr2)) {
  8988. enc3 = enc4 = 64;
  8989. }
  8990. else if (isNaN(chr3)) {
  8991. enc4 = 64;
  8992. }
  8993. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8994. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8995. }
  8996. return "data:image/png;base64," + output;
  8997. };
  8998. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8999. if (bias === void 0) { bias = null; }
  9000. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9001. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9002. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9003. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9004. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9005. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9006. }
  9007. if (bias) {
  9008. minimum.x -= minimum.x * bias.x + bias.y;
  9009. minimum.y -= minimum.y * bias.x + bias.y;
  9010. minimum.z -= minimum.z * bias.x + bias.y;
  9011. maximum.x += maximum.x * bias.x + bias.y;
  9012. maximum.y += maximum.y * bias.x + bias.y;
  9013. maximum.z += maximum.z * bias.x + bias.y;
  9014. }
  9015. return {
  9016. minimum: minimum,
  9017. maximum: maximum
  9018. };
  9019. };
  9020. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9021. if (bias === void 0) { bias = null; }
  9022. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9023. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9024. if (!stride) {
  9025. stride = 3;
  9026. }
  9027. for (var index = start; index < start + count; index++) {
  9028. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9029. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9030. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9031. }
  9032. if (bias) {
  9033. minimum.x -= minimum.x * bias.x + bias.y;
  9034. minimum.y -= minimum.y * bias.x + bias.y;
  9035. minimum.z -= minimum.z * bias.x + bias.y;
  9036. maximum.x += maximum.x * bias.x + bias.y;
  9037. maximum.y += maximum.y * bias.x + bias.y;
  9038. maximum.z += maximum.z * bias.x + bias.y;
  9039. }
  9040. return {
  9041. minimum: minimum,
  9042. maximum: maximum
  9043. };
  9044. };
  9045. Tools.Vector2ArrayFeeder = function (array) {
  9046. return function (index) {
  9047. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9048. var length = isFloatArray ? array.length / 2 : array.length;
  9049. if (index >= length) {
  9050. return null;
  9051. }
  9052. if (isFloatArray) {
  9053. var fa = array;
  9054. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9055. }
  9056. var a = array;
  9057. return a[index];
  9058. };
  9059. };
  9060. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9061. if (bias === void 0) { bias = null; }
  9062. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9063. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9064. var i = 0;
  9065. var cur = feeder(i++);
  9066. while (cur) {
  9067. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9068. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9069. cur = feeder(i++);
  9070. }
  9071. if (bias) {
  9072. minimum.x -= minimum.x * bias.x + bias.y;
  9073. minimum.y -= minimum.y * bias.x + bias.y;
  9074. maximum.x += maximum.x * bias.x + bias.y;
  9075. maximum.y += maximum.y * bias.x + bias.y;
  9076. }
  9077. return {
  9078. minimum: minimum,
  9079. maximum: maximum
  9080. };
  9081. };
  9082. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9083. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9084. return null;
  9085. return Array.isArray(obj) ? obj : [obj];
  9086. };
  9087. // Misc.
  9088. Tools.GetPointerPrefix = function () {
  9089. var eventPrefix = "pointer";
  9090. // Check if pointer events are supported
  9091. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9092. eventPrefix = "mouse";
  9093. }
  9094. return eventPrefix;
  9095. };
  9096. /**
  9097. * @param func - the function to be called
  9098. * @param requester - the object that will request the next frame. Falls back to window.
  9099. */
  9100. Tools.QueueNewFrame = function (func, requester) {
  9101. if (!Tools.IsWindowObjectExist()) {
  9102. return setTimeout(func, 16);
  9103. }
  9104. if (!requester) {
  9105. requester = window;
  9106. }
  9107. if (requester.requestAnimationFrame) {
  9108. return requester.requestAnimationFrame(func);
  9109. }
  9110. else if (requester.msRequestAnimationFrame) {
  9111. return requester.msRequestAnimationFrame(func);
  9112. }
  9113. else if (requester.webkitRequestAnimationFrame) {
  9114. return requester.webkitRequestAnimationFrame(func);
  9115. }
  9116. else if (requester.mozRequestAnimationFrame) {
  9117. return requester.mozRequestAnimationFrame(func);
  9118. }
  9119. else if (requester.oRequestAnimationFrame) {
  9120. return requester.oRequestAnimationFrame(func);
  9121. }
  9122. else {
  9123. return window.setTimeout(func, 16);
  9124. }
  9125. };
  9126. Tools.RequestFullscreen = function (element) {
  9127. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9128. if (!requestFunction)
  9129. return;
  9130. requestFunction.call(element);
  9131. };
  9132. Tools.ExitFullscreen = function () {
  9133. if (document.exitFullscreen) {
  9134. document.exitFullscreen();
  9135. }
  9136. else if (document.mozCancelFullScreen) {
  9137. document.mozCancelFullScreen();
  9138. }
  9139. else if (document.webkitCancelFullScreen) {
  9140. document.webkitCancelFullScreen();
  9141. }
  9142. else if (document.msCancelFullScreen) {
  9143. document.msCancelFullScreen();
  9144. }
  9145. };
  9146. Tools.SetCorsBehavior = function (url, element) {
  9147. if (url && url.indexOf("data:") === 0) {
  9148. return;
  9149. }
  9150. if (Tools.CorsBehavior) {
  9151. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9152. element.crossOrigin = Tools.CorsBehavior;
  9153. }
  9154. else {
  9155. var result = Tools.CorsBehavior(url);
  9156. if (result) {
  9157. element.crossOrigin = result;
  9158. }
  9159. }
  9160. }
  9161. };
  9162. // External files
  9163. Tools.CleanUrl = function (url) {
  9164. url = url.replace(/#/mg, "%23");
  9165. return url;
  9166. };
  9167. /**
  9168. * Loads an image as an HTMLImageElement.
  9169. * @param input url string, ArrayBuffer, or Blob to load
  9170. * @param onLoad callback called when the image successfully loads
  9171. * @param onError callback called when the image fails to load
  9172. * @param database database for caching
  9173. * @returns the HTMLImageElement of the loaded image
  9174. */
  9175. Tools.LoadImage = function (input, onLoad, onError, database) {
  9176. var url;
  9177. var usingObjectURL = false;
  9178. if (input instanceof ArrayBuffer) {
  9179. url = URL.createObjectURL(new Blob([input]));
  9180. usingObjectURL = true;
  9181. }
  9182. else if (input instanceof Blob) {
  9183. url = URL.createObjectURL(input);
  9184. usingObjectURL = true;
  9185. }
  9186. else {
  9187. url = Tools.CleanUrl(input);
  9188. url = Tools.PreprocessUrl(input);
  9189. }
  9190. var img = new Image();
  9191. Tools.SetCorsBehavior(url, img);
  9192. var loadHandler = function () {
  9193. if (usingObjectURL && img.src) {
  9194. URL.revokeObjectURL(img.src);
  9195. }
  9196. img.removeEventListener("load", loadHandler);
  9197. img.removeEventListener("error", errorHandler);
  9198. onLoad(img);
  9199. };
  9200. var errorHandler = function (err) {
  9201. if (usingObjectURL && img.src) {
  9202. URL.revokeObjectURL(img.src);
  9203. }
  9204. img.removeEventListener("load", loadHandler);
  9205. img.removeEventListener("error", errorHandler);
  9206. Tools.Error("Error while trying to load image: " + input);
  9207. if (onError) {
  9208. onError("Error while trying to load image: " + input, err);
  9209. }
  9210. };
  9211. img.addEventListener("load", loadHandler);
  9212. img.addEventListener("error", errorHandler);
  9213. var noIndexedDB = function () {
  9214. img.src = url;
  9215. };
  9216. var loadFromIndexedDB = function () {
  9217. if (database) {
  9218. database.loadImageFromDB(url, img);
  9219. }
  9220. };
  9221. //ANY database to do!
  9222. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9223. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9224. }
  9225. else {
  9226. if (url.indexOf("file:") !== -1) {
  9227. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9228. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9229. try {
  9230. var blobURL;
  9231. try {
  9232. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9233. }
  9234. catch (ex) {
  9235. // Chrome doesn't support oneTimeOnly parameter
  9236. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9237. }
  9238. img.src = blobURL;
  9239. usingObjectURL = true;
  9240. }
  9241. catch (e) {
  9242. img.src = "";
  9243. }
  9244. return img;
  9245. }
  9246. }
  9247. noIndexedDB();
  9248. }
  9249. return img;
  9250. };
  9251. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9252. url = Tools.CleanUrl(url);
  9253. url = Tools.PreprocessUrl(url);
  9254. // If file and file input are set
  9255. if (url.indexOf("file:") !== -1) {
  9256. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9257. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9258. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9259. }
  9260. }
  9261. var loadUrl = Tools.BaseUrl + url;
  9262. var aborted = false;
  9263. var fileRequest = {
  9264. onCompleteObservable: new BABYLON.Observable(),
  9265. abort: function () { return aborted = true; },
  9266. };
  9267. var requestFile = function () {
  9268. var request = new XMLHttpRequest();
  9269. var retryHandle = null;
  9270. fileRequest.abort = function () {
  9271. aborted = true;
  9272. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9273. request.abort();
  9274. }
  9275. if (retryHandle !== null) {
  9276. clearTimeout(retryHandle);
  9277. retryHandle = null;
  9278. }
  9279. };
  9280. var retryLoop = function (retryIndex) {
  9281. request.open('GET', loadUrl, true);
  9282. if (useArrayBuffer) {
  9283. request.responseType = "arraybuffer";
  9284. }
  9285. if (onProgress) {
  9286. request.addEventListener("progress", onProgress);
  9287. }
  9288. var onLoadEnd = function () {
  9289. request.removeEventListener("loadend", onLoadEnd);
  9290. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9291. fileRequest.onCompleteObservable.clear();
  9292. };
  9293. request.addEventListener("loadend", onLoadEnd);
  9294. var onReadyStateChange = function () {
  9295. if (aborted) {
  9296. return;
  9297. }
  9298. // In case of undefined state in some browsers.
  9299. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9300. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9301. request.removeEventListener("readystatechange", onReadyStateChange);
  9302. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9303. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9304. return;
  9305. }
  9306. var retryStrategy = Tools.DefaultRetryStrategy;
  9307. if (retryStrategy) {
  9308. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9309. if (waitTime !== -1) {
  9310. // Prevent the request from completing for retry.
  9311. request.removeEventListener("loadend", onLoadEnd);
  9312. request = new XMLHttpRequest();
  9313. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9314. return;
  9315. }
  9316. }
  9317. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9318. if (onError) {
  9319. onError(request, e);
  9320. }
  9321. else {
  9322. throw e;
  9323. }
  9324. }
  9325. };
  9326. request.addEventListener("readystatechange", onReadyStateChange);
  9327. request.send();
  9328. };
  9329. retryLoop(0);
  9330. };
  9331. // Caching all files
  9332. if (database && database.enableSceneOffline) {
  9333. var noIndexedDB_1 = function (request) {
  9334. if (request && request.status > 400) {
  9335. if (onError) {
  9336. onError(request);
  9337. }
  9338. }
  9339. else {
  9340. if (!aborted) {
  9341. requestFile();
  9342. }
  9343. }
  9344. };
  9345. var loadFromIndexedDB = function () {
  9346. // TODO: database needs to support aborting and should return a IFileRequest
  9347. if (aborted) {
  9348. return;
  9349. }
  9350. if (database) {
  9351. database.loadFileFromDB(url, function (data) {
  9352. if (!aborted) {
  9353. onSuccess(data);
  9354. }
  9355. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9356. }, onProgress ? function (event) {
  9357. if (!aborted) {
  9358. onProgress(event);
  9359. }
  9360. } : undefined, noIndexedDB_1, useArrayBuffer);
  9361. }
  9362. };
  9363. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9364. }
  9365. else {
  9366. requestFile();
  9367. }
  9368. return fileRequest;
  9369. };
  9370. /**
  9371. * Load a script (identified by an url). When the url returns, the
  9372. * content of this file is added into a new script element, attached to the DOM (body element)
  9373. */
  9374. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9375. if (!Tools.IsWindowObjectExist()) {
  9376. return;
  9377. }
  9378. var head = document.getElementsByTagName('head')[0];
  9379. var script = document.createElement('script');
  9380. script.type = 'text/javascript';
  9381. script.src = scriptUrl;
  9382. script.onload = function () {
  9383. if (onSuccess) {
  9384. onSuccess();
  9385. }
  9386. };
  9387. script.onerror = function (e) {
  9388. if (onError) {
  9389. onError("Unable to load script '" + scriptUrl + "'", e);
  9390. }
  9391. };
  9392. head.appendChild(script);
  9393. };
  9394. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9395. var reader = new FileReader();
  9396. var request = {
  9397. onCompleteObservable: new BABYLON.Observable(),
  9398. abort: function () { return reader.abort(); },
  9399. };
  9400. reader.onloadend = function (e) {
  9401. request.onCompleteObservable.notifyObservers(request);
  9402. };
  9403. reader.onload = function (e) {
  9404. //target doesn't have result from ts 1.3
  9405. callback(e.target['result']);
  9406. };
  9407. reader.onprogress = progressCallback;
  9408. reader.readAsDataURL(fileToLoad);
  9409. return request;
  9410. };
  9411. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9412. var reader = new FileReader();
  9413. var request = {
  9414. onCompleteObservable: new BABYLON.Observable(),
  9415. abort: function () { return reader.abort(); },
  9416. };
  9417. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9418. reader.onerror = function (e) {
  9419. Tools.Log("Error while reading file: " + fileToLoad.name);
  9420. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9421. };
  9422. reader.onload = function (e) {
  9423. //target doesn't have result from ts 1.3
  9424. callback(e.target['result']);
  9425. };
  9426. if (progressCallBack) {
  9427. reader.onprogress = progressCallBack;
  9428. }
  9429. if (!useArrayBuffer) {
  9430. // Asynchronous read
  9431. reader.readAsText(fileToLoad);
  9432. }
  9433. else {
  9434. reader.readAsArrayBuffer(fileToLoad);
  9435. }
  9436. return request;
  9437. };
  9438. //returns a downloadable url to a file content.
  9439. Tools.FileAsURL = function (content) {
  9440. var fileBlob = new Blob([content]);
  9441. var url = window.URL || window.webkitURL;
  9442. var link = url.createObjectURL(fileBlob);
  9443. return link;
  9444. };
  9445. // Misc.
  9446. Tools.Format = function (value, decimals) {
  9447. if (decimals === void 0) { decimals = 2; }
  9448. return value.toFixed(decimals);
  9449. };
  9450. Tools.CheckExtends = function (v, min, max) {
  9451. if (v.x < min.x)
  9452. min.x = v.x;
  9453. if (v.y < min.y)
  9454. min.y = v.y;
  9455. if (v.z < min.z)
  9456. min.z = v.z;
  9457. if (v.x > max.x)
  9458. max.x = v.x;
  9459. if (v.y > max.y)
  9460. max.y = v.y;
  9461. if (v.z > max.z)
  9462. max.z = v.z;
  9463. };
  9464. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9465. for (var prop in source) {
  9466. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9467. continue;
  9468. }
  9469. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9470. continue;
  9471. }
  9472. var sourceValue = source[prop];
  9473. var typeOfSourceValue = typeof sourceValue;
  9474. if (typeOfSourceValue === "function") {
  9475. continue;
  9476. }
  9477. try {
  9478. if (typeOfSourceValue === "object") {
  9479. if (sourceValue instanceof Array) {
  9480. destination[prop] = [];
  9481. if (sourceValue.length > 0) {
  9482. if (typeof sourceValue[0] == "object") {
  9483. for (var index = 0; index < sourceValue.length; index++) {
  9484. var clonedValue = cloneValue(sourceValue[index], destination);
  9485. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9486. destination[prop].push(clonedValue);
  9487. }
  9488. }
  9489. }
  9490. else {
  9491. destination[prop] = sourceValue.slice(0);
  9492. }
  9493. }
  9494. }
  9495. else {
  9496. destination[prop] = cloneValue(sourceValue, destination);
  9497. }
  9498. }
  9499. else {
  9500. destination[prop] = sourceValue;
  9501. }
  9502. }
  9503. catch (e) {
  9504. // Just ignore error (it could be because of a read-only property)
  9505. }
  9506. }
  9507. };
  9508. Tools.IsEmpty = function (obj) {
  9509. for (var i in obj) {
  9510. if (obj.hasOwnProperty(i)) {
  9511. return false;
  9512. }
  9513. }
  9514. return true;
  9515. };
  9516. Tools.RegisterTopRootEvents = function (events) {
  9517. for (var index = 0; index < events.length; index++) {
  9518. var event = events[index];
  9519. window.addEventListener(event.name, event.handler, false);
  9520. try {
  9521. if (window.parent) {
  9522. window.parent.addEventListener(event.name, event.handler, false);
  9523. }
  9524. }
  9525. catch (e) {
  9526. // Silently fails...
  9527. }
  9528. }
  9529. };
  9530. Tools.UnregisterTopRootEvents = function (events) {
  9531. for (var index = 0; index < events.length; index++) {
  9532. var event = events[index];
  9533. window.removeEventListener(event.name, event.handler);
  9534. try {
  9535. if (window.parent) {
  9536. window.parent.removeEventListener(event.name, event.handler);
  9537. }
  9538. }
  9539. catch (e) {
  9540. // Silently fails...
  9541. }
  9542. }
  9543. };
  9544. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9545. if (mimeType === void 0) { mimeType = "image/png"; }
  9546. // Read the contents of the framebuffer
  9547. var numberOfChannelsByLine = width * 4;
  9548. var halfHeight = height / 2;
  9549. //Reading datas from WebGL
  9550. var data = engine.readPixels(0, 0, width, height);
  9551. //To flip image on Y axis.
  9552. for (var i = 0; i < halfHeight; i++) {
  9553. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9554. var currentCell = j + i * numberOfChannelsByLine;
  9555. var targetLine = height - i - 1;
  9556. var targetCell = j + targetLine * numberOfChannelsByLine;
  9557. var temp = data[currentCell];
  9558. data[currentCell] = data[targetCell];
  9559. data[targetCell] = temp;
  9560. }
  9561. }
  9562. // Create a 2D canvas to store the result
  9563. if (!screenshotCanvas) {
  9564. screenshotCanvas = document.createElement('canvas');
  9565. }
  9566. screenshotCanvas.width = width;
  9567. screenshotCanvas.height = height;
  9568. var context = screenshotCanvas.getContext('2d');
  9569. if (context) {
  9570. // Copy the pixels to a 2D canvas
  9571. var imageData = context.createImageData(width, height);
  9572. var castData = (imageData.data);
  9573. castData.set(data);
  9574. context.putImageData(imageData, 0, 0);
  9575. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9576. }
  9577. };
  9578. /**
  9579. * Converts the canvas data to blob.
  9580. * This acts as a polyfill for browsers not supporting the to blob function.
  9581. * @param canvas Defines the canvas to extract the data from
  9582. * @param successCallback Defines the callback triggered once the data are available
  9583. * @param mimeType Defines the mime type of the result
  9584. */
  9585. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9586. if (mimeType === void 0) { mimeType = "image/png"; }
  9587. // We need HTMLCanvasElement.toBlob for HD screenshots
  9588. if (!canvas.toBlob) {
  9589. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9590. canvas.toBlob = function (callback, type, quality) {
  9591. var _this = this;
  9592. setTimeout(function () {
  9593. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9594. for (var i = 0; i < len; i++) {
  9595. arr[i] = binStr.charCodeAt(i);
  9596. }
  9597. callback(new Blob([arr]));
  9598. });
  9599. };
  9600. }
  9601. canvas.toBlob(function (blob) {
  9602. successCallback(blob);
  9603. }, mimeType);
  9604. };
  9605. /**
  9606. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9607. * @param successCallback Defines the callback triggered once the data are available
  9608. * @param mimeType Defines the mime type of the result
  9609. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9610. */
  9611. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9612. if (mimeType === void 0) { mimeType = "image/png"; }
  9613. if (successCallback) {
  9614. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9615. successCallback(base64Image);
  9616. }
  9617. else {
  9618. this.ToBlob(screenshotCanvas, function (blob) {
  9619. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9620. if (("download" in document.createElement("a"))) {
  9621. if (!fileName) {
  9622. var date = new Date();
  9623. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9624. fileName = "screenshot_" + stringDate + ".png";
  9625. }
  9626. Tools.Download(blob, fileName);
  9627. }
  9628. else {
  9629. var url = URL.createObjectURL(blob);
  9630. var newWindow = window.open("");
  9631. if (!newWindow)
  9632. return;
  9633. var img = newWindow.document.createElement("img");
  9634. img.onload = function () {
  9635. // no longer need to read the blob so it's revoked
  9636. URL.revokeObjectURL(url);
  9637. };
  9638. img.src = url;
  9639. newWindow.document.body.appendChild(img);
  9640. }
  9641. }, mimeType);
  9642. }
  9643. };
  9644. /**
  9645. * Downloads a blob in the browser
  9646. * @param blob defines the blob to download
  9647. * @param fileName defines the name of the downloaded file
  9648. */
  9649. Tools.Download = function (blob, fileName) {
  9650. if (navigator && navigator.msSaveBlob) {
  9651. navigator.msSaveBlob(blob, fileName);
  9652. return;
  9653. }
  9654. var url = window.URL.createObjectURL(blob);
  9655. var a = document.createElement("a");
  9656. document.body.appendChild(a);
  9657. a.style.display = "none";
  9658. a.href = url;
  9659. a.download = fileName;
  9660. a.addEventListener("click", function () {
  9661. if (a.parentElement) {
  9662. a.parentElement.removeChild(a);
  9663. }
  9664. });
  9665. a.click();
  9666. window.URL.revokeObjectURL(url);
  9667. };
  9668. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9669. if (mimeType === void 0) { mimeType = "image/png"; }
  9670. var width;
  9671. var height;
  9672. // If a precision value is specified
  9673. if (size.precision) {
  9674. width = Math.round(engine.getRenderWidth() * size.precision);
  9675. height = Math.round(width / engine.getAspectRatio(camera));
  9676. }
  9677. else if (size.width && size.height) {
  9678. width = size.width;
  9679. height = size.height;
  9680. }
  9681. //If passing only width, computing height to keep display canvas ratio.
  9682. else if (size.width && !size.height) {
  9683. width = size.width;
  9684. height = Math.round(width / engine.getAspectRatio(camera));
  9685. }
  9686. //If passing only height, computing width to keep display canvas ratio.
  9687. else if (size.height && !size.width) {
  9688. height = size.height;
  9689. width = Math.round(height * engine.getAspectRatio(camera));
  9690. }
  9691. //Assuming here that "size" parameter is a number
  9692. else if (!isNaN(size)) {
  9693. height = size;
  9694. width = size;
  9695. }
  9696. else {
  9697. Tools.Error("Invalid 'size' parameter !");
  9698. return;
  9699. }
  9700. if (!screenshotCanvas) {
  9701. screenshotCanvas = document.createElement('canvas');
  9702. }
  9703. screenshotCanvas.width = width;
  9704. screenshotCanvas.height = height;
  9705. var renderContext = screenshotCanvas.getContext("2d");
  9706. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9707. var newWidth = width;
  9708. var newHeight = newWidth / ratio;
  9709. if (newHeight > height) {
  9710. newHeight = height;
  9711. newWidth = newHeight * ratio;
  9712. }
  9713. var offsetX = Math.max(0, width - newWidth) / 2;
  9714. var offsetY = Math.max(0, height - newHeight) / 2;
  9715. var renderingCanvas = engine.getRenderingCanvas();
  9716. if (renderContext && renderingCanvas) {
  9717. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9718. }
  9719. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9720. };
  9721. /**
  9722. * Generates an image screenshot from the specified camera.
  9723. *
  9724. * @param engine The engine to use for rendering
  9725. * @param camera The camera to use for rendering
  9726. * @param size This parameter can be set to a single number or to an object with the
  9727. * following (optional) properties: precision, width, height. If a single number is passed,
  9728. * it will be used for both width and height. If an object is passed, the screenshot size
  9729. * will be derived from the parameters. The precision property is a multiplier allowing
  9730. * rendering at a higher or lower resolution.
  9731. * @param successCallback The callback receives a single parameter which contains the
  9732. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9733. * src parameter of an <img> to display it.
  9734. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9735. * Check your browser for supported MIME types.
  9736. * @param samples Texture samples (default: 1)
  9737. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9738. * @param fileName A name for for the downloaded file.
  9739. * @constructor
  9740. */
  9741. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9742. if (mimeType === void 0) { mimeType = "image/png"; }
  9743. if (samples === void 0) { samples = 1; }
  9744. if (antialiasing === void 0) { antialiasing = false; }
  9745. var width;
  9746. var height;
  9747. //If a precision value is specified
  9748. if (size.precision) {
  9749. width = Math.round(engine.getRenderWidth() * size.precision);
  9750. height = Math.round(width / engine.getAspectRatio(camera));
  9751. size = { width: width, height: height };
  9752. }
  9753. else if (size.width && size.height) {
  9754. width = size.width;
  9755. height = size.height;
  9756. }
  9757. //If passing only width, computing height to keep display canvas ratio.
  9758. else if (size.width && !size.height) {
  9759. width = size.width;
  9760. height = Math.round(width / engine.getAspectRatio(camera));
  9761. size = { width: width, height: height };
  9762. }
  9763. //If passing only height, computing width to keep display canvas ratio.
  9764. else if (size.height && !size.width) {
  9765. height = size.height;
  9766. width = Math.round(height * engine.getAspectRatio(camera));
  9767. size = { width: width, height: height };
  9768. }
  9769. //Assuming here that "size" parameter is a number
  9770. else if (!isNaN(size)) {
  9771. height = size;
  9772. width = size;
  9773. }
  9774. else {
  9775. Tools.Error("Invalid 'size' parameter !");
  9776. return;
  9777. }
  9778. var scene = camera.getScene();
  9779. var previousCamera = null;
  9780. if (scene.activeCamera !== camera) {
  9781. previousCamera = scene.activeCamera;
  9782. scene.activeCamera = camera;
  9783. }
  9784. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9785. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9786. texture.renderList = null;
  9787. texture.samples = samples;
  9788. if (antialiasing) {
  9789. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9790. }
  9791. texture.onAfterRenderObservable.add(function () {
  9792. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9793. });
  9794. scene.incrementRenderId();
  9795. scene.resetCachedMaterial();
  9796. texture.render(true);
  9797. texture.dispose();
  9798. if (previousCamera) {
  9799. scene.activeCamera = previousCamera;
  9800. }
  9801. camera.getProjectionMatrix(true); // Force cache refresh;
  9802. };
  9803. // XHR response validator for local file scenario
  9804. Tools.ValidateXHRData = function (xhr, dataType) {
  9805. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9806. if (dataType === void 0) { dataType = 7; }
  9807. try {
  9808. if (dataType & 1) {
  9809. if (xhr.responseText && xhr.responseText.length > 0) {
  9810. return true;
  9811. }
  9812. else if (dataType === 1) {
  9813. return false;
  9814. }
  9815. }
  9816. if (dataType & 2) {
  9817. // Check header width and height since there is no "TGA" magic number
  9818. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9819. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9820. return true;
  9821. }
  9822. else if (dataType === 2) {
  9823. return false;
  9824. }
  9825. }
  9826. if (dataType & 4) {
  9827. // Check for the "DDS" magic number
  9828. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9829. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9830. return true;
  9831. }
  9832. else {
  9833. return false;
  9834. }
  9835. }
  9836. }
  9837. catch (e) {
  9838. // Global protection
  9839. }
  9840. return false;
  9841. };
  9842. /**
  9843. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9844. * Be aware Math.random() could cause collisions, but:
  9845. * "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"
  9846. */
  9847. Tools.RandomId = function () {
  9848. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9849. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9850. return v.toString(16);
  9851. });
  9852. };
  9853. /**
  9854. * Test if the given uri is a base64 string.
  9855. * @param uri The uri to test
  9856. * @return True if the uri is a base64 string or false otherwise.
  9857. */
  9858. Tools.IsBase64 = function (uri) {
  9859. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9860. };
  9861. /**
  9862. * Decode the given base64 uri.
  9863. * @param uri The uri to decode
  9864. * @return The decoded base64 data.
  9865. */
  9866. Tools.DecodeBase64 = function (uri) {
  9867. var decodedString = atob(uri.split(",")[1]);
  9868. var bufferLength = decodedString.length;
  9869. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9870. for (var i = 0; i < bufferLength; i++) {
  9871. bufferView[i] = decodedString.charCodeAt(i);
  9872. }
  9873. return bufferView.buffer;
  9874. };
  9875. Object.defineProperty(Tools, "NoneLogLevel", {
  9876. get: function () {
  9877. return Tools._NoneLogLevel;
  9878. },
  9879. enumerable: true,
  9880. configurable: true
  9881. });
  9882. Object.defineProperty(Tools, "MessageLogLevel", {
  9883. get: function () {
  9884. return Tools._MessageLogLevel;
  9885. },
  9886. enumerable: true,
  9887. configurable: true
  9888. });
  9889. Object.defineProperty(Tools, "WarningLogLevel", {
  9890. get: function () {
  9891. return Tools._WarningLogLevel;
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Object.defineProperty(Tools, "ErrorLogLevel", {
  9897. get: function () {
  9898. return Tools._ErrorLogLevel;
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. Object.defineProperty(Tools, "AllLogLevel", {
  9904. get: function () {
  9905. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. Tools._AddLogEntry = function (entry) {
  9911. Tools._LogCache = entry + Tools._LogCache;
  9912. if (Tools.OnNewCacheEntry) {
  9913. Tools.OnNewCacheEntry(entry);
  9914. }
  9915. };
  9916. Tools._FormatMessage = function (message) {
  9917. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9918. var date = new Date();
  9919. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9920. };
  9921. Tools._LogDisabled = function (message) {
  9922. // nothing to do
  9923. };
  9924. Tools._LogEnabled = function (message) {
  9925. var formattedMessage = Tools._FormatMessage(message);
  9926. console.log("BJS - " + formattedMessage);
  9927. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9928. Tools._AddLogEntry(entry);
  9929. };
  9930. Tools._WarnDisabled = function (message) {
  9931. // nothing to do
  9932. };
  9933. Tools._WarnEnabled = function (message) {
  9934. var formattedMessage = Tools._FormatMessage(message);
  9935. console.warn("BJS - " + formattedMessage);
  9936. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9937. Tools._AddLogEntry(entry);
  9938. };
  9939. Tools._ErrorDisabled = function (message) {
  9940. // nothing to do
  9941. };
  9942. Tools._ErrorEnabled = function (message) {
  9943. Tools.errorsCount++;
  9944. var formattedMessage = Tools._FormatMessage(message);
  9945. console.error("BJS - " + formattedMessage);
  9946. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9947. Tools._AddLogEntry(entry);
  9948. };
  9949. Object.defineProperty(Tools, "LogCache", {
  9950. get: function () {
  9951. return Tools._LogCache;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Tools.ClearLogCache = function () {
  9957. Tools._LogCache = "";
  9958. Tools.errorsCount = 0;
  9959. };
  9960. Object.defineProperty(Tools, "LogLevels", {
  9961. set: function (level) {
  9962. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9963. Tools.Log = Tools._LogEnabled;
  9964. }
  9965. else {
  9966. Tools.Log = Tools._LogDisabled;
  9967. }
  9968. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9969. Tools.Warn = Tools._WarnEnabled;
  9970. }
  9971. else {
  9972. Tools.Warn = Tools._WarnDisabled;
  9973. }
  9974. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9975. Tools.Error = Tools._ErrorEnabled;
  9976. }
  9977. else {
  9978. Tools.Error = Tools._ErrorDisabled;
  9979. }
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. /**
  9985. * Check if the loaded document was accessed via `file:`-Protocol.
  9986. * @returns boolean
  9987. */
  9988. Tools.IsFileURL = function () {
  9989. return location.protocol === "file:";
  9990. };
  9991. Tools.IsWindowObjectExist = function () {
  9992. return (typeof window) !== "undefined";
  9993. };
  9994. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9995. get: function () {
  9996. return Tools._PerformanceNoneLogLevel;
  9997. },
  9998. enumerable: true,
  9999. configurable: true
  10000. });
  10001. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  10002. get: function () {
  10003. return Tools._PerformanceUserMarkLogLevel;
  10004. },
  10005. enumerable: true,
  10006. configurable: true
  10007. });
  10008. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  10009. get: function () {
  10010. return Tools._PerformanceConsoleLogLevel;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10016. set: function (level) {
  10017. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10018. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10019. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10020. return;
  10021. }
  10022. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10023. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10024. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10025. return;
  10026. }
  10027. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10028. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10034. };
  10035. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10036. };
  10037. Tools._StartUserMark = function (counterName, condition) {
  10038. if (condition === void 0) { condition = true; }
  10039. if (!Tools._performance) {
  10040. if (!Tools.IsWindowObjectExist()) {
  10041. return;
  10042. }
  10043. Tools._performance = window.performance;
  10044. }
  10045. if (!condition || !Tools._performance.mark) {
  10046. return;
  10047. }
  10048. Tools._performance.mark(counterName + "-Begin");
  10049. };
  10050. Tools._EndUserMark = function (counterName, condition) {
  10051. if (condition === void 0) { condition = true; }
  10052. if (!condition || !Tools._performance.mark) {
  10053. return;
  10054. }
  10055. Tools._performance.mark(counterName + "-End");
  10056. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10057. };
  10058. Tools._StartPerformanceConsole = function (counterName, condition) {
  10059. if (condition === void 0) { condition = true; }
  10060. if (!condition) {
  10061. return;
  10062. }
  10063. Tools._StartUserMark(counterName, condition);
  10064. if (console.time) {
  10065. console.time(counterName);
  10066. }
  10067. };
  10068. Tools._EndPerformanceConsole = function (counterName, condition) {
  10069. if (condition === void 0) { condition = true; }
  10070. if (!condition) {
  10071. return;
  10072. }
  10073. Tools._EndUserMark(counterName, condition);
  10074. if (console.time) {
  10075. console.timeEnd(counterName);
  10076. }
  10077. };
  10078. Object.defineProperty(Tools, "Now", {
  10079. get: function () {
  10080. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10081. return window.performance.now();
  10082. }
  10083. return Date.now();
  10084. },
  10085. enumerable: true,
  10086. configurable: true
  10087. });
  10088. /**
  10089. * This method will return the name of the class used to create the instance of the given object.
  10090. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10091. * @param object the object to get the class name from
  10092. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10093. */
  10094. Tools.GetClassName = function (object, isType) {
  10095. if (isType === void 0) { isType = false; }
  10096. var name = null;
  10097. if (!isType && object.getClassName) {
  10098. name = object.getClassName();
  10099. }
  10100. else {
  10101. if (object instanceof Object) {
  10102. var classObj = isType ? object : Object.getPrototypeOf(object);
  10103. name = classObj.constructor["__bjsclassName__"];
  10104. }
  10105. if (!name) {
  10106. name = typeof object;
  10107. }
  10108. }
  10109. return name;
  10110. };
  10111. Tools.First = function (array, predicate) {
  10112. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10113. var el = array_1[_i];
  10114. if (predicate(el)) {
  10115. return el;
  10116. }
  10117. }
  10118. return null;
  10119. };
  10120. /**
  10121. * This method will return the name of the full name of the class, including its owning module (if any).
  10122. * 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).
  10123. * @param object the object to get the class name from
  10124. * @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.
  10125. */
  10126. Tools.getFullClassName = function (object, isType) {
  10127. if (isType === void 0) { isType = false; }
  10128. var className = null;
  10129. var moduleName = null;
  10130. if (!isType && object.getClassName) {
  10131. className = object.getClassName();
  10132. }
  10133. else {
  10134. if (object instanceof Object) {
  10135. var classObj = isType ? object : Object.getPrototypeOf(object);
  10136. className = classObj.constructor["__bjsclassName__"];
  10137. moduleName = classObj.constructor["__bjsmoduleName__"];
  10138. }
  10139. if (!className) {
  10140. className = typeof object;
  10141. }
  10142. }
  10143. if (!className) {
  10144. return null;
  10145. }
  10146. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10147. };
  10148. /**
  10149. * 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.
  10150. * @param array
  10151. */
  10152. Tools.arrayOrStringFeeder = function (array) {
  10153. return function (index) {
  10154. if (index >= array.length) {
  10155. return null;
  10156. }
  10157. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10158. if (val && val.getHashCode) {
  10159. val = val.getHashCode();
  10160. }
  10161. if (typeof val === "string") {
  10162. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10163. }
  10164. return val;
  10165. };
  10166. };
  10167. /**
  10168. * Compute the hashCode of a stream of number
  10169. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10170. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10171. * @return the hash code computed
  10172. */
  10173. Tools.hashCodeFromStream = function (feeder) {
  10174. // Based from here: http://stackoverflow.com/a/7616484/802124
  10175. var hash = 0;
  10176. var index = 0;
  10177. var chr = feeder(index++);
  10178. while (chr != null) {
  10179. hash = ((hash << 5) - hash) + chr;
  10180. hash |= 0; // Convert to 32bit integer
  10181. chr = feeder(index++);
  10182. }
  10183. return hash;
  10184. };
  10185. /**
  10186. * Returns a promise that resolves after the given amount of time.
  10187. * @param delay Number of milliseconds to delay
  10188. * @returns Promise that resolves after the given amount of time
  10189. */
  10190. Tools.DelayAsync = function (delay) {
  10191. return new Promise(function (resolve) {
  10192. setTimeout(function () {
  10193. resolve();
  10194. }, delay);
  10195. });
  10196. };
  10197. /**
  10198. * Gets the current gradient from an array of IValueGradient
  10199. * @param ratio defines the current ratio to get
  10200. * @param gradients defines the array of IValueGradient
  10201. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10202. */
  10203. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10204. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10205. var currentGradient = gradients[gradientIndex];
  10206. var nextGradient = gradients[gradientIndex + 1];
  10207. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10208. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10209. updateFunc(currentGradient, nextGradient, scale);
  10210. return;
  10211. }
  10212. }
  10213. // Use last index if over
  10214. var lastIndex = gradients.length - 1;
  10215. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10216. };
  10217. Tools.BaseUrl = "";
  10218. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10219. /**
  10220. * Default behaviour for cors in the application.
  10221. * It can be a string if the expected behavior is identical in the entire app.
  10222. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10223. */
  10224. Tools.CorsBehavior = "anonymous";
  10225. Tools.UseFallbackTexture = true;
  10226. /**
  10227. * Use this object to register external classes like custom textures or material
  10228. * to allow the laoders to instantiate them
  10229. */
  10230. Tools.RegisteredExternalClasses = {};
  10231. // Used in case of a texture loading problem
  10232. 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";
  10233. Tools._tmpFloatArray = new Float32Array(1);
  10234. Tools.PreprocessUrl = function (url) {
  10235. return url;
  10236. };
  10237. // Logs
  10238. Tools._NoneLogLevel = 0;
  10239. Tools._MessageLogLevel = 1;
  10240. Tools._WarningLogLevel = 2;
  10241. Tools._ErrorLogLevel = 4;
  10242. Tools._LogCache = "";
  10243. Tools.errorsCount = 0;
  10244. Tools.Log = Tools._LogEnabled;
  10245. Tools.Warn = Tools._WarnEnabled;
  10246. Tools.Error = Tools._ErrorEnabled;
  10247. // Performances
  10248. Tools._PerformanceNoneLogLevel = 0;
  10249. Tools._PerformanceUserMarkLogLevel = 1;
  10250. Tools._PerformanceConsoleLogLevel = 2;
  10251. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10252. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10253. return Tools;
  10254. }());
  10255. BABYLON.Tools = Tools;
  10256. /**
  10257. * This class is used to track a performance counter which is number based.
  10258. * The user has access to many properties which give statistics of different nature
  10259. *
  10260. * The implementer can track two kinds of Performance Counter: time and count
  10261. * 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.
  10262. * 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.
  10263. */
  10264. var PerfCounter = /** @class */ (function () {
  10265. function PerfCounter() {
  10266. this._startMonitoringTime = 0;
  10267. this._min = 0;
  10268. this._max = 0;
  10269. this._average = 0;
  10270. this._lastSecAverage = 0;
  10271. this._current = 0;
  10272. this._totalValueCount = 0;
  10273. this._totalAccumulated = 0;
  10274. this._lastSecAccumulated = 0;
  10275. this._lastSecTime = 0;
  10276. this._lastSecValueCount = 0;
  10277. }
  10278. Object.defineProperty(PerfCounter.prototype, "min", {
  10279. /**
  10280. * Returns the smallest value ever
  10281. */
  10282. get: function () {
  10283. return this._min;
  10284. },
  10285. enumerable: true,
  10286. configurable: true
  10287. });
  10288. Object.defineProperty(PerfCounter.prototype, "max", {
  10289. /**
  10290. * Returns the biggest value ever
  10291. */
  10292. get: function () {
  10293. return this._max;
  10294. },
  10295. enumerable: true,
  10296. configurable: true
  10297. });
  10298. Object.defineProperty(PerfCounter.prototype, "average", {
  10299. /**
  10300. * Returns the average value since the performance counter is running
  10301. */
  10302. get: function () {
  10303. return this._average;
  10304. },
  10305. enumerable: true,
  10306. configurable: true
  10307. });
  10308. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10309. /**
  10310. * Returns the average value of the last second the counter was monitored
  10311. */
  10312. get: function () {
  10313. return this._lastSecAverage;
  10314. },
  10315. enumerable: true,
  10316. configurable: true
  10317. });
  10318. Object.defineProperty(PerfCounter.prototype, "current", {
  10319. /**
  10320. * Returns the current value
  10321. */
  10322. get: function () {
  10323. return this._current;
  10324. },
  10325. enumerable: true,
  10326. configurable: true
  10327. });
  10328. Object.defineProperty(PerfCounter.prototype, "total", {
  10329. get: function () {
  10330. return this._totalAccumulated;
  10331. },
  10332. enumerable: true,
  10333. configurable: true
  10334. });
  10335. Object.defineProperty(PerfCounter.prototype, "count", {
  10336. get: function () {
  10337. return this._totalValueCount;
  10338. },
  10339. enumerable: true,
  10340. configurable: true
  10341. });
  10342. /**
  10343. * Call this method to start monitoring a new frame.
  10344. * 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.
  10345. */
  10346. PerfCounter.prototype.fetchNewFrame = function () {
  10347. this._totalValueCount++;
  10348. this._current = 0;
  10349. this._lastSecValueCount++;
  10350. };
  10351. /**
  10352. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10353. * @param newCount the count value to add to the monitored count
  10354. * @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.
  10355. */
  10356. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10357. if (!PerfCounter.Enabled) {
  10358. return;
  10359. }
  10360. this._current += newCount;
  10361. if (fetchResult) {
  10362. this._fetchResult();
  10363. }
  10364. };
  10365. /**
  10366. * Start monitoring this performance counter
  10367. */
  10368. PerfCounter.prototype.beginMonitoring = function () {
  10369. if (!PerfCounter.Enabled) {
  10370. return;
  10371. }
  10372. this._startMonitoringTime = Tools.Now;
  10373. };
  10374. /**
  10375. * Compute the time lapsed since the previous beginMonitoring() call.
  10376. * @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
  10377. */
  10378. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10379. if (newFrame === void 0) { newFrame = true; }
  10380. if (!PerfCounter.Enabled) {
  10381. return;
  10382. }
  10383. if (newFrame) {
  10384. this.fetchNewFrame();
  10385. }
  10386. var currentTime = Tools.Now;
  10387. this._current = currentTime - this._startMonitoringTime;
  10388. if (newFrame) {
  10389. this._fetchResult();
  10390. }
  10391. };
  10392. PerfCounter.prototype._fetchResult = function () {
  10393. this._totalAccumulated += this._current;
  10394. this._lastSecAccumulated += this._current;
  10395. // Min/Max update
  10396. this._min = Math.min(this._min, this._current);
  10397. this._max = Math.max(this._max, this._current);
  10398. this._average = this._totalAccumulated / this._totalValueCount;
  10399. // Reset last sec?
  10400. var now = Tools.Now;
  10401. if ((now - this._lastSecTime) > 1000) {
  10402. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10403. this._lastSecTime = now;
  10404. this._lastSecAccumulated = 0;
  10405. this._lastSecValueCount = 0;
  10406. }
  10407. };
  10408. PerfCounter.Enabled = true;
  10409. return PerfCounter;
  10410. }());
  10411. BABYLON.PerfCounter = PerfCounter;
  10412. /**
  10413. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10414. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10415. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10416. * @param name The name of the class, case should be preserved
  10417. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10418. */
  10419. function className(name, module) {
  10420. return function (target) {
  10421. target["__bjsclassName__"] = name;
  10422. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10423. };
  10424. }
  10425. BABYLON.className = className;
  10426. /**
  10427. * An implementation of a loop for asynchronous functions.
  10428. */
  10429. var AsyncLoop = /** @class */ (function () {
  10430. /**
  10431. * Constructor.
  10432. * @param iterations the number of iterations.
  10433. * @param func the function to run each iteration
  10434. * @param successCallback the callback that will be called upon succesful execution
  10435. * @param offset starting offset.
  10436. */
  10437. function AsyncLoop(
  10438. /**
  10439. * Defines the number of iterations for the loop
  10440. */
  10441. iterations, func, successCallback, offset) {
  10442. if (offset === void 0) { offset = 0; }
  10443. this.iterations = iterations;
  10444. this.index = offset - 1;
  10445. this._done = false;
  10446. this._fn = func;
  10447. this._successCallback = successCallback;
  10448. }
  10449. /**
  10450. * Execute the next iteration. Must be called after the last iteration was finished.
  10451. */
  10452. AsyncLoop.prototype.executeNext = function () {
  10453. if (!this._done) {
  10454. if (this.index + 1 < this.iterations) {
  10455. ++this.index;
  10456. this._fn(this);
  10457. }
  10458. else {
  10459. this.breakLoop();
  10460. }
  10461. }
  10462. };
  10463. /**
  10464. * Break the loop and run the success callback.
  10465. */
  10466. AsyncLoop.prototype.breakLoop = function () {
  10467. this._done = true;
  10468. this._successCallback();
  10469. };
  10470. /**
  10471. * Create and run an async loop.
  10472. * @param iterations the number of iterations.
  10473. * @param _fn the function to run each iteration
  10474. * @param _successCallback the callback that will be called upon succesful execution
  10475. * @param offset starting offset.
  10476. * @returns the created async loop object
  10477. */
  10478. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10479. if (offset === void 0) { offset = 0; }
  10480. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10481. loop.executeNext();
  10482. return loop;
  10483. };
  10484. /**
  10485. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10486. * @param iterations total number of iterations
  10487. * @param syncedIterations number of synchronous iterations in each async iteration.
  10488. * @param fn the function to call each iteration.
  10489. * @param callback a success call back that will be called when iterating stops.
  10490. * @param breakFunction a break condition (optional)
  10491. * @param timeout timeout settings for the setTimeout function. default - 0.
  10492. * @returns the created async loop object
  10493. */
  10494. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10495. if (timeout === void 0) { timeout = 0; }
  10496. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10497. if (breakFunction && breakFunction())
  10498. loop.breakLoop();
  10499. else {
  10500. setTimeout(function () {
  10501. for (var i = 0; i < syncedIterations; ++i) {
  10502. var iteration = (loop.index * syncedIterations) + i;
  10503. if (iteration >= iterations)
  10504. break;
  10505. fn(iteration);
  10506. if (breakFunction && breakFunction()) {
  10507. loop.breakLoop();
  10508. break;
  10509. }
  10510. }
  10511. loop.executeNext();
  10512. }, timeout);
  10513. }
  10514. }, callback);
  10515. };
  10516. return AsyncLoop;
  10517. }());
  10518. BABYLON.AsyncLoop = AsyncLoop;
  10519. })(BABYLON || (BABYLON = {}));
  10520. //# sourceMappingURL=babylon.tools.js.map
  10521. var BABYLON;
  10522. (function (BABYLON) {
  10523. var PromiseStates;
  10524. (function (PromiseStates) {
  10525. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10526. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10527. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10528. })(PromiseStates || (PromiseStates = {}));
  10529. var FulFillmentAgregator = /** @class */ (function () {
  10530. function FulFillmentAgregator() {
  10531. this.count = 0;
  10532. this.target = 0;
  10533. this.results = [];
  10534. }
  10535. return FulFillmentAgregator;
  10536. }());
  10537. var InternalPromise = /** @class */ (function () {
  10538. function InternalPromise(resolver) {
  10539. var _this = this;
  10540. this._state = PromiseStates.Pending;
  10541. this._children = new Array();
  10542. this._rejectWasConsumed = false;
  10543. if (!resolver) {
  10544. return;
  10545. }
  10546. try {
  10547. resolver(function (value) {
  10548. _this._resolve(value);
  10549. }, function (reason) {
  10550. _this._reject(reason);
  10551. });
  10552. }
  10553. catch (e) {
  10554. this._reject(e);
  10555. }
  10556. }
  10557. Object.defineProperty(InternalPromise.prototype, "_result", {
  10558. get: function () {
  10559. return this._resultValue;
  10560. },
  10561. set: function (value) {
  10562. this._resultValue = value;
  10563. if (this._parent && this._parent._result === undefined) {
  10564. this._parent._result = value;
  10565. }
  10566. },
  10567. enumerable: true,
  10568. configurable: true
  10569. });
  10570. InternalPromise.prototype.catch = function (onRejected) {
  10571. return this.then(undefined, onRejected);
  10572. };
  10573. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10574. var _this = this;
  10575. var newPromise = new InternalPromise();
  10576. newPromise._onFulfilled = onFulfilled;
  10577. newPromise._onRejected = onRejected;
  10578. // Composition
  10579. this._children.push(newPromise);
  10580. newPromise._parent = this;
  10581. if (this._state !== PromiseStates.Pending) {
  10582. BABYLON.Tools.SetImmediate(function () {
  10583. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10584. var returnedValue = newPromise._resolve(_this._result);
  10585. if (returnedValue !== undefined && returnedValue !== null) {
  10586. if (returnedValue._state !== undefined) {
  10587. var returnedPromise = returnedValue;
  10588. newPromise._children.push(returnedPromise);
  10589. returnedPromise._parent = newPromise;
  10590. newPromise = returnedPromise;
  10591. }
  10592. else {
  10593. newPromise._result = returnedValue;
  10594. }
  10595. }
  10596. }
  10597. else {
  10598. newPromise._reject(_this._reason);
  10599. }
  10600. });
  10601. }
  10602. return newPromise;
  10603. };
  10604. InternalPromise.prototype._moveChildren = function (children) {
  10605. var _this = this;
  10606. var _a;
  10607. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10608. this._children.forEach(function (child) {
  10609. child._parent = _this;
  10610. });
  10611. if (this._state === PromiseStates.Fulfilled) {
  10612. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10613. var child = _b[_i];
  10614. child._resolve(this._result);
  10615. }
  10616. }
  10617. else if (this._state === PromiseStates.Rejected) {
  10618. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10619. var child = _d[_c];
  10620. child._reject(this._reason);
  10621. }
  10622. }
  10623. };
  10624. InternalPromise.prototype._resolve = function (value) {
  10625. try {
  10626. this._state = PromiseStates.Fulfilled;
  10627. var returnedValue = null;
  10628. if (this._onFulfilled) {
  10629. returnedValue = this._onFulfilled(value);
  10630. }
  10631. if (returnedValue !== undefined && returnedValue !== null) {
  10632. if (returnedValue._state !== undefined) {
  10633. // Transmit children
  10634. var returnedPromise = returnedValue;
  10635. returnedPromise._parent = this;
  10636. returnedPromise._moveChildren(this._children);
  10637. value = returnedPromise._result;
  10638. }
  10639. else {
  10640. value = returnedValue;
  10641. }
  10642. }
  10643. this._result = value;
  10644. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10645. var child = _a[_i];
  10646. child._resolve(value);
  10647. }
  10648. this._children.length = 0;
  10649. delete this._onFulfilled;
  10650. delete this._onRejected;
  10651. }
  10652. catch (e) {
  10653. this._reject(e, true);
  10654. }
  10655. };
  10656. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10657. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10658. this._state = PromiseStates.Rejected;
  10659. this._reason = reason;
  10660. if (this._onRejected && !onLocalThrow) {
  10661. try {
  10662. this._onRejected(reason);
  10663. this._rejectWasConsumed = true;
  10664. }
  10665. catch (e) {
  10666. reason = e;
  10667. }
  10668. }
  10669. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10670. var child = _a[_i];
  10671. if (this._rejectWasConsumed) {
  10672. child._resolve(null);
  10673. }
  10674. else {
  10675. child._reject(reason);
  10676. }
  10677. }
  10678. this._children.length = 0;
  10679. delete this._onFulfilled;
  10680. delete this._onRejected;
  10681. };
  10682. InternalPromise.resolve = function (value) {
  10683. var newPromise = new InternalPromise();
  10684. newPromise._resolve(value);
  10685. return newPromise;
  10686. };
  10687. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10688. promise.then(function (value) {
  10689. agregator.results[index] = value;
  10690. agregator.count++;
  10691. if (agregator.count === agregator.target) {
  10692. agregator.rootPromise._resolve(agregator.results);
  10693. }
  10694. return null;
  10695. }, function (reason) {
  10696. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10697. agregator.rootPromise._reject(reason);
  10698. }
  10699. });
  10700. };
  10701. InternalPromise.all = function (promises) {
  10702. var newPromise = new InternalPromise();
  10703. var agregator = new FulFillmentAgregator();
  10704. agregator.target = promises.length;
  10705. agregator.rootPromise = newPromise;
  10706. if (promises.length) {
  10707. for (var index = 0; index < promises.length; index++) {
  10708. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10709. }
  10710. }
  10711. else {
  10712. newPromise._resolve([]);
  10713. }
  10714. return newPromise;
  10715. };
  10716. InternalPromise.race = function (promises) {
  10717. var newPromise = new InternalPromise();
  10718. if (promises.length) {
  10719. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10720. var promise = promises_1[_i];
  10721. promise.then(function (value) {
  10722. if (newPromise) {
  10723. newPromise._resolve(value);
  10724. newPromise = null;
  10725. }
  10726. return null;
  10727. }, function (reason) {
  10728. if (newPromise) {
  10729. newPromise._reject(reason);
  10730. newPromise = null;
  10731. }
  10732. });
  10733. }
  10734. }
  10735. return newPromise;
  10736. };
  10737. return InternalPromise;
  10738. }());
  10739. /**
  10740. * Helper class that provides a small promise polyfill
  10741. */
  10742. var PromisePolyfill = /** @class */ (function () {
  10743. function PromisePolyfill() {
  10744. }
  10745. /**
  10746. * Static function used to check if the polyfill is required
  10747. * If this is the case then the function will inject the polyfill to window.Promise
  10748. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10749. */
  10750. PromisePolyfill.Apply = function (force) {
  10751. if (force === void 0) { force = false; }
  10752. if (force || typeof Promise === 'undefined') {
  10753. var root = window;
  10754. root.Promise = InternalPromise;
  10755. }
  10756. };
  10757. return PromisePolyfill;
  10758. }());
  10759. BABYLON.PromisePolyfill = PromisePolyfill;
  10760. })(BABYLON || (BABYLON = {}));
  10761. //# sourceMappingURL=babylon.promise.js.map
  10762. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10763. var BABYLON;
  10764. (function (BABYLON) {
  10765. /**
  10766. * Helper class to push actions to a pool of workers.
  10767. */
  10768. var WorkerPool = /** @class */ (function () {
  10769. /**
  10770. * Constructor
  10771. * @param workers Array of workers to use for actions
  10772. */
  10773. function WorkerPool(workers) {
  10774. this._pendingActions = new Array();
  10775. this._workerInfos = workers.map(function (worker) { return ({
  10776. worker: worker,
  10777. active: false
  10778. }); });
  10779. }
  10780. /**
  10781. * Terminates all workers and clears any pending actions.
  10782. */
  10783. WorkerPool.prototype.dispose = function () {
  10784. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10785. var workerInfo = _a[_i];
  10786. workerInfo.worker.terminate();
  10787. }
  10788. delete this._workerInfos;
  10789. delete this._pendingActions;
  10790. };
  10791. /**
  10792. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10793. * pended until a worker has completed its action.
  10794. * @param action The action to perform. Call onComplete when the action is complete.
  10795. */
  10796. WorkerPool.prototype.push = function (action) {
  10797. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10798. var workerInfo = _a[_i];
  10799. if (!workerInfo.active) {
  10800. this._execute(workerInfo, action);
  10801. return;
  10802. }
  10803. }
  10804. this._pendingActions.push(action);
  10805. };
  10806. WorkerPool.prototype._execute = function (workerInfo, action) {
  10807. var _this = this;
  10808. workerInfo.active = true;
  10809. action(workerInfo.worker, function () {
  10810. workerInfo.active = false;
  10811. var nextAction = _this._pendingActions.shift();
  10812. if (nextAction) {
  10813. _this._execute(workerInfo, nextAction);
  10814. }
  10815. });
  10816. };
  10817. return WorkerPool;
  10818. }());
  10819. BABYLON.WorkerPool = WorkerPool;
  10820. })(BABYLON || (BABYLON = {}));
  10821. //# sourceMappingURL=babylon.workerPool.js.map
  10822. var BABYLON;
  10823. (function (BABYLON) {
  10824. /**
  10825. * @hidden
  10826. **/
  10827. var _AlphaState = /** @class */ (function () {
  10828. /**
  10829. * Initializes the state.
  10830. */
  10831. function _AlphaState() {
  10832. this._isAlphaBlendDirty = false;
  10833. this._isBlendFunctionParametersDirty = false;
  10834. this._isBlendEquationParametersDirty = false;
  10835. this._isBlendConstantsDirty = false;
  10836. this._alphaBlend = false;
  10837. this._blendFunctionParameters = new Array(4);
  10838. this._blendEquationParameters = new Array(2);
  10839. this._blendConstants = new Array(4);
  10840. this.reset();
  10841. }
  10842. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10843. get: function () {
  10844. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10850. get: function () {
  10851. return this._alphaBlend;
  10852. },
  10853. set: function (value) {
  10854. if (this._alphaBlend === value) {
  10855. return;
  10856. }
  10857. this._alphaBlend = value;
  10858. this._isAlphaBlendDirty = true;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10864. if (this._blendConstants[0] === r &&
  10865. this._blendConstants[1] === g &&
  10866. this._blendConstants[2] === b &&
  10867. this._blendConstants[3] === a) {
  10868. return;
  10869. }
  10870. this._blendConstants[0] = r;
  10871. this._blendConstants[1] = g;
  10872. this._blendConstants[2] = b;
  10873. this._blendConstants[3] = a;
  10874. this._isBlendConstantsDirty = true;
  10875. };
  10876. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10877. if (this._blendFunctionParameters[0] === value0 &&
  10878. this._blendFunctionParameters[1] === value1 &&
  10879. this._blendFunctionParameters[2] === value2 &&
  10880. this._blendFunctionParameters[3] === value3) {
  10881. return;
  10882. }
  10883. this._blendFunctionParameters[0] = value0;
  10884. this._blendFunctionParameters[1] = value1;
  10885. this._blendFunctionParameters[2] = value2;
  10886. this._blendFunctionParameters[3] = value3;
  10887. this._isBlendFunctionParametersDirty = true;
  10888. };
  10889. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10890. if (this._blendEquationParameters[0] === rgb &&
  10891. this._blendEquationParameters[1] === alpha) {
  10892. return;
  10893. }
  10894. this._blendEquationParameters[0] = rgb;
  10895. this._blendEquationParameters[1] = alpha;
  10896. this._isBlendEquationParametersDirty = true;
  10897. };
  10898. _AlphaState.prototype.reset = function () {
  10899. this._alphaBlend = false;
  10900. this._blendFunctionParameters[0] = null;
  10901. this._blendFunctionParameters[1] = null;
  10902. this._blendFunctionParameters[2] = null;
  10903. this._blendFunctionParameters[3] = null;
  10904. this._blendEquationParameters[0] = null;
  10905. this._blendEquationParameters[1] = null;
  10906. this._blendConstants[0] = null;
  10907. this._blendConstants[1] = null;
  10908. this._blendConstants[2] = null;
  10909. this._blendConstants[3] = null;
  10910. this._isAlphaBlendDirty = true;
  10911. this._isBlendFunctionParametersDirty = false;
  10912. this._isBlendEquationParametersDirty = false;
  10913. this._isBlendConstantsDirty = false;
  10914. };
  10915. _AlphaState.prototype.apply = function (gl) {
  10916. if (!this.isDirty) {
  10917. return;
  10918. }
  10919. // Alpha blend
  10920. if (this._isAlphaBlendDirty) {
  10921. if (this._alphaBlend) {
  10922. gl.enable(gl.BLEND);
  10923. }
  10924. else {
  10925. gl.disable(gl.BLEND);
  10926. }
  10927. this._isAlphaBlendDirty = false;
  10928. }
  10929. // Alpha function
  10930. if (this._isBlendFunctionParametersDirty) {
  10931. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10932. this._isBlendFunctionParametersDirty = false;
  10933. }
  10934. // Alpha equation
  10935. if (this._isBlendEquationParametersDirty) {
  10936. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10937. this._isBlendEquationParametersDirty = false;
  10938. }
  10939. // Constants
  10940. if (this._isBlendConstantsDirty) {
  10941. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10942. this._isBlendConstantsDirty = false;
  10943. }
  10944. };
  10945. return _AlphaState;
  10946. }());
  10947. BABYLON._AlphaState = _AlphaState;
  10948. })(BABYLON || (BABYLON = {}));
  10949. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10950. var BABYLON;
  10951. (function (BABYLON) {
  10952. /**
  10953. * @hidden
  10954. **/
  10955. var _DepthCullingState = /** @class */ (function () {
  10956. /**
  10957. * Initializes the state.
  10958. */
  10959. function _DepthCullingState() {
  10960. this._isDepthTestDirty = false;
  10961. this._isDepthMaskDirty = false;
  10962. this._isDepthFuncDirty = false;
  10963. this._isCullFaceDirty = false;
  10964. this._isCullDirty = false;
  10965. this._isZOffsetDirty = false;
  10966. this._isFrontFaceDirty = false;
  10967. this.reset();
  10968. }
  10969. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10970. get: function () {
  10971. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10977. get: function () {
  10978. return this._zOffset;
  10979. },
  10980. set: function (value) {
  10981. if (this._zOffset === value) {
  10982. return;
  10983. }
  10984. this._zOffset = value;
  10985. this._isZOffsetDirty = true;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10991. get: function () {
  10992. return this._cullFace;
  10993. },
  10994. set: function (value) {
  10995. if (this._cullFace === value) {
  10996. return;
  10997. }
  10998. this._cullFace = value;
  10999. this._isCullFaceDirty = true;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11005. get: function () {
  11006. return this._cull;
  11007. },
  11008. set: function (value) {
  11009. if (this._cull === value) {
  11010. return;
  11011. }
  11012. this._cull = value;
  11013. this._isCullDirty = true;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11019. get: function () {
  11020. return this._depthFunc;
  11021. },
  11022. set: function (value) {
  11023. if (this._depthFunc === value) {
  11024. return;
  11025. }
  11026. this._depthFunc = value;
  11027. this._isDepthFuncDirty = true;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11033. get: function () {
  11034. return this._depthMask;
  11035. },
  11036. set: function (value) {
  11037. if (this._depthMask === value) {
  11038. return;
  11039. }
  11040. this._depthMask = value;
  11041. this._isDepthMaskDirty = true;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11047. get: function () {
  11048. return this._depthTest;
  11049. },
  11050. set: function (value) {
  11051. if (this._depthTest === value) {
  11052. return;
  11053. }
  11054. this._depthTest = value;
  11055. this._isDepthTestDirty = true;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11061. get: function () {
  11062. return this._frontFace;
  11063. },
  11064. set: function (value) {
  11065. if (this._frontFace === value) {
  11066. return;
  11067. }
  11068. this._frontFace = value;
  11069. this._isFrontFaceDirty = true;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. _DepthCullingState.prototype.reset = function () {
  11075. this._depthMask = true;
  11076. this._depthTest = true;
  11077. this._depthFunc = null;
  11078. this._cullFace = null;
  11079. this._cull = null;
  11080. this._zOffset = 0;
  11081. this._frontFace = null;
  11082. this._isDepthTestDirty = true;
  11083. this._isDepthMaskDirty = true;
  11084. this._isDepthFuncDirty = false;
  11085. this._isCullFaceDirty = false;
  11086. this._isCullDirty = false;
  11087. this._isZOffsetDirty = false;
  11088. this._isFrontFaceDirty = false;
  11089. };
  11090. _DepthCullingState.prototype.apply = function (gl) {
  11091. if (!this.isDirty) {
  11092. return;
  11093. }
  11094. // Cull
  11095. if (this._isCullDirty) {
  11096. if (this.cull) {
  11097. gl.enable(gl.CULL_FACE);
  11098. }
  11099. else {
  11100. gl.disable(gl.CULL_FACE);
  11101. }
  11102. this._isCullDirty = false;
  11103. }
  11104. // Cull face
  11105. if (this._isCullFaceDirty) {
  11106. gl.cullFace(this.cullFace);
  11107. this._isCullFaceDirty = false;
  11108. }
  11109. // Depth mask
  11110. if (this._isDepthMaskDirty) {
  11111. gl.depthMask(this.depthMask);
  11112. this._isDepthMaskDirty = false;
  11113. }
  11114. // Depth test
  11115. if (this._isDepthTestDirty) {
  11116. if (this.depthTest) {
  11117. gl.enable(gl.DEPTH_TEST);
  11118. }
  11119. else {
  11120. gl.disable(gl.DEPTH_TEST);
  11121. }
  11122. this._isDepthTestDirty = false;
  11123. }
  11124. // Depth func
  11125. if (this._isDepthFuncDirty) {
  11126. gl.depthFunc(this.depthFunc);
  11127. this._isDepthFuncDirty = false;
  11128. }
  11129. // zOffset
  11130. if (this._isZOffsetDirty) {
  11131. if (this.zOffset) {
  11132. gl.enable(gl.POLYGON_OFFSET_FILL);
  11133. gl.polygonOffset(this.zOffset, 0);
  11134. }
  11135. else {
  11136. gl.disable(gl.POLYGON_OFFSET_FILL);
  11137. }
  11138. this._isZOffsetDirty = false;
  11139. }
  11140. // Front face
  11141. if (this._isFrontFaceDirty) {
  11142. gl.frontFace(this.frontFace);
  11143. this._isFrontFaceDirty = false;
  11144. }
  11145. };
  11146. return _DepthCullingState;
  11147. }());
  11148. BABYLON._DepthCullingState = _DepthCullingState;
  11149. })(BABYLON || (BABYLON = {}));
  11150. //# sourceMappingURL=babylon.depthCullingState.js.map
  11151. var BABYLON;
  11152. (function (BABYLON) {
  11153. /**
  11154. * @hidden
  11155. **/
  11156. var _StencilState = /** @class */ (function () {
  11157. function _StencilState() {
  11158. this._isStencilTestDirty = false;
  11159. this._isStencilMaskDirty = false;
  11160. this._isStencilFuncDirty = false;
  11161. this._isStencilOpDirty = false;
  11162. this.reset();
  11163. }
  11164. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11165. get: function () {
  11166. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11172. get: function () {
  11173. return this._stencilFunc;
  11174. },
  11175. set: function (value) {
  11176. if (this._stencilFunc === value) {
  11177. return;
  11178. }
  11179. this._stencilFunc = value;
  11180. this._isStencilFuncDirty = true;
  11181. },
  11182. enumerable: true,
  11183. configurable: true
  11184. });
  11185. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11186. get: function () {
  11187. return this._stencilFuncRef;
  11188. },
  11189. set: function (value) {
  11190. if (this._stencilFuncRef === value) {
  11191. return;
  11192. }
  11193. this._stencilFuncRef = value;
  11194. this._isStencilFuncDirty = true;
  11195. },
  11196. enumerable: true,
  11197. configurable: true
  11198. });
  11199. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11200. get: function () {
  11201. return this._stencilFuncMask;
  11202. },
  11203. set: function (value) {
  11204. if (this._stencilFuncMask === value) {
  11205. return;
  11206. }
  11207. this._stencilFuncMask = value;
  11208. this._isStencilFuncDirty = true;
  11209. },
  11210. enumerable: true,
  11211. configurable: true
  11212. });
  11213. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11214. get: function () {
  11215. return this._stencilOpStencilFail;
  11216. },
  11217. set: function (value) {
  11218. if (this._stencilOpStencilFail === value) {
  11219. return;
  11220. }
  11221. this._stencilOpStencilFail = value;
  11222. this._isStencilOpDirty = true;
  11223. },
  11224. enumerable: true,
  11225. configurable: true
  11226. });
  11227. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11228. get: function () {
  11229. return this._stencilOpDepthFail;
  11230. },
  11231. set: function (value) {
  11232. if (this._stencilOpDepthFail === value) {
  11233. return;
  11234. }
  11235. this._stencilOpDepthFail = value;
  11236. this._isStencilOpDirty = true;
  11237. },
  11238. enumerable: true,
  11239. configurable: true
  11240. });
  11241. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11242. get: function () {
  11243. return this._stencilOpStencilDepthPass;
  11244. },
  11245. set: function (value) {
  11246. if (this._stencilOpStencilDepthPass === value) {
  11247. return;
  11248. }
  11249. this._stencilOpStencilDepthPass = value;
  11250. this._isStencilOpDirty = true;
  11251. },
  11252. enumerable: true,
  11253. configurable: true
  11254. });
  11255. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11256. get: function () {
  11257. return this._stencilMask;
  11258. },
  11259. set: function (value) {
  11260. if (this._stencilMask === value) {
  11261. return;
  11262. }
  11263. this._stencilMask = value;
  11264. this._isStencilMaskDirty = true;
  11265. },
  11266. enumerable: true,
  11267. configurable: true
  11268. });
  11269. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11270. get: function () {
  11271. return this._stencilTest;
  11272. },
  11273. set: function (value) {
  11274. if (this._stencilTest === value) {
  11275. return;
  11276. }
  11277. this._stencilTest = value;
  11278. this._isStencilTestDirty = true;
  11279. },
  11280. enumerable: true,
  11281. configurable: true
  11282. });
  11283. _StencilState.prototype.reset = function () {
  11284. this._stencilTest = false;
  11285. this._stencilMask = 0xFF;
  11286. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11287. this._stencilFuncRef = 1;
  11288. this._stencilFuncMask = 0xFF;
  11289. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11290. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11291. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11292. this._isStencilTestDirty = true;
  11293. this._isStencilMaskDirty = true;
  11294. this._isStencilFuncDirty = true;
  11295. this._isStencilOpDirty = true;
  11296. };
  11297. _StencilState.prototype.apply = function (gl) {
  11298. if (!this.isDirty) {
  11299. return;
  11300. }
  11301. // Stencil test
  11302. if (this._isStencilTestDirty) {
  11303. if (this.stencilTest) {
  11304. gl.enable(gl.STENCIL_TEST);
  11305. }
  11306. else {
  11307. gl.disable(gl.STENCIL_TEST);
  11308. }
  11309. this._isStencilTestDirty = false;
  11310. }
  11311. // Stencil mask
  11312. if (this._isStencilMaskDirty) {
  11313. gl.stencilMask(this.stencilMask);
  11314. this._isStencilMaskDirty = false;
  11315. }
  11316. // Stencil func
  11317. if (this._isStencilFuncDirty) {
  11318. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11319. this._isStencilFuncDirty = false;
  11320. }
  11321. // Stencil op
  11322. if (this._isStencilOpDirty) {
  11323. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11324. this._isStencilOpDirty = false;
  11325. }
  11326. };
  11327. return _StencilState;
  11328. }());
  11329. BABYLON._StencilState = _StencilState;
  11330. })(BABYLON || (BABYLON = {}));
  11331. //# sourceMappingURL=babylon.stencilState.js.map
  11332. var __assign = (this && this.__assign) || function () {
  11333. __assign = Object.assign || function(t) {
  11334. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11335. s = arguments[i];
  11336. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11337. t[p] = s[p];
  11338. }
  11339. return t;
  11340. };
  11341. return __assign.apply(this, arguments);
  11342. };
  11343. var BABYLON;
  11344. (function (BABYLON) {
  11345. /**
  11346. * Keeps track of all the buffer info used in engine.
  11347. */
  11348. var BufferPointer = /** @class */ (function () {
  11349. function BufferPointer() {
  11350. }
  11351. return BufferPointer;
  11352. }());
  11353. /**
  11354. * Interface for attribute information associated with buffer instanciation
  11355. */
  11356. var InstancingAttributeInfo = /** @class */ (function () {
  11357. function InstancingAttributeInfo() {
  11358. }
  11359. return InstancingAttributeInfo;
  11360. }());
  11361. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11362. /**
  11363. * Define options used to create a render target texture
  11364. */
  11365. var RenderTargetCreationOptions = /** @class */ (function () {
  11366. function RenderTargetCreationOptions() {
  11367. }
  11368. return RenderTargetCreationOptions;
  11369. }());
  11370. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11371. /**
  11372. * Define options used to create a depth texture
  11373. */
  11374. var DepthTextureCreationOptions = /** @class */ (function () {
  11375. function DepthTextureCreationOptions() {
  11376. }
  11377. return DepthTextureCreationOptions;
  11378. }());
  11379. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11380. /**
  11381. * Class used to describe the capabilities of the engine relatively to the current browser
  11382. */
  11383. var EngineCapabilities = /** @class */ (function () {
  11384. function EngineCapabilities() {
  11385. }
  11386. return EngineCapabilities;
  11387. }());
  11388. BABYLON.EngineCapabilities = EngineCapabilities;
  11389. /**
  11390. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11391. */
  11392. var Engine = /** @class */ (function () {
  11393. /**
  11394. * Creates a new engine
  11395. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11396. * @param antialias defines enable antialiasing (default: false)
  11397. * @param options defines further options to be sent to the getContext() function
  11398. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11399. */
  11400. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11401. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11402. var _this = this;
  11403. // Public members
  11404. /**
  11405. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11406. */
  11407. this.forcePOTTextures = false;
  11408. /**
  11409. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11410. */
  11411. this.isFullscreen = false;
  11412. /**
  11413. * Gets a boolean indicating if the pointer is currently locked
  11414. */
  11415. this.isPointerLock = false;
  11416. /**
  11417. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11418. */
  11419. this.cullBackFaces = true;
  11420. /**
  11421. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11422. */
  11423. this.renderEvenInBackground = true;
  11424. /**
  11425. * Gets or sets a boolean indicating that cache can be kept between frames
  11426. */
  11427. this.preventCacheWipeBetweenFrames = false;
  11428. /**
  11429. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11430. **/
  11431. this.enableOfflineSupport = false;
  11432. /**
  11433. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11434. **/
  11435. this.disableManifestCheck = false;
  11436. /**
  11437. * Gets the list of created scenes
  11438. */
  11439. this.scenes = new Array();
  11440. /**
  11441. * Gets the list of created postprocesses
  11442. */
  11443. this.postProcesses = new Array();
  11444. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11445. this.validateShaderPrograms = false;
  11446. // Observables
  11447. /**
  11448. * Observable event triggered each time the rendering canvas is resized
  11449. */
  11450. this.onResizeObservable = new BABYLON.Observable();
  11451. /**
  11452. * Observable event triggered each time the canvas loses focus
  11453. */
  11454. this.onCanvasBlurObservable = new BABYLON.Observable();
  11455. /**
  11456. * Observable event triggered each time the canvas gains focus
  11457. */
  11458. this.onCanvasFocusObservable = new BABYLON.Observable();
  11459. /**
  11460. * Observable event triggered each time the canvas receives pointerout event
  11461. */
  11462. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11463. /**
  11464. * Observable event triggered before each texture is initialized
  11465. */
  11466. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11467. //WebVR
  11468. this._vrDisplay = undefined;
  11469. this._vrSupported = false;
  11470. this._vrExclusivePointerMode = false;
  11471. // Uniform buffers list
  11472. /**
  11473. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11474. */
  11475. this.disableUniformBuffers = false;
  11476. /** @hidden */
  11477. this._uniformBuffers = new Array();
  11478. // Observables
  11479. /**
  11480. * Observable raised when the engine begins a new frame
  11481. */
  11482. this.onBeginFrameObservable = new BABYLON.Observable();
  11483. /**
  11484. * Observable raised when the engine ends the current frame
  11485. */
  11486. this.onEndFrameObservable = new BABYLON.Observable();
  11487. /**
  11488. * Observable raised when the engine is about to compile a shader
  11489. */
  11490. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11491. /**
  11492. * Observable raised when the engine has jsut compiled a shader
  11493. */
  11494. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11495. this._windowIsBackground = false;
  11496. this._webGLVersion = 1.0;
  11497. /** @hidden */
  11498. this._badOS = false;
  11499. /** @hidden */
  11500. this._badDesktopOS = false;
  11501. /**
  11502. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11503. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11504. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11505. */
  11506. this.disableTextureBindingOptimization = false;
  11507. /**
  11508. * Observable signaled when VR display mode changes
  11509. */
  11510. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11511. /**
  11512. * Observable signaled when VR request present is complete
  11513. */
  11514. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11515. /**
  11516. * Observable signaled when VR request present starts
  11517. */
  11518. this.onVRRequestPresentStart = new BABYLON.Observable();
  11519. this._colorWrite = true;
  11520. /** @hidden */
  11521. this._drawCalls = new BABYLON.PerfCounter();
  11522. /** @hidden */
  11523. this._textureCollisions = new BABYLON.PerfCounter();
  11524. this._renderingQueueLaunched = false;
  11525. this._activeRenderLoops = new Array();
  11526. // Deterministic lockstepMaxSteps
  11527. this._deterministicLockstep = false;
  11528. this._lockstepMaxSteps = 4;
  11529. // Lost context
  11530. /**
  11531. * Observable signaled when a context lost event is raised
  11532. */
  11533. this.onContextLostObservable = new BABYLON.Observable();
  11534. /**
  11535. * Observable signaled when a context restored event is raised
  11536. */
  11537. this.onContextRestoredObservable = new BABYLON.Observable();
  11538. this._contextWasLost = false;
  11539. this._doNotHandleContextLost = false;
  11540. // FPS
  11541. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11542. this._fps = 60;
  11543. this._deltaTime = 0;
  11544. /**
  11545. * Turn this value on if you want to pause FPS computation when in background
  11546. */
  11547. this.disablePerformanceMonitorInBackground = false;
  11548. // States
  11549. /** @hidden */
  11550. this._depthCullingState = new BABYLON._DepthCullingState();
  11551. /** @hidden */
  11552. this._stencilState = new BABYLON._StencilState();
  11553. /** @hidden */
  11554. this._alphaState = new BABYLON._AlphaState();
  11555. /** @hidden */
  11556. this._alphaMode = Engine.ALPHA_DISABLE;
  11557. // Cache
  11558. this._internalTexturesCache = new Array();
  11559. /** @hidden */
  11560. this._activeChannel = 0;
  11561. this._currentTextureChannel = -1;
  11562. /** @hidden */
  11563. this._boundTexturesCache = {};
  11564. this._compiledEffects = {};
  11565. this._vertexAttribArraysEnabled = [];
  11566. this._uintIndicesCurrentlySet = false;
  11567. this._currentBoundBuffer = new Array();
  11568. /** @hidden */
  11569. this._currentFramebuffer = null;
  11570. this._currentBufferPointers = new Array();
  11571. this._currentInstanceLocations = new Array();
  11572. this._currentInstanceBuffers = new Array();
  11573. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11574. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11575. this._vaoRecordInProgress = false;
  11576. this._mustWipeVertexAttributes = false;
  11577. this._nextFreeTextureSlots = new Array();
  11578. this._maxSimultaneousTextures = 0;
  11579. this._activeRequests = new Array();
  11580. // Hardware supported Compressed Textures
  11581. this._texturesSupported = new Array();
  11582. /**
  11583. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11584. */
  11585. this.premultipliedAlpha = true;
  11586. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11587. this._onVRFullScreenTriggered = function () {
  11588. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11589. //get the old size before we change
  11590. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11591. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11592. //get the width and height, change the render size
  11593. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11594. _this.setHardwareScalingLevel(1);
  11595. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11596. }
  11597. else {
  11598. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11599. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11600. }
  11601. };
  11602. this._unpackFlipYCached = null;
  11603. /**
  11604. * In case you are sharing the context with other applications, it might
  11605. * be interested to not cache the unpack flip y state to ensure a consistent
  11606. * value would be set.
  11607. */
  11608. this.enableUnpackFlipYCached = true;
  11609. this._boundUniforms = {};
  11610. // Register promises
  11611. BABYLON.PromisePolyfill.Apply();
  11612. var canvas = null;
  11613. Engine.Instances.push(this);
  11614. if (!canvasOrContext) {
  11615. return;
  11616. }
  11617. options = options || {};
  11618. if (canvasOrContext.getContext) {
  11619. canvas = canvasOrContext;
  11620. this._renderingCanvas = canvas;
  11621. if (antialias != null) {
  11622. options.antialias = antialias;
  11623. }
  11624. if (options.deterministicLockstep === undefined) {
  11625. options.deterministicLockstep = false;
  11626. }
  11627. if (options.lockstepMaxSteps === undefined) {
  11628. options.lockstepMaxSteps = 4;
  11629. }
  11630. if (options.preserveDrawingBuffer === undefined) {
  11631. options.preserveDrawingBuffer = false;
  11632. }
  11633. if (options.audioEngine === undefined) {
  11634. options.audioEngine = true;
  11635. }
  11636. if (options.stencil === undefined) {
  11637. options.stencil = true;
  11638. }
  11639. if (options.premultipliedAlpha === false) {
  11640. this.premultipliedAlpha = false;
  11641. }
  11642. this._deterministicLockstep = options.deterministicLockstep;
  11643. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11644. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11645. // Exceptions
  11646. if (navigator && navigator.userAgent) {
  11647. var ua = navigator.userAgent;
  11648. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11649. var exception = _a[_i];
  11650. var key = exception.key;
  11651. var targets = exception.targets;
  11652. if (ua.indexOf(key) > -1) {
  11653. if (exception.capture && exception.captureConstraint) {
  11654. var capture = exception.capture;
  11655. var constraint = exception.captureConstraint;
  11656. var regex = new RegExp(capture);
  11657. var matches = regex.exec(ua);
  11658. if (matches && matches.length > 0) {
  11659. var capturedValue = parseInt(matches[matches.length - 1]);
  11660. if (capturedValue >= constraint) {
  11661. continue;
  11662. }
  11663. }
  11664. }
  11665. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11666. var target = targets_1[_b];
  11667. switch (target) {
  11668. case "uniformBuffer":
  11669. this.disableUniformBuffers = true;
  11670. break;
  11671. case "textureBindingOptimization":
  11672. this.disableTextureBindingOptimization = true;
  11673. break;
  11674. }
  11675. }
  11676. }
  11677. }
  11678. }
  11679. // GL
  11680. if (!options.disableWebGL2Support) {
  11681. try {
  11682. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11683. if (this._gl) {
  11684. this._webGLVersion = 2.0;
  11685. }
  11686. }
  11687. catch (e) {
  11688. // Do nothing
  11689. }
  11690. }
  11691. if (!this._gl) {
  11692. if (!canvas) {
  11693. throw new Error("The provided canvas is null or undefined.");
  11694. }
  11695. try {
  11696. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11697. }
  11698. catch (e) {
  11699. throw new Error("WebGL not supported");
  11700. }
  11701. }
  11702. if (!this._gl) {
  11703. throw new Error("WebGL not supported");
  11704. }
  11705. this._onCanvasFocus = function () {
  11706. _this.onCanvasFocusObservable.notifyObservers(_this);
  11707. };
  11708. this._onCanvasBlur = function () {
  11709. _this.onCanvasBlurObservable.notifyObservers(_this);
  11710. };
  11711. canvas.addEventListener("focus", this._onCanvasFocus);
  11712. canvas.addEventListener("blur", this._onCanvasBlur);
  11713. this._onBlur = function () {
  11714. if (_this.disablePerformanceMonitorInBackground) {
  11715. _this._performanceMonitor.disable();
  11716. }
  11717. _this._windowIsBackground = true;
  11718. };
  11719. this._onFocus = function () {
  11720. if (_this.disablePerformanceMonitorInBackground) {
  11721. _this._performanceMonitor.enable();
  11722. }
  11723. _this._windowIsBackground = false;
  11724. };
  11725. this._onCanvasPointerOut = function (ev) {
  11726. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11727. };
  11728. window.addEventListener("blur", this._onBlur);
  11729. window.addEventListener("focus", this._onFocus);
  11730. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11731. // Context lost
  11732. if (!this._doNotHandleContextLost) {
  11733. this._onContextLost = function (evt) {
  11734. evt.preventDefault();
  11735. _this._contextWasLost = true;
  11736. BABYLON.Tools.Warn("WebGL context lost.");
  11737. _this.onContextLostObservable.notifyObservers(_this);
  11738. };
  11739. this._onContextRestored = function (evt) {
  11740. // Adding a timeout to avoid race condition at browser level
  11741. setTimeout(function () {
  11742. // Rebuild gl context
  11743. _this._initGLContext();
  11744. // Rebuild effects
  11745. _this._rebuildEffects();
  11746. // Rebuild textures
  11747. _this._rebuildInternalTextures();
  11748. // Rebuild buffers
  11749. _this._rebuildBuffers();
  11750. // Cache
  11751. _this.wipeCaches(true);
  11752. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11753. _this.onContextRestoredObservable.notifyObservers(_this);
  11754. _this._contextWasLost = false;
  11755. }, 0);
  11756. };
  11757. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11758. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11759. }
  11760. }
  11761. else {
  11762. this._gl = canvasOrContext;
  11763. this._renderingCanvas = this._gl.canvas;
  11764. if (this._gl.renderbufferStorageMultisample) {
  11765. this._webGLVersion = 2.0;
  11766. }
  11767. options.stencil = this._gl.getContextAttributes().stencil;
  11768. }
  11769. // Viewport
  11770. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11771. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11772. this.resize();
  11773. this._isStencilEnable = options.stencil ? true : false;
  11774. this._initGLContext();
  11775. if (canvas) {
  11776. // Fullscreen
  11777. this._onFullscreenChange = function () {
  11778. if (document.fullscreen !== undefined) {
  11779. _this.isFullscreen = document.fullscreen;
  11780. }
  11781. else if (document.mozFullScreen !== undefined) {
  11782. _this.isFullscreen = document.mozFullScreen;
  11783. }
  11784. else if (document.webkitIsFullScreen !== undefined) {
  11785. _this.isFullscreen = document.webkitIsFullScreen;
  11786. }
  11787. else if (document.msIsFullScreen !== undefined) {
  11788. _this.isFullscreen = document.msIsFullScreen;
  11789. }
  11790. // Pointer lock
  11791. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11792. canvas.requestPointerLock = canvas.requestPointerLock ||
  11793. canvas.msRequestPointerLock ||
  11794. canvas.mozRequestPointerLock ||
  11795. canvas.webkitRequestPointerLock;
  11796. if (canvas.requestPointerLock) {
  11797. canvas.requestPointerLock();
  11798. }
  11799. }
  11800. };
  11801. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11802. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11803. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11804. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11805. // Pointer lock
  11806. this._onPointerLockChange = function () {
  11807. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11808. document.webkitPointerLockElement === canvas ||
  11809. document.msPointerLockElement === canvas ||
  11810. document.pointerLockElement === canvas);
  11811. };
  11812. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11813. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11814. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11815. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11816. this._onVRDisplayPointerRestricted = function () {
  11817. if (canvas) {
  11818. canvas.requestPointerLock();
  11819. }
  11820. };
  11821. this._onVRDisplayPointerUnrestricted = function () {
  11822. document.exitPointerLock();
  11823. };
  11824. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11825. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11826. }
  11827. // Create Audio Engine if needed.
  11828. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11829. Engine.audioEngine = Engine.AudioEngineFactory(this);
  11830. }
  11831. // Prepare buffer pointers
  11832. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11833. this._currentBufferPointers[i] = new BufferPointer();
  11834. }
  11835. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11836. // Load WebVR Devices
  11837. if (options.autoEnableWebVR) {
  11838. this.initWebVR();
  11839. }
  11840. // Detect if we are running on a faulty buggy OS.
  11841. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11842. // Detect if we are running on a faulty buggy desktop OS.
  11843. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11844. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11845. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11846. }
  11847. Object.defineProperty(Engine, "LastCreatedEngine", {
  11848. /**
  11849. * Gets the latest created engine
  11850. */
  11851. get: function () {
  11852. if (Engine.Instances.length === 0) {
  11853. return null;
  11854. }
  11855. return Engine.Instances[Engine.Instances.length - 1];
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine, "LastCreatedScene", {
  11861. /**
  11862. * Gets the latest created scene
  11863. */
  11864. get: function () {
  11865. var lastCreatedEngine = Engine.LastCreatedEngine;
  11866. if (!lastCreatedEngine) {
  11867. return null;
  11868. }
  11869. if (lastCreatedEngine.scenes.length === 0) {
  11870. return null;
  11871. }
  11872. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. /**
  11878. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11879. * @param flag defines which part of the materials must be marked as dirty
  11880. * @param predicate defines a predicate used to filter which materials should be affected
  11881. */
  11882. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11883. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11884. var engine = Engine.Instances[engineIndex];
  11885. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11886. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11887. }
  11888. }
  11889. };
  11890. Object.defineProperty(Engine, "Version", {
  11891. /**
  11892. * Returns the current version of the framework
  11893. */
  11894. get: function () {
  11895. return "3.3.0-beta.5";
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11901. /**
  11902. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11903. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11904. */
  11905. get: function () {
  11906. return this._vrExclusivePointerMode;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11912. /**
  11913. * Gets a boolean indicating that the engine supports uniform buffers
  11914. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11915. */
  11916. get: function () {
  11917. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11923. /**
  11924. * Gets a boolean indicating that only power of 2 textures are supported
  11925. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11926. */
  11927. get: function () {
  11928. return this._webGLVersion < 2 || this.forcePOTTextures;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11934. /**
  11935. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11936. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11937. */
  11938. get: function () {
  11939. return this._doNotHandleContextLost;
  11940. },
  11941. set: function (value) {
  11942. this._doNotHandleContextLost = value;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11948. /**
  11949. * Gets the performance monitor attached to this engine
  11950. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11951. */
  11952. get: function () {
  11953. return this._performanceMonitor;
  11954. },
  11955. enumerable: true,
  11956. configurable: true
  11957. });
  11958. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11959. /**
  11960. * Gets the list of texture formats supported
  11961. */
  11962. get: function () {
  11963. return this._texturesSupported;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11969. /**
  11970. * Gets the list of texture formats in use
  11971. */
  11972. get: function () {
  11973. return this._textureFormatInUse;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(Engine.prototype, "currentViewport", {
  11979. /**
  11980. * Gets the current viewport
  11981. */
  11982. get: function () {
  11983. return this._cachedViewport;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11989. /**
  11990. * Gets the default empty texture
  11991. */
  11992. get: function () {
  11993. if (!this._emptyTexture) {
  11994. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11995. }
  11996. return this._emptyTexture;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12002. /**
  12003. * Gets the default empty 3D texture
  12004. */
  12005. get: function () {
  12006. if (!this._emptyTexture3D) {
  12007. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12008. }
  12009. return this._emptyTexture3D;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12015. /**
  12016. * Gets the default empty cube texture
  12017. */
  12018. get: function () {
  12019. if (!this._emptyCubeTexture) {
  12020. var faceData = new Uint8Array(4);
  12021. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12022. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12023. }
  12024. return this._emptyCubeTexture;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Engine.prototype._rebuildInternalTextures = function () {
  12030. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12031. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12032. var internalTexture = currentState_1[_i];
  12033. internalTexture._rebuild();
  12034. }
  12035. };
  12036. Engine.prototype._rebuildEffects = function () {
  12037. for (var key in this._compiledEffects) {
  12038. var effect = this._compiledEffects[key];
  12039. effect._prepareEffect();
  12040. }
  12041. BABYLON.Effect.ResetCache();
  12042. };
  12043. Engine.prototype._rebuildBuffers = function () {
  12044. // Index / Vertex
  12045. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12046. var scene = _a[_i];
  12047. scene.resetCachedMaterial();
  12048. scene._rebuildGeometries();
  12049. scene._rebuildTextures();
  12050. }
  12051. // Uniforms
  12052. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12053. var uniformBuffer = _c[_b];
  12054. uniformBuffer._rebuild();
  12055. }
  12056. };
  12057. Engine.prototype._initGLContext = function () {
  12058. // Caps
  12059. this._caps = new EngineCapabilities();
  12060. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12061. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12062. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12063. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12064. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12065. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12066. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12067. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12068. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12069. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12070. // Infos
  12071. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12072. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12073. if (rendererInfo != null) {
  12074. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12075. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12076. }
  12077. if (!this._glVendor) {
  12078. this._glVendor = "Unknown vendor";
  12079. }
  12080. if (!this._glRenderer) {
  12081. this._glRenderer = "Unknown renderer";
  12082. }
  12083. // Constants
  12084. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12085. if (this._gl.RGBA16F !== 0x881A) {
  12086. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12087. }
  12088. if (this._gl.RGBA32F !== 0x8814) {
  12089. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12090. }
  12091. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12092. this._gl.DEPTH24_STENCIL8 = 35056;
  12093. }
  12094. // Extensions
  12095. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12096. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12097. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12098. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12099. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12100. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12101. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12102. 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');
  12103. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12104. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12105. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12106. this._caps.highPrecisionShaderSupported = true;
  12107. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12108. if (this._caps.timerQuery) {
  12109. if (this._webGLVersion === 1) {
  12110. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12111. }
  12112. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12113. }
  12114. // Checks if some of the format renders first to allow the use of webgl inspector.
  12115. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12116. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12117. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12118. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12119. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12120. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12121. if (this._webGLVersion > 1) {
  12122. this._gl.HALF_FLOAT_OES = 0x140B;
  12123. }
  12124. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12125. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12126. // Draw buffers
  12127. if (this._webGLVersion > 1) {
  12128. this._caps.drawBuffersExtension = true;
  12129. }
  12130. else {
  12131. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12132. if (drawBuffersExtension !== null) {
  12133. this._caps.drawBuffersExtension = true;
  12134. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12135. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12136. for (var i = 0; i < 16; i++) {
  12137. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12138. }
  12139. }
  12140. else {
  12141. this._caps.drawBuffersExtension = false;
  12142. }
  12143. }
  12144. // Depth Texture
  12145. if (this._webGLVersion > 1) {
  12146. this._caps.depthTextureExtension = true;
  12147. }
  12148. else {
  12149. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12150. if (depthTextureExtension != null) {
  12151. this._caps.depthTextureExtension = true;
  12152. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12153. }
  12154. }
  12155. // Vertex array object
  12156. if (this._webGLVersion > 1) {
  12157. this._caps.vertexArrayObject = true;
  12158. }
  12159. else {
  12160. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12161. if (vertexArrayObjectExtension != null) {
  12162. this._caps.vertexArrayObject = true;
  12163. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12164. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12165. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12166. }
  12167. else {
  12168. this._caps.vertexArrayObject = false;
  12169. }
  12170. }
  12171. // Instances count
  12172. if (this._webGLVersion > 1) {
  12173. this._caps.instancedArrays = true;
  12174. }
  12175. else {
  12176. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12177. if (instanceExtension != null) {
  12178. this._caps.instancedArrays = true;
  12179. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12180. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12181. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12182. }
  12183. else {
  12184. this._caps.instancedArrays = false;
  12185. }
  12186. }
  12187. // Intelligently add supported compressed formats in order to check for.
  12188. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12189. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12190. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12191. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12192. if (this._caps.astc)
  12193. this.texturesSupported.push('-astc.ktx');
  12194. if (this._caps.s3tc)
  12195. this.texturesSupported.push('-dxt.ktx');
  12196. if (this._caps.pvrtc)
  12197. this.texturesSupported.push('-pvrtc.ktx');
  12198. if (this._caps.etc2)
  12199. this.texturesSupported.push('-etc2.ktx');
  12200. if (this._caps.etc1)
  12201. this.texturesSupported.push('-etc1.ktx');
  12202. if (this._gl.getShaderPrecisionFormat) {
  12203. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12204. if (highp) {
  12205. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12206. }
  12207. }
  12208. // Depth buffer
  12209. this.setDepthBuffer(true);
  12210. this.setDepthFunctionToLessOrEqual();
  12211. this.setDepthWrite(true);
  12212. // Texture maps
  12213. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12214. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12215. this._nextFreeTextureSlots.push(slot);
  12216. }
  12217. };
  12218. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12219. /**
  12220. * Gets version of the current webGL context
  12221. */
  12222. get: function () {
  12223. return this._webGLVersion;
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12229. /**
  12230. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12231. */
  12232. get: function () {
  12233. return this._isStencilEnable;
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. Engine.prototype._prepareWorkingCanvas = function () {
  12239. if (this._workingCanvas) {
  12240. return;
  12241. }
  12242. this._workingCanvas = document.createElement("canvas");
  12243. var context = this._workingCanvas.getContext("2d");
  12244. if (context) {
  12245. this._workingContext = context;
  12246. }
  12247. };
  12248. /**
  12249. * Reset the texture cache to empty state
  12250. */
  12251. Engine.prototype.resetTextureCache = function () {
  12252. for (var key in this._boundTexturesCache) {
  12253. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12254. continue;
  12255. }
  12256. var boundTexture = this._boundTexturesCache[key];
  12257. if (boundTexture) {
  12258. this._removeDesignatedSlot(boundTexture);
  12259. }
  12260. this._boundTexturesCache[key] = null;
  12261. }
  12262. if (!this.disableTextureBindingOptimization) {
  12263. this._nextFreeTextureSlots = [];
  12264. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12265. this._nextFreeTextureSlots.push(slot);
  12266. }
  12267. }
  12268. this._currentTextureChannel = -1;
  12269. };
  12270. /**
  12271. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12272. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12273. * @returns true if engine is in deterministic lock step mode
  12274. */
  12275. Engine.prototype.isDeterministicLockStep = function () {
  12276. return this._deterministicLockstep;
  12277. };
  12278. /**
  12279. * Gets the max steps when engine is running in deterministic lock step
  12280. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12281. * @returns the max steps
  12282. */
  12283. Engine.prototype.getLockstepMaxSteps = function () {
  12284. return this._lockstepMaxSteps;
  12285. };
  12286. /**
  12287. * Gets an object containing information about the current webGL context
  12288. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12289. */
  12290. Engine.prototype.getGlInfo = function () {
  12291. return {
  12292. vendor: this._glVendor,
  12293. renderer: this._glRenderer,
  12294. version: this._glVersion
  12295. };
  12296. };
  12297. /**
  12298. * Gets current aspect ratio
  12299. * @param camera defines the camera to use to get the aspect ratio
  12300. * @param useScreen defines if screen size must be used (or the current render target if any)
  12301. * @returns a number defining the aspect ratio
  12302. */
  12303. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12304. if (useScreen === void 0) { useScreen = false; }
  12305. var viewport = camera.viewport;
  12306. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12307. };
  12308. /**
  12309. * Gets current screen aspect ratio
  12310. * @returns a number defining the aspect ratio
  12311. */
  12312. Engine.prototype.getScreenAspectRatio = function () {
  12313. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12314. };
  12315. /**
  12316. * Gets the current render width
  12317. * @param useScreen defines if screen size must be used (or the current render target if any)
  12318. * @returns a number defining the current render width
  12319. */
  12320. Engine.prototype.getRenderWidth = function (useScreen) {
  12321. if (useScreen === void 0) { useScreen = false; }
  12322. if (!useScreen && this._currentRenderTarget) {
  12323. return this._currentRenderTarget.width;
  12324. }
  12325. return this._gl.drawingBufferWidth;
  12326. };
  12327. /**
  12328. * Gets the current render height
  12329. * @param useScreen defines if screen size must be used (or the current render target if any)
  12330. * @returns a number defining the current render height
  12331. */
  12332. Engine.prototype.getRenderHeight = function (useScreen) {
  12333. if (useScreen === void 0) { useScreen = false; }
  12334. if (!useScreen && this._currentRenderTarget) {
  12335. return this._currentRenderTarget.height;
  12336. }
  12337. return this._gl.drawingBufferHeight;
  12338. };
  12339. /**
  12340. * Gets the HTML canvas attached with the current webGL context
  12341. * @returns a HTML canvas
  12342. */
  12343. Engine.prototype.getRenderingCanvas = function () {
  12344. return this._renderingCanvas;
  12345. };
  12346. /**
  12347. * Gets the client rect of the HTML canvas attached with the current webGL context
  12348. * @returns a client rectanglee
  12349. */
  12350. Engine.prototype.getRenderingCanvasClientRect = function () {
  12351. if (!this._renderingCanvas) {
  12352. return null;
  12353. }
  12354. return this._renderingCanvas.getBoundingClientRect();
  12355. };
  12356. /**
  12357. * Defines the hardware scaling level.
  12358. * By default the hardware scaling level is computed from the window device ratio.
  12359. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12360. * @param level defines the level to use
  12361. */
  12362. Engine.prototype.setHardwareScalingLevel = function (level) {
  12363. this._hardwareScalingLevel = level;
  12364. this.resize();
  12365. };
  12366. /**
  12367. * Gets the current hardware scaling level.
  12368. * By default the hardware scaling level is computed from the window device ratio.
  12369. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12370. * @returns a number indicating the current hardware scaling level
  12371. */
  12372. Engine.prototype.getHardwareScalingLevel = function () {
  12373. return this._hardwareScalingLevel;
  12374. };
  12375. /**
  12376. * Gets the list of loaded textures
  12377. * @returns an array containing all loaded textures
  12378. */
  12379. Engine.prototype.getLoadedTexturesCache = function () {
  12380. return this._internalTexturesCache;
  12381. };
  12382. /**
  12383. * Gets the object containing all engine capabilities
  12384. * @returns the EngineCapabilities object
  12385. */
  12386. Engine.prototype.getCaps = function () {
  12387. return this._caps;
  12388. };
  12389. Object.defineProperty(Engine.prototype, "drawCalls", {
  12390. /** @hidden */
  12391. get: function () {
  12392. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12393. return 0;
  12394. },
  12395. enumerable: true,
  12396. configurable: true
  12397. });
  12398. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12399. /** @hidden */
  12400. get: function () {
  12401. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12402. return null;
  12403. },
  12404. enumerable: true,
  12405. configurable: true
  12406. });
  12407. /**
  12408. * Gets the current depth function
  12409. * @returns a number defining the depth function
  12410. */
  12411. Engine.prototype.getDepthFunction = function () {
  12412. return this._depthCullingState.depthFunc;
  12413. };
  12414. /**
  12415. * Sets the current depth function
  12416. * @param depthFunc defines the function to use
  12417. */
  12418. Engine.prototype.setDepthFunction = function (depthFunc) {
  12419. this._depthCullingState.depthFunc = depthFunc;
  12420. };
  12421. /**
  12422. * Sets the current depth function to GREATER
  12423. */
  12424. Engine.prototype.setDepthFunctionToGreater = function () {
  12425. this._depthCullingState.depthFunc = this._gl.GREATER;
  12426. };
  12427. /**
  12428. * Sets the current depth function to GEQUAL
  12429. */
  12430. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12431. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12432. };
  12433. /**
  12434. * Sets the current depth function to LESS
  12435. */
  12436. Engine.prototype.setDepthFunctionToLess = function () {
  12437. this._depthCullingState.depthFunc = this._gl.LESS;
  12438. };
  12439. /**
  12440. * Sets the current depth function to LEQUAL
  12441. */
  12442. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12443. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12444. };
  12445. /**
  12446. * Gets a boolean indicating if stencil buffer is enabled
  12447. * @returns the current stencil buffer state
  12448. */
  12449. Engine.prototype.getStencilBuffer = function () {
  12450. return this._stencilState.stencilTest;
  12451. };
  12452. /**
  12453. * Enable or disable the stencil buffer
  12454. * @param enable defines if the stencil buffer must be enabled or disabled
  12455. */
  12456. Engine.prototype.setStencilBuffer = function (enable) {
  12457. this._stencilState.stencilTest = enable;
  12458. };
  12459. /**
  12460. * Gets the current stencil mask
  12461. * @returns a number defining the new stencil mask to use
  12462. */
  12463. Engine.prototype.getStencilMask = function () {
  12464. return this._stencilState.stencilMask;
  12465. };
  12466. /**
  12467. * Sets the current stencil mask
  12468. * @param mask defines the new stencil mask to use
  12469. */
  12470. Engine.prototype.setStencilMask = function (mask) {
  12471. this._stencilState.stencilMask = mask;
  12472. };
  12473. /**
  12474. * Gets the current stencil function
  12475. * @returns a number defining the stencil function to use
  12476. */
  12477. Engine.prototype.getStencilFunction = function () {
  12478. return this._stencilState.stencilFunc;
  12479. };
  12480. /**
  12481. * Gets the current stencil reference value
  12482. * @returns a number defining the stencil reference value to use
  12483. */
  12484. Engine.prototype.getStencilFunctionReference = function () {
  12485. return this._stencilState.stencilFuncRef;
  12486. };
  12487. /**
  12488. * Gets the current stencil mask
  12489. * @returns a number defining the stencil mask to use
  12490. */
  12491. Engine.prototype.getStencilFunctionMask = function () {
  12492. return this._stencilState.stencilFuncMask;
  12493. };
  12494. /**
  12495. * Sets the current stencil function
  12496. * @param stencilFunc defines the new stencil function to use
  12497. */
  12498. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12499. this._stencilState.stencilFunc = stencilFunc;
  12500. };
  12501. /**
  12502. * Sets the current stencil reference
  12503. * @param reference defines the new stencil reference to use
  12504. */
  12505. Engine.prototype.setStencilFunctionReference = function (reference) {
  12506. this._stencilState.stencilFuncRef = reference;
  12507. };
  12508. /**
  12509. * Sets the current stencil mask
  12510. * @param mask defines the new stencil mask to use
  12511. */
  12512. Engine.prototype.setStencilFunctionMask = function (mask) {
  12513. this._stencilState.stencilFuncMask = mask;
  12514. };
  12515. /**
  12516. * Gets the current stencil operation when stencil fails
  12517. * @returns a number defining stencil operation to use when stencil fails
  12518. */
  12519. Engine.prototype.getStencilOperationFail = function () {
  12520. return this._stencilState.stencilOpStencilFail;
  12521. };
  12522. /**
  12523. * Gets the current stencil operation when depth fails
  12524. * @returns a number defining stencil operation to use when depth fails
  12525. */
  12526. Engine.prototype.getStencilOperationDepthFail = function () {
  12527. return this._stencilState.stencilOpDepthFail;
  12528. };
  12529. /**
  12530. * Gets the current stencil operation when stencil passes
  12531. * @returns a number defining stencil operation to use when stencil passes
  12532. */
  12533. Engine.prototype.getStencilOperationPass = function () {
  12534. return this._stencilState.stencilOpStencilDepthPass;
  12535. };
  12536. /**
  12537. * Sets the stencil operation to use when stencil fails
  12538. * @param operation defines the stencil operation to use when stencil fails
  12539. */
  12540. Engine.prototype.setStencilOperationFail = function (operation) {
  12541. this._stencilState.stencilOpStencilFail = operation;
  12542. };
  12543. /**
  12544. * Sets the stencil operation to use when depth fails
  12545. * @param operation defines the stencil operation to use when depth fails
  12546. */
  12547. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12548. this._stencilState.stencilOpDepthFail = operation;
  12549. };
  12550. /**
  12551. * Sets the stencil operation to use when stencil passes
  12552. * @param operation defines the stencil operation to use when stencil passes
  12553. */
  12554. Engine.prototype.setStencilOperationPass = function (operation) {
  12555. this._stencilState.stencilOpStencilDepthPass = operation;
  12556. };
  12557. /**
  12558. * Sets a boolean indicating if the dithering state is enabled or disabled
  12559. * @param value defines the dithering state
  12560. */
  12561. Engine.prototype.setDitheringState = function (value) {
  12562. if (value) {
  12563. this._gl.enable(this._gl.DITHER);
  12564. }
  12565. else {
  12566. this._gl.disable(this._gl.DITHER);
  12567. }
  12568. };
  12569. /**
  12570. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12571. * @param value defines the rasterizer state
  12572. */
  12573. Engine.prototype.setRasterizerState = function (value) {
  12574. if (value) {
  12575. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12576. }
  12577. else {
  12578. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12579. }
  12580. };
  12581. /**
  12582. * stop executing a render loop function and remove it from the execution array
  12583. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12584. */
  12585. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12586. if (!renderFunction) {
  12587. this._activeRenderLoops = [];
  12588. return;
  12589. }
  12590. var index = this._activeRenderLoops.indexOf(renderFunction);
  12591. if (index >= 0) {
  12592. this._activeRenderLoops.splice(index, 1);
  12593. }
  12594. };
  12595. /** @hidden */
  12596. Engine.prototype._renderLoop = function () {
  12597. if (!this._contextWasLost) {
  12598. var shouldRender = true;
  12599. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12600. shouldRender = false;
  12601. }
  12602. if (shouldRender) {
  12603. // Start new frame
  12604. this.beginFrame();
  12605. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12606. var renderFunction = this._activeRenderLoops[index];
  12607. renderFunction();
  12608. }
  12609. // Present
  12610. this.endFrame();
  12611. }
  12612. }
  12613. if (this._activeRenderLoops.length > 0) {
  12614. // Register new frame
  12615. var requester = null;
  12616. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12617. requester = this._vrDisplay;
  12618. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12619. }
  12620. else {
  12621. this._renderingQueueLaunched = false;
  12622. }
  12623. };
  12624. /**
  12625. * Register and execute a render loop. The engine can have more than one render function
  12626. * @param renderFunction defines the function to continuously execute
  12627. */
  12628. Engine.prototype.runRenderLoop = function (renderFunction) {
  12629. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12630. return;
  12631. }
  12632. this._activeRenderLoops.push(renderFunction);
  12633. if (!this._renderingQueueLaunched) {
  12634. this._renderingQueueLaunched = true;
  12635. this._bindedRenderFunction = this._renderLoop.bind(this);
  12636. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12637. }
  12638. };
  12639. /**
  12640. * Toggle full screen mode
  12641. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12642. * @param options defines an option object to be sent to the requestFullscreen function
  12643. */
  12644. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12645. if (this.isFullscreen) {
  12646. BABYLON.Tools.ExitFullscreen();
  12647. }
  12648. else {
  12649. this._pointerLockRequested = requestPointerLock;
  12650. if (this._renderingCanvas) {
  12651. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12652. }
  12653. }
  12654. };
  12655. /**
  12656. * Clear the current render buffer or the current render target (if any is set up)
  12657. * @param color defines the color to use
  12658. * @param backBuffer defines if the back buffer must be cleared
  12659. * @param depth defines if the depth buffer must be cleared
  12660. * @param stencil defines if the stencil buffer must be cleared
  12661. */
  12662. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12663. if (stencil === void 0) { stencil = false; }
  12664. this.applyStates();
  12665. var mode = 0;
  12666. if (backBuffer && color) {
  12667. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12668. mode |= this._gl.COLOR_BUFFER_BIT;
  12669. }
  12670. if (depth) {
  12671. this._gl.clearDepth(1.0);
  12672. mode |= this._gl.DEPTH_BUFFER_BIT;
  12673. }
  12674. if (stencil) {
  12675. this._gl.clearStencil(0);
  12676. mode |= this._gl.STENCIL_BUFFER_BIT;
  12677. }
  12678. this._gl.clear(mode);
  12679. };
  12680. /**
  12681. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12682. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12683. * @param y defines the y-coordinate of the corner of the clear rectangle
  12684. * @param width defines the width of the clear rectangle
  12685. * @param height defines the height of the clear rectangle
  12686. * @param clearColor defines the clear color
  12687. */
  12688. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12689. var gl = this._gl;
  12690. // Save state
  12691. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12692. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12693. // Change state
  12694. gl.enable(gl.SCISSOR_TEST);
  12695. gl.scissor(x, y, width, height);
  12696. // Clear
  12697. this.clear(clearColor, true, true, true);
  12698. // Restore state
  12699. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12700. if (curScissor === true) {
  12701. gl.enable(gl.SCISSOR_TEST);
  12702. }
  12703. else {
  12704. gl.disable(gl.SCISSOR_TEST);
  12705. }
  12706. };
  12707. /** @hidden */
  12708. Engine.prototype._viewport = function (x, y, width, height) {
  12709. if (x !== this._viewportCached.x ||
  12710. y !== this._viewportCached.y ||
  12711. width !== this._viewportCached.z ||
  12712. height !== this._viewportCached.w) {
  12713. this._viewportCached.x = x;
  12714. this._viewportCached.y = y;
  12715. this._viewportCached.z = width;
  12716. this._viewportCached.w = height;
  12717. this._gl.viewport(x, y, width, height);
  12718. }
  12719. };
  12720. /**
  12721. * Set the WebGL's viewport
  12722. * @param viewport defines the viewport element to be used
  12723. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12724. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12725. */
  12726. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12727. var width = requiredWidth || this.getRenderWidth();
  12728. var height = requiredHeight || this.getRenderHeight();
  12729. var x = viewport.x || 0;
  12730. var y = viewport.y || 0;
  12731. this._cachedViewport = viewport;
  12732. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12733. };
  12734. /**
  12735. * Directly set the WebGL Viewport
  12736. * @param x defines the x coordinate of the viewport (in screen space)
  12737. * @param y defines the y coordinate of the viewport (in screen space)
  12738. * @param width defines the width of the viewport (in screen space)
  12739. * @param height defines the height of the viewport (in screen space)
  12740. * @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
  12741. */
  12742. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12743. var currentViewport = this._cachedViewport;
  12744. this._cachedViewport = null;
  12745. this._viewport(x, y, width, height);
  12746. return currentViewport;
  12747. };
  12748. /**
  12749. * Begin a new frame
  12750. */
  12751. Engine.prototype.beginFrame = function () {
  12752. this.onBeginFrameObservable.notifyObservers(this);
  12753. this._measureFps();
  12754. };
  12755. /**
  12756. * Enf the current frame
  12757. */
  12758. Engine.prototype.endFrame = function () {
  12759. // Force a flush in case we are using a bad OS.
  12760. if (this._badOS) {
  12761. this.flushFramebuffer();
  12762. }
  12763. // Submit frame to the vr device, if enabled
  12764. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12765. // TODO: We should only submit the frame if we read frameData successfully.
  12766. this._vrDisplay.submitFrame();
  12767. }
  12768. this.onEndFrameObservable.notifyObservers(this);
  12769. };
  12770. /**
  12771. * Resize the view according to the canvas' size
  12772. */
  12773. Engine.prototype.resize = function () {
  12774. // We're not resizing the size of the canvas while in VR mode & presenting
  12775. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12776. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12777. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12778. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12779. }
  12780. };
  12781. /**
  12782. * Force a specific size of the canvas
  12783. * @param width defines the new canvas' width
  12784. * @param height defines the new canvas' height
  12785. */
  12786. Engine.prototype.setSize = function (width, height) {
  12787. if (!this._renderingCanvas) {
  12788. return;
  12789. }
  12790. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12791. return;
  12792. }
  12793. this._renderingCanvas.width = width;
  12794. this._renderingCanvas.height = height;
  12795. for (var index = 0; index < this.scenes.length; index++) {
  12796. var scene = this.scenes[index];
  12797. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12798. var cam = scene.cameras[camIndex];
  12799. cam._currentRenderId = 0;
  12800. }
  12801. }
  12802. if (this.onResizeObservable.hasObservers) {
  12803. this.onResizeObservable.notifyObservers(this);
  12804. }
  12805. };
  12806. // WebVR functions
  12807. /**
  12808. * Gets a boolean indicating if a webVR device was detected
  12809. * @returns true if a webVR device was detected
  12810. */
  12811. Engine.prototype.isVRDevicePresent = function () {
  12812. return !!this._vrDisplay;
  12813. };
  12814. /**
  12815. * Gets the current webVR device
  12816. * @returns the current webVR device (or null)
  12817. */
  12818. Engine.prototype.getVRDevice = function () {
  12819. return this._vrDisplay;
  12820. };
  12821. /**
  12822. * Initializes a webVR display and starts listening to display change events
  12823. * The onVRDisplayChangedObservable will be notified upon these changes
  12824. * @returns The onVRDisplayChangedObservable
  12825. */
  12826. Engine.prototype.initWebVR = function () {
  12827. this.initWebVRAsync();
  12828. return this.onVRDisplayChangedObservable;
  12829. };
  12830. /**
  12831. * Initializes a webVR display and starts listening to display change events
  12832. * The onVRDisplayChangedObservable will be notified upon these changes
  12833. * @returns A promise containing a VRDisplay and if vr is supported
  12834. */
  12835. Engine.prototype.initWebVRAsync = function () {
  12836. var _this = this;
  12837. var notifyObservers = function () {
  12838. var eventArgs = {
  12839. vrDisplay: _this._vrDisplay,
  12840. vrSupported: _this._vrSupported
  12841. };
  12842. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12843. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12844. };
  12845. if (!this._onVrDisplayConnect) {
  12846. this._onVrDisplayConnect = function (event) {
  12847. _this._vrDisplay = event.display;
  12848. notifyObservers();
  12849. };
  12850. this._onVrDisplayDisconnect = function () {
  12851. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12852. _this._vrDisplay = undefined;
  12853. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12854. notifyObservers();
  12855. };
  12856. this._onVrDisplayPresentChange = function () {
  12857. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12858. };
  12859. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12860. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12861. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12862. }
  12863. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12864. this._webVRInitPromise.then(notifyObservers);
  12865. return this._webVRInitPromise;
  12866. };
  12867. /**
  12868. * Call this function to switch to webVR mode
  12869. * Will do nothing if webVR is not supported or if there is no webVR device
  12870. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12871. */
  12872. Engine.prototype.enableVR = function () {
  12873. var _this = this;
  12874. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12875. var onResolved = function () {
  12876. _this.onVRRequestPresentComplete.notifyObservers(true);
  12877. _this._onVRFullScreenTriggered();
  12878. };
  12879. var onRejected = function () {
  12880. _this.onVRRequestPresentComplete.notifyObservers(false);
  12881. };
  12882. this.onVRRequestPresentStart.notifyObservers(this);
  12883. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12884. }
  12885. };
  12886. /**
  12887. * Call this function to leave webVR mode
  12888. * Will do nothing if webVR is not supported or if there is no webVR device
  12889. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12890. */
  12891. Engine.prototype.disableVR = function () {
  12892. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12893. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12894. }
  12895. };
  12896. Engine.prototype._getVRDisplaysAsync = function () {
  12897. var _this = this;
  12898. return new Promise(function (res, rej) {
  12899. if (navigator.getVRDisplays) {
  12900. navigator.getVRDisplays().then(function (devices) {
  12901. _this._vrSupported = true;
  12902. // note that devices may actually be an empty array. This is fine;
  12903. // we expect this._vrDisplay to be undefined in this case.
  12904. _this._vrDisplay = devices[0];
  12905. res({
  12906. vrDisplay: _this._vrDisplay,
  12907. vrSupported: _this._vrSupported
  12908. });
  12909. });
  12910. }
  12911. else {
  12912. _this._vrDisplay = undefined;
  12913. _this._vrSupported = false;
  12914. res({
  12915. vrDisplay: _this._vrDisplay,
  12916. vrSupported: _this._vrSupported
  12917. });
  12918. }
  12919. });
  12920. };
  12921. /**
  12922. * Binds the frame buffer to the specified texture.
  12923. * @param texture The texture to render to or null for the default canvas
  12924. * @param faceIndex The face of the texture to render to in case of cube texture
  12925. * @param requiredWidth The width of the target to render to
  12926. * @param requiredHeight The height of the target to render to
  12927. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12928. * @param depthStencilTexture The depth stencil texture to use to render
  12929. * @param lodLevel defines le lod level to bind to the frame buffer
  12930. */
  12931. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12932. if (lodLevel === void 0) { lodLevel = 0; }
  12933. if (this._currentRenderTarget) {
  12934. this.unBindFramebuffer(this._currentRenderTarget);
  12935. }
  12936. this._currentRenderTarget = texture;
  12937. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12938. var gl = this._gl;
  12939. if (texture.isCube) {
  12940. if (faceIndex === undefined) {
  12941. faceIndex = 0;
  12942. }
  12943. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12944. if (depthStencilTexture) {
  12945. if (depthStencilTexture._generateStencilBuffer) {
  12946. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12947. }
  12948. else {
  12949. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12950. }
  12951. }
  12952. }
  12953. if (this._cachedViewport && !forceFullscreenViewport) {
  12954. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12955. }
  12956. else {
  12957. if (!requiredWidth) {
  12958. requiredWidth = texture.width;
  12959. if (lodLevel) {
  12960. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12961. }
  12962. }
  12963. if (!requiredHeight) {
  12964. requiredHeight = texture.height;
  12965. if (lodLevel) {
  12966. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12967. }
  12968. }
  12969. this._viewport(0, 0, requiredWidth, requiredHeight);
  12970. }
  12971. this.wipeCaches();
  12972. };
  12973. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12974. if (this._currentFramebuffer !== framebuffer) {
  12975. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12976. this._currentFramebuffer = framebuffer;
  12977. }
  12978. };
  12979. /**
  12980. * Unbind the current render target texture from the webGL context
  12981. * @param texture defines the render target texture to unbind
  12982. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12983. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12984. */
  12985. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12986. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12987. this._currentRenderTarget = null;
  12988. // If MSAA, we need to bitblt back to main texture
  12989. var gl = this._gl;
  12990. if (texture._MSAAFramebuffer) {
  12991. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12992. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12993. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12994. }
  12995. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12996. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12997. gl.generateMipmap(gl.TEXTURE_2D);
  12998. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12999. }
  13000. if (onBeforeUnbind) {
  13001. if (texture._MSAAFramebuffer) {
  13002. // Bind the correct framebuffer
  13003. this.bindUnboundFramebuffer(texture._framebuffer);
  13004. }
  13005. onBeforeUnbind();
  13006. }
  13007. this.bindUnboundFramebuffer(null);
  13008. };
  13009. /**
  13010. * Unbind a list of render target textures from the webGL context
  13011. * This is used only when drawBuffer extension or webGL2 are active
  13012. * @param textures defines the render target textures to unbind
  13013. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13014. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13015. */
  13016. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13017. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13018. this._currentRenderTarget = null;
  13019. // If MSAA, we need to bitblt back to main texture
  13020. var gl = this._gl;
  13021. if (textures[0]._MSAAFramebuffer) {
  13022. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13023. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13024. var attachments = textures[0]._attachments;
  13025. if (!attachments) {
  13026. attachments = new Array(textures.length);
  13027. textures[0]._attachments = attachments;
  13028. }
  13029. for (var i = 0; i < textures.length; i++) {
  13030. var texture = textures[i];
  13031. for (var j = 0; j < attachments.length; j++) {
  13032. attachments[j] = gl.NONE;
  13033. }
  13034. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13035. gl.readBuffer(attachments[i]);
  13036. gl.drawBuffers(attachments);
  13037. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13038. }
  13039. for (var i = 0; i < attachments.length; i++) {
  13040. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13041. }
  13042. gl.drawBuffers(attachments);
  13043. }
  13044. for (var i = 0; i < textures.length; i++) {
  13045. var texture = textures[i];
  13046. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13047. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13048. gl.generateMipmap(gl.TEXTURE_2D);
  13049. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13050. }
  13051. }
  13052. if (onBeforeUnbind) {
  13053. if (textures[0]._MSAAFramebuffer) {
  13054. // Bind the correct framebuffer
  13055. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13056. }
  13057. onBeforeUnbind();
  13058. }
  13059. this.bindUnboundFramebuffer(null);
  13060. };
  13061. /**
  13062. * Force the mipmap generation for the given render target texture
  13063. * @param texture defines the render target texture to use
  13064. */
  13065. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13066. if (texture.generateMipMaps) {
  13067. var gl = this._gl;
  13068. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13069. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13070. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13071. }
  13072. };
  13073. /**
  13074. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13075. */
  13076. Engine.prototype.flushFramebuffer = function () {
  13077. this._gl.flush();
  13078. };
  13079. /**
  13080. * Unbind the current render target and bind the default framebuffer
  13081. */
  13082. Engine.prototype.restoreDefaultFramebuffer = function () {
  13083. if (this._currentRenderTarget) {
  13084. this.unBindFramebuffer(this._currentRenderTarget);
  13085. }
  13086. else {
  13087. this.bindUnboundFramebuffer(null);
  13088. }
  13089. if (this._cachedViewport) {
  13090. this.setViewport(this._cachedViewport);
  13091. }
  13092. this.wipeCaches();
  13093. };
  13094. // UBOs
  13095. /**
  13096. * Create an uniform buffer
  13097. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13098. * @param elements defines the content of the uniform buffer
  13099. * @returns the webGL uniform buffer
  13100. */
  13101. Engine.prototype.createUniformBuffer = function (elements) {
  13102. var ubo = this._gl.createBuffer();
  13103. if (!ubo) {
  13104. throw new Error("Unable to create uniform buffer");
  13105. }
  13106. this.bindUniformBuffer(ubo);
  13107. if (elements instanceof Float32Array) {
  13108. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13109. }
  13110. else {
  13111. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13112. }
  13113. this.bindUniformBuffer(null);
  13114. ubo.references = 1;
  13115. return ubo;
  13116. };
  13117. /**
  13118. * Create a dynamic uniform buffer
  13119. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13120. * @param elements defines the content of the uniform buffer
  13121. * @returns the webGL uniform buffer
  13122. */
  13123. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13124. var ubo = this._gl.createBuffer();
  13125. if (!ubo) {
  13126. throw new Error("Unable to create dynamic uniform buffer");
  13127. }
  13128. this.bindUniformBuffer(ubo);
  13129. if (elements instanceof Float32Array) {
  13130. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13131. }
  13132. else {
  13133. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13134. }
  13135. this.bindUniformBuffer(null);
  13136. ubo.references = 1;
  13137. return ubo;
  13138. };
  13139. /**
  13140. * Update an existing uniform buffer
  13141. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13142. * @param uniformBuffer defines the target uniform buffer
  13143. * @param elements defines the content to update
  13144. * @param offset defines the offset in the uniform buffer where update should start
  13145. * @param count defines the size of the data to update
  13146. */
  13147. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13148. this.bindUniformBuffer(uniformBuffer);
  13149. if (offset === undefined) {
  13150. offset = 0;
  13151. }
  13152. if (count === undefined) {
  13153. if (elements instanceof Float32Array) {
  13154. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13155. }
  13156. else {
  13157. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13158. }
  13159. }
  13160. else {
  13161. if (elements instanceof Float32Array) {
  13162. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13163. }
  13164. else {
  13165. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13166. }
  13167. }
  13168. this.bindUniformBuffer(null);
  13169. };
  13170. // VBOs
  13171. Engine.prototype._resetVertexBufferBinding = function () {
  13172. this.bindArrayBuffer(null);
  13173. this._cachedVertexBuffers = null;
  13174. };
  13175. /**
  13176. * Creates a vertex buffer
  13177. * @param data the data for the vertex buffer
  13178. * @returns the new WebGL static buffer
  13179. */
  13180. Engine.prototype.createVertexBuffer = function (data) {
  13181. var vbo = this._gl.createBuffer();
  13182. if (!vbo) {
  13183. throw new Error("Unable to create vertex buffer");
  13184. }
  13185. this.bindArrayBuffer(vbo);
  13186. if (data instanceof Array) {
  13187. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13188. }
  13189. else {
  13190. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13191. }
  13192. this._resetVertexBufferBinding();
  13193. vbo.references = 1;
  13194. return vbo;
  13195. };
  13196. /**
  13197. * Creates a dynamic vertex buffer
  13198. * @param data the data for the dynamic vertex buffer
  13199. * @returns the new WebGL dynamic buffer
  13200. */
  13201. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13202. var vbo = this._gl.createBuffer();
  13203. if (!vbo) {
  13204. throw new Error("Unable to create dynamic vertex buffer");
  13205. }
  13206. this.bindArrayBuffer(vbo);
  13207. if (data instanceof Array) {
  13208. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13209. }
  13210. else {
  13211. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13212. }
  13213. this._resetVertexBufferBinding();
  13214. vbo.references = 1;
  13215. return vbo;
  13216. };
  13217. /**
  13218. * Update a dynamic index buffer
  13219. * @param indexBuffer defines the target index buffer
  13220. * @param indices defines the data to update
  13221. * @param offset defines the offset in the target index buffer where update should start
  13222. */
  13223. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13224. if (offset === void 0) { offset = 0; }
  13225. // Force cache update
  13226. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13227. this.bindIndexBuffer(indexBuffer);
  13228. var arrayBuffer;
  13229. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13230. arrayBuffer = indices;
  13231. }
  13232. else {
  13233. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13234. }
  13235. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13236. this._resetIndexBufferBinding();
  13237. };
  13238. /**
  13239. * Updates a dynamic vertex buffer.
  13240. * @param vertexBuffer the vertex buffer to update
  13241. * @param data the data used to update the vertex buffer
  13242. * @param byteOffset the byte offset of the data
  13243. * @param byteLength the byte length of the data
  13244. */
  13245. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13246. this.bindArrayBuffer(vertexBuffer);
  13247. if (byteOffset === undefined) {
  13248. byteOffset = 0;
  13249. }
  13250. if (byteLength === undefined) {
  13251. if (data instanceof Array) {
  13252. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13253. }
  13254. else {
  13255. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13256. }
  13257. }
  13258. else {
  13259. if (data instanceof Array) {
  13260. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13261. }
  13262. else {
  13263. if (data instanceof ArrayBuffer) {
  13264. data = new Uint8Array(data, byteOffset, byteLength);
  13265. }
  13266. else {
  13267. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13268. }
  13269. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13270. }
  13271. }
  13272. this._resetVertexBufferBinding();
  13273. };
  13274. Engine.prototype._resetIndexBufferBinding = function () {
  13275. this.bindIndexBuffer(null);
  13276. this._cachedIndexBuffer = null;
  13277. };
  13278. /**
  13279. * Creates a new index buffer
  13280. * @param indices defines the content of the index buffer
  13281. * @param updatable defines if the index buffer must be updatable
  13282. * @returns a new webGL buffer
  13283. */
  13284. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13285. var vbo = this._gl.createBuffer();
  13286. if (!vbo) {
  13287. throw new Error("Unable to create index buffer");
  13288. }
  13289. this.bindIndexBuffer(vbo);
  13290. // Check for 32 bits indices
  13291. var arrayBuffer;
  13292. var need32Bits = false;
  13293. if (indices instanceof Uint16Array) {
  13294. arrayBuffer = indices;
  13295. }
  13296. else {
  13297. //check 32 bit support
  13298. if (this._caps.uintIndices) {
  13299. if (indices instanceof Uint32Array) {
  13300. arrayBuffer = indices;
  13301. need32Bits = true;
  13302. }
  13303. else {
  13304. //number[] or Int32Array, check if 32 bit is necessary
  13305. for (var index = 0; index < indices.length; index++) {
  13306. if (indices[index] > 65535) {
  13307. need32Bits = true;
  13308. break;
  13309. }
  13310. }
  13311. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13312. }
  13313. }
  13314. else {
  13315. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13316. arrayBuffer = new Uint16Array(indices);
  13317. }
  13318. }
  13319. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13320. this._resetIndexBufferBinding();
  13321. vbo.references = 1;
  13322. vbo.is32Bits = need32Bits;
  13323. return vbo;
  13324. };
  13325. /**
  13326. * Bind a webGL buffer to the webGL context
  13327. * @param buffer defines the buffer to bind
  13328. */
  13329. Engine.prototype.bindArrayBuffer = function (buffer) {
  13330. if (!this._vaoRecordInProgress) {
  13331. this._unbindVertexArrayObject();
  13332. }
  13333. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13334. };
  13335. /**
  13336. * Bind an uniform buffer to the current webGL context
  13337. * @param buffer defines the buffer to bind
  13338. */
  13339. Engine.prototype.bindUniformBuffer = function (buffer) {
  13340. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13341. };
  13342. /**
  13343. * Bind a buffer to the current webGL context at a given location
  13344. * @param buffer defines the buffer to bind
  13345. * @param location defines the index where to bind the buffer
  13346. */
  13347. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13348. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13349. };
  13350. /**
  13351. * Bind a specific block at a given index in a specific shader program
  13352. * @param shaderProgram defines the shader program
  13353. * @param blockName defines the block name
  13354. * @param index defines the index where to bind the block
  13355. */
  13356. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13357. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13358. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13359. };
  13360. ;
  13361. Engine.prototype.bindIndexBuffer = function (buffer) {
  13362. if (!this._vaoRecordInProgress) {
  13363. this._unbindVertexArrayObject();
  13364. }
  13365. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13366. };
  13367. Engine.prototype.bindBuffer = function (buffer, target) {
  13368. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13369. this._gl.bindBuffer(target, buffer);
  13370. this._currentBoundBuffer[target] = buffer;
  13371. }
  13372. };
  13373. /**
  13374. * update the bound buffer with the given data
  13375. * @param data defines the data to update
  13376. */
  13377. Engine.prototype.updateArrayBuffer = function (data) {
  13378. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13379. };
  13380. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13381. var pointer = this._currentBufferPointers[indx];
  13382. var changed = false;
  13383. if (!pointer.active) {
  13384. changed = true;
  13385. pointer.active = true;
  13386. pointer.index = indx;
  13387. pointer.size = size;
  13388. pointer.type = type;
  13389. pointer.normalized = normalized;
  13390. pointer.stride = stride;
  13391. pointer.offset = offset;
  13392. pointer.buffer = buffer;
  13393. }
  13394. else {
  13395. if (pointer.buffer !== buffer) {
  13396. pointer.buffer = buffer;
  13397. changed = true;
  13398. }
  13399. if (pointer.size !== size) {
  13400. pointer.size = size;
  13401. changed = true;
  13402. }
  13403. if (pointer.type !== type) {
  13404. pointer.type = type;
  13405. changed = true;
  13406. }
  13407. if (pointer.normalized !== normalized) {
  13408. pointer.normalized = normalized;
  13409. changed = true;
  13410. }
  13411. if (pointer.stride !== stride) {
  13412. pointer.stride = stride;
  13413. changed = true;
  13414. }
  13415. if (pointer.offset !== offset) {
  13416. pointer.offset = offset;
  13417. changed = true;
  13418. }
  13419. }
  13420. if (changed || this._vaoRecordInProgress) {
  13421. this.bindArrayBuffer(buffer);
  13422. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13423. }
  13424. };
  13425. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13426. if (indexBuffer == null) {
  13427. return;
  13428. }
  13429. if (this._cachedIndexBuffer !== indexBuffer) {
  13430. this._cachedIndexBuffer = indexBuffer;
  13431. this.bindIndexBuffer(indexBuffer);
  13432. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13433. }
  13434. };
  13435. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13436. var attributes = effect.getAttributesNames();
  13437. if (!this._vaoRecordInProgress) {
  13438. this._unbindVertexArrayObject();
  13439. }
  13440. this.unbindAllAttributes();
  13441. for (var index = 0; index < attributes.length; index++) {
  13442. var order = effect.getAttributeLocation(index);
  13443. if (order >= 0) {
  13444. var vertexBuffer = vertexBuffers[attributes[index]];
  13445. if (!vertexBuffer) {
  13446. continue;
  13447. }
  13448. this._gl.enableVertexAttribArray(order);
  13449. if (!this._vaoRecordInProgress) {
  13450. this._vertexAttribArraysEnabled[order] = true;
  13451. }
  13452. var buffer = vertexBuffer.getBuffer();
  13453. if (buffer) {
  13454. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13455. if (vertexBuffer.getIsInstanced()) {
  13456. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13457. if (!this._vaoRecordInProgress) {
  13458. this._currentInstanceLocations.push(order);
  13459. this._currentInstanceBuffers.push(buffer);
  13460. }
  13461. }
  13462. }
  13463. }
  13464. }
  13465. };
  13466. /**
  13467. * Records a vertex array object
  13468. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13469. * @param vertexBuffers defines the list of vertex buffers to store
  13470. * @param indexBuffer defines the index buffer to store
  13471. * @param effect defines the effect to store
  13472. * @returns the new vertex array object
  13473. */
  13474. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13475. var vao = this._gl.createVertexArray();
  13476. this._vaoRecordInProgress = true;
  13477. this._gl.bindVertexArray(vao);
  13478. this._mustWipeVertexAttributes = true;
  13479. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13480. this.bindIndexBuffer(indexBuffer);
  13481. this._vaoRecordInProgress = false;
  13482. this._gl.bindVertexArray(null);
  13483. return vao;
  13484. };
  13485. /**
  13486. * Bind a specific vertex array object
  13487. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13488. * @param vertexArrayObject defines the vertex array object to bind
  13489. * @param indexBuffer defines the index buffer to bind
  13490. */
  13491. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13492. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13493. this._cachedVertexArrayObject = vertexArrayObject;
  13494. this._gl.bindVertexArray(vertexArrayObject);
  13495. this._cachedVertexBuffers = null;
  13496. this._cachedIndexBuffer = null;
  13497. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13498. this._mustWipeVertexAttributes = true;
  13499. }
  13500. };
  13501. /**
  13502. * Bind webGl buffers directly to the webGL context
  13503. * @param vertexBuffer defines the vertex buffer to bind
  13504. * @param indexBuffer defines the index buffer to bind
  13505. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13506. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13507. * @param effect defines the effect associated with the vertex buffer
  13508. */
  13509. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13510. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13511. this._cachedVertexBuffers = vertexBuffer;
  13512. this._cachedEffectForVertexBuffers = effect;
  13513. var attributesCount = effect.getAttributesCount();
  13514. this._unbindVertexArrayObject();
  13515. this.unbindAllAttributes();
  13516. var offset = 0;
  13517. for (var index = 0; index < attributesCount; index++) {
  13518. if (index < vertexDeclaration.length) {
  13519. var order = effect.getAttributeLocation(index);
  13520. if (order >= 0) {
  13521. this._gl.enableVertexAttribArray(order);
  13522. this._vertexAttribArraysEnabled[order] = true;
  13523. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13524. }
  13525. offset += vertexDeclaration[index] * 4;
  13526. }
  13527. }
  13528. }
  13529. this._bindIndexBufferWithCache(indexBuffer);
  13530. };
  13531. Engine.prototype._unbindVertexArrayObject = function () {
  13532. if (!this._cachedVertexArrayObject) {
  13533. return;
  13534. }
  13535. this._cachedVertexArrayObject = null;
  13536. this._gl.bindVertexArray(null);
  13537. };
  13538. /**
  13539. * Bind a list of vertex buffers to the webGL context
  13540. * @param vertexBuffers defines the list of vertex buffers to bind
  13541. * @param indexBuffer defines the index buffer to bind
  13542. * @param effect defines the effect associated with the vertex buffers
  13543. */
  13544. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13545. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13546. this._cachedVertexBuffers = vertexBuffers;
  13547. this._cachedEffectForVertexBuffers = effect;
  13548. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13549. }
  13550. this._bindIndexBufferWithCache(indexBuffer);
  13551. };
  13552. /**
  13553. * Unbind all instance attributes
  13554. */
  13555. Engine.prototype.unbindInstanceAttributes = function () {
  13556. var boundBuffer;
  13557. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13558. var instancesBuffer = this._currentInstanceBuffers[i];
  13559. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13560. boundBuffer = instancesBuffer;
  13561. this.bindArrayBuffer(instancesBuffer);
  13562. }
  13563. var offsetLocation = this._currentInstanceLocations[i];
  13564. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13565. }
  13566. this._currentInstanceBuffers.length = 0;
  13567. this._currentInstanceLocations.length = 0;
  13568. };
  13569. /**
  13570. * Release and free the memory of a vertex array object
  13571. * @param vao defines the vertex array object to delete
  13572. */
  13573. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13574. this._gl.deleteVertexArray(vao);
  13575. };
  13576. /** @hidden */
  13577. Engine.prototype._releaseBuffer = function (buffer) {
  13578. buffer.references--;
  13579. if (buffer.references === 0) {
  13580. this._gl.deleteBuffer(buffer);
  13581. return true;
  13582. }
  13583. return false;
  13584. };
  13585. /**
  13586. * Creates a webGL buffer to use with instanciation
  13587. * @param capacity defines the size of the buffer
  13588. * @returns the webGL buffer
  13589. */
  13590. Engine.prototype.createInstancesBuffer = function (capacity) {
  13591. var buffer = this._gl.createBuffer();
  13592. if (!buffer) {
  13593. throw new Error("Unable to create instance buffer");
  13594. }
  13595. buffer.capacity = capacity;
  13596. this.bindArrayBuffer(buffer);
  13597. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13598. return buffer;
  13599. };
  13600. /**
  13601. * Delete a webGL buffer used with instanciation
  13602. * @param buffer defines the webGL buffer to delete
  13603. */
  13604. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13605. this._gl.deleteBuffer(buffer);
  13606. };
  13607. /**
  13608. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13609. * @param instancesBuffer defines the webGL buffer to update and bind
  13610. * @param data defines the data to store in the buffer
  13611. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13612. */
  13613. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13614. this.bindArrayBuffer(instancesBuffer);
  13615. if (data) {
  13616. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13617. }
  13618. if (offsetLocations[0].index !== undefined) {
  13619. var stride = 0;
  13620. for (var i = 0; i < offsetLocations.length; i++) {
  13621. var ai = offsetLocations[i];
  13622. stride += ai.attributeSize * 4;
  13623. }
  13624. for (var i = 0; i < offsetLocations.length; i++) {
  13625. var ai = offsetLocations[i];
  13626. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13627. this._gl.enableVertexAttribArray(ai.index);
  13628. this._vertexAttribArraysEnabled[ai.index] = true;
  13629. }
  13630. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13631. this._gl.vertexAttribDivisor(ai.index, 1);
  13632. this._currentInstanceLocations.push(ai.index);
  13633. this._currentInstanceBuffers.push(instancesBuffer);
  13634. }
  13635. }
  13636. else {
  13637. for (var index = 0; index < 4; index++) {
  13638. var offsetLocation = offsetLocations[index];
  13639. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13640. this._gl.enableVertexAttribArray(offsetLocation);
  13641. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13642. }
  13643. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13644. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13645. this._currentInstanceLocations.push(offsetLocation);
  13646. this._currentInstanceBuffers.push(instancesBuffer);
  13647. }
  13648. }
  13649. };
  13650. /**
  13651. * Apply all cached states (depth, culling, stencil and alpha)
  13652. */
  13653. Engine.prototype.applyStates = function () {
  13654. this._depthCullingState.apply(this._gl);
  13655. this._stencilState.apply(this._gl);
  13656. this._alphaState.apply(this._gl);
  13657. };
  13658. /**
  13659. * Send a draw order
  13660. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13661. * @param indexStart defines the starting index
  13662. * @param indexCount defines the number of index to draw
  13663. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13664. */
  13665. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13666. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13667. };
  13668. /**
  13669. * Draw a list of points
  13670. * @param verticesStart defines the index of first vertex to draw
  13671. * @param verticesCount defines the count of vertices to draw
  13672. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13673. */
  13674. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13675. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13676. };
  13677. /**
  13678. * Draw a list of unindexed primitives
  13679. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13680. * @param verticesStart defines the index of first vertex to draw
  13681. * @param verticesCount defines the count of vertices to draw
  13682. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13683. */
  13684. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13685. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13686. };
  13687. /**
  13688. * Draw a list of indexed primitives
  13689. * @param fillMode defines the primitive to use
  13690. * @param indexStart defines the starting index
  13691. * @param indexCount defines the number of index to draw
  13692. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13693. */
  13694. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13695. // Apply states
  13696. this.applyStates();
  13697. this._drawCalls.addCount(1, false);
  13698. // Render
  13699. var drawMode = this._drawMode(fillMode);
  13700. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13701. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13702. if (instancesCount) {
  13703. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13704. }
  13705. else {
  13706. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13707. }
  13708. };
  13709. /**
  13710. * Draw a list of unindexed primitives
  13711. * @param fillMode defines the primitive to use
  13712. * @param verticesStart defines the index of first vertex to draw
  13713. * @param verticesCount defines the count of vertices to draw
  13714. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13715. */
  13716. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13717. // Apply states
  13718. this.applyStates();
  13719. this._drawCalls.addCount(1, false);
  13720. var drawMode = this._drawMode(fillMode);
  13721. if (instancesCount) {
  13722. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13723. }
  13724. else {
  13725. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13726. }
  13727. };
  13728. Engine.prototype._drawMode = function (fillMode) {
  13729. switch (fillMode) {
  13730. // Triangle views
  13731. case BABYLON.Material.TriangleFillMode:
  13732. return this._gl.TRIANGLES;
  13733. case BABYLON.Material.PointFillMode:
  13734. return this._gl.POINTS;
  13735. case BABYLON.Material.WireFrameFillMode:
  13736. return this._gl.LINES;
  13737. // Draw modes
  13738. case BABYLON.Material.PointListDrawMode:
  13739. return this._gl.POINTS;
  13740. case BABYLON.Material.LineListDrawMode:
  13741. return this._gl.LINES;
  13742. case BABYLON.Material.LineLoopDrawMode:
  13743. return this._gl.LINE_LOOP;
  13744. case BABYLON.Material.LineStripDrawMode:
  13745. return this._gl.LINE_STRIP;
  13746. case BABYLON.Material.TriangleStripDrawMode:
  13747. return this._gl.TRIANGLE_STRIP;
  13748. case BABYLON.Material.TriangleFanDrawMode:
  13749. return this._gl.TRIANGLE_FAN;
  13750. default:
  13751. return this._gl.TRIANGLES;
  13752. }
  13753. };
  13754. // Shaders
  13755. /** @hidden */
  13756. Engine.prototype._releaseEffect = function (effect) {
  13757. if (this._compiledEffects[effect._key]) {
  13758. delete this._compiledEffects[effect._key];
  13759. this._deleteProgram(effect.getProgram());
  13760. }
  13761. };
  13762. /** @hidden */
  13763. Engine.prototype._deleteProgram = function (program) {
  13764. if (program) {
  13765. program.__SPECTOR_rebuildProgram = null;
  13766. if (program.transformFeedback) {
  13767. this.deleteTransformFeedback(program.transformFeedback);
  13768. program.transformFeedback = null;
  13769. }
  13770. this._gl.deleteProgram(program);
  13771. }
  13772. };
  13773. /**
  13774. * Create a new effect (used to store vertex/fragment shaders)
  13775. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13776. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13777. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13778. * @param samplers defines an array of string used to represent textures
  13779. * @param defines defines the string containing the defines to use to compile the shaders
  13780. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13781. * @param onCompiled defines a function to call when the effect creation is successful
  13782. * @param onError defines a function to call when the effect creation has failed
  13783. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13784. * @returns the new Effect
  13785. */
  13786. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13787. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13788. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13789. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13790. if (this._compiledEffects[name]) {
  13791. var compiledEffect = this._compiledEffects[name];
  13792. if (onCompiled && compiledEffect.isReady()) {
  13793. onCompiled(compiledEffect);
  13794. }
  13795. return compiledEffect;
  13796. }
  13797. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13798. effect._key = name;
  13799. this._compiledEffects[name] = effect;
  13800. return effect;
  13801. };
  13802. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13803. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13804. };
  13805. ;
  13806. Engine.prototype._compileRawShader = function (source, type) {
  13807. var gl = this._gl;
  13808. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13809. gl.shaderSource(shader, source);
  13810. gl.compileShader(shader);
  13811. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13812. var log = gl.getShaderInfoLog(shader);
  13813. if (log) {
  13814. throw new Error(log);
  13815. }
  13816. }
  13817. if (!shader) {
  13818. throw new Error("Something went wrong while compile the shader.");
  13819. }
  13820. return shader;
  13821. };
  13822. ;
  13823. /**
  13824. * Directly creates a webGL program
  13825. * @param vertexCode defines the vertex shader code to use
  13826. * @param fragmentCode defines the fragment shader code to use
  13827. * @param context defines the webGL context to use (if not set, the current one will be used)
  13828. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13829. * @returns the new webGL program
  13830. */
  13831. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13832. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13833. context = context || this._gl;
  13834. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13835. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13836. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13837. };
  13838. /**
  13839. * Creates a webGL program
  13840. * @param vertexCode defines the vertex shader code to use
  13841. * @param fragmentCode defines the fragment shader code to use
  13842. * @param defines defines the string containing the defines to use to compile the shaders
  13843. * @param context defines the webGL context to use (if not set, the current one will be used)
  13844. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13845. * @returns the new webGL program
  13846. */
  13847. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13848. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13849. context = context || this._gl;
  13850. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13851. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13852. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13853. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13854. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13855. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13856. return program;
  13857. };
  13858. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13859. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13860. var shaderProgram = context.createProgram();
  13861. if (!shaderProgram) {
  13862. throw new Error("Unable to create program");
  13863. }
  13864. context.attachShader(shaderProgram, vertexShader);
  13865. context.attachShader(shaderProgram, fragmentShader);
  13866. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13867. var transformFeedback = this.createTransformFeedback();
  13868. this.bindTransformFeedback(transformFeedback);
  13869. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13870. shaderProgram.transformFeedback = transformFeedback;
  13871. }
  13872. context.linkProgram(shaderProgram);
  13873. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13874. this.bindTransformFeedback(null);
  13875. }
  13876. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13877. if (!linked) {
  13878. var error = context.getProgramInfoLog(shaderProgram);
  13879. if (error) {
  13880. throw new Error(error);
  13881. }
  13882. }
  13883. if (this.validateShaderPrograms) {
  13884. context.validateProgram(shaderProgram);
  13885. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13886. if (!validated) {
  13887. var error = context.getProgramInfoLog(shaderProgram);
  13888. if (error) {
  13889. throw new Error(error);
  13890. }
  13891. }
  13892. }
  13893. context.deleteShader(vertexShader);
  13894. context.deleteShader(fragmentShader);
  13895. return shaderProgram;
  13896. };
  13897. /**
  13898. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13899. * @param shaderProgram defines the webGL program to use
  13900. * @param uniformsNames defines the list of uniform names
  13901. * @returns an array of webGL uniform locations
  13902. */
  13903. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13904. var results = new Array();
  13905. for (var index = 0; index < uniformsNames.length; index++) {
  13906. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13907. }
  13908. return results;
  13909. };
  13910. /**
  13911. * Gets the lsit of active attributes for a given webGL program
  13912. * @param shaderProgram defines the webGL program to use
  13913. * @param attributesNames defines the list of attribute names to get
  13914. * @returns an array of indices indicating the offset of each attribute
  13915. */
  13916. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13917. var results = [];
  13918. for (var index = 0; index < attributesNames.length; index++) {
  13919. try {
  13920. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13921. }
  13922. catch (e) {
  13923. results.push(-1);
  13924. }
  13925. }
  13926. return results;
  13927. };
  13928. /**
  13929. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13930. * @param effect defines the effect to activate
  13931. */
  13932. Engine.prototype.enableEffect = function (effect) {
  13933. if (!effect || effect === this._currentEffect) {
  13934. return;
  13935. }
  13936. // Use program
  13937. this.bindSamplers(effect);
  13938. this._currentEffect = effect;
  13939. if (effect.onBind) {
  13940. effect.onBind(effect);
  13941. }
  13942. if (effect._onBindObservable) {
  13943. effect._onBindObservable.notifyObservers(effect);
  13944. }
  13945. };
  13946. /**
  13947. * Set the value of an uniform to an array of int32
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param array defines the array of int32 to store
  13950. */
  13951. Engine.prototype.setIntArray = function (uniform, array) {
  13952. if (!uniform)
  13953. return;
  13954. this._gl.uniform1iv(uniform, array);
  13955. };
  13956. /**
  13957. * Set the value of an uniform to an array of int32 (stored as vec2)
  13958. * @param uniform defines the webGL uniform location where to store the value
  13959. * @param array defines the array of int32 to store
  13960. */
  13961. Engine.prototype.setIntArray2 = function (uniform, array) {
  13962. if (!uniform || array.length % 2 !== 0)
  13963. return;
  13964. this._gl.uniform2iv(uniform, array);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to an array of int32 (stored as vec3)
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param array defines the array of int32 to store
  13970. */
  13971. Engine.prototype.setIntArray3 = function (uniform, array) {
  13972. if (!uniform || array.length % 3 !== 0)
  13973. return;
  13974. this._gl.uniform3iv(uniform, array);
  13975. };
  13976. /**
  13977. * Set the value of an uniform to an array of int32 (stored as vec4)
  13978. * @param uniform defines the webGL uniform location where to store the value
  13979. * @param array defines the array of int32 to store
  13980. */
  13981. Engine.prototype.setIntArray4 = function (uniform, array) {
  13982. if (!uniform || array.length % 4 !== 0)
  13983. return;
  13984. this._gl.uniform4iv(uniform, array);
  13985. };
  13986. /**
  13987. * Set the value of an uniform to an array of float32
  13988. * @param uniform defines the webGL uniform location where to store the value
  13989. * @param array defines the array of float32 to store
  13990. */
  13991. Engine.prototype.setFloatArray = function (uniform, array) {
  13992. if (!uniform)
  13993. return;
  13994. this._gl.uniform1fv(uniform, array);
  13995. };
  13996. /**
  13997. * Set the value of an uniform to an array of float32 (stored as vec2)
  13998. * @param uniform defines the webGL uniform location where to store the value
  13999. * @param array defines the array of float32 to store
  14000. */
  14001. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14002. if (!uniform || array.length % 2 !== 0)
  14003. return;
  14004. this._gl.uniform2fv(uniform, array);
  14005. };
  14006. /**
  14007. * Set the value of an uniform to an array of float32 (stored as vec3)
  14008. * @param uniform defines the webGL uniform location where to store the value
  14009. * @param array defines the array of float32 to store
  14010. */
  14011. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14012. if (!uniform || array.length % 3 !== 0)
  14013. return;
  14014. this._gl.uniform3fv(uniform, array);
  14015. };
  14016. /**
  14017. * Set the value of an uniform to an array of float32 (stored as vec4)
  14018. * @param uniform defines the webGL uniform location where to store the value
  14019. * @param array defines the array of float32 to store
  14020. */
  14021. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14022. if (!uniform || array.length % 4 !== 0)
  14023. return;
  14024. this._gl.uniform4fv(uniform, array);
  14025. };
  14026. /**
  14027. * Set the value of an uniform to an array of number
  14028. * @param uniform defines the webGL uniform location where to store the value
  14029. * @param array defines the array of number to store
  14030. */
  14031. Engine.prototype.setArray = function (uniform, array) {
  14032. if (!uniform)
  14033. return;
  14034. this._gl.uniform1fv(uniform, array);
  14035. };
  14036. /**
  14037. * Set the value of an uniform to an array of number (stored as vec2)
  14038. * @param uniform defines the webGL uniform location where to store the value
  14039. * @param array defines the array of number to store
  14040. */
  14041. Engine.prototype.setArray2 = function (uniform, array) {
  14042. if (!uniform || array.length % 2 !== 0)
  14043. return;
  14044. this._gl.uniform2fv(uniform, array);
  14045. };
  14046. /**
  14047. * Set the value of an uniform to an array of number (stored as vec3)
  14048. * @param uniform defines the webGL uniform location where to store the value
  14049. * @param array defines the array of number to store
  14050. */
  14051. Engine.prototype.setArray3 = function (uniform, array) {
  14052. if (!uniform || array.length % 3 !== 0)
  14053. return;
  14054. this._gl.uniform3fv(uniform, array);
  14055. };
  14056. /**
  14057. * Set the value of an uniform to an array of number (stored as vec4)
  14058. * @param uniform defines the webGL uniform location where to store the value
  14059. * @param array defines the array of number to store
  14060. */
  14061. Engine.prototype.setArray4 = function (uniform, array) {
  14062. if (!uniform || array.length % 4 !== 0)
  14063. return;
  14064. this._gl.uniform4fv(uniform, array);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to an array of float32 (stored as matrices)
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param matrices defines the array of float32 to store
  14070. */
  14071. Engine.prototype.setMatrices = function (uniform, matrices) {
  14072. if (!uniform)
  14073. return;
  14074. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to a matrix
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param matrix defines the matrix to store
  14080. */
  14081. Engine.prototype.setMatrix = function (uniform, matrix) {
  14082. if (!uniform)
  14083. return;
  14084. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14085. };
  14086. /**
  14087. * Set the value of an uniform to a matrix (3x3)
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14090. */
  14091. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14092. if (!uniform)
  14093. return;
  14094. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to a matrix (2x2)
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14100. */
  14101. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14102. if (!uniform)
  14103. return;
  14104. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14105. };
  14106. /**
  14107. * Set the value of an uniform to a number (int)
  14108. * @param uniform defines the webGL uniform location where to store the value
  14109. * @param value defines the int number to store
  14110. */
  14111. Engine.prototype.setInt = function (uniform, value) {
  14112. if (!uniform)
  14113. return;
  14114. this._gl.uniform1i(uniform, value);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to a number (float)
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param value defines the float number to store
  14120. */
  14121. Engine.prototype.setFloat = function (uniform, value) {
  14122. if (!uniform)
  14123. return;
  14124. this._gl.uniform1f(uniform, value);
  14125. };
  14126. /**
  14127. * Set the value of an uniform to a vec2
  14128. * @param uniform defines the webGL uniform location where to store the value
  14129. * @param x defines the 1st component of the value
  14130. * @param y defines the 2nd component of the value
  14131. */
  14132. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14133. if (!uniform)
  14134. return;
  14135. this._gl.uniform2f(uniform, x, y);
  14136. };
  14137. /**
  14138. * Set the value of an uniform to a vec3
  14139. * @param uniform defines the webGL uniform location where to store the value
  14140. * @param x defines the 1st component of the value
  14141. * @param y defines the 2nd component of the value
  14142. * @param z defines the 3rd component of the value
  14143. */
  14144. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniform3f(uniform, x, y, z);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a boolean
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param bool defines the boolean to store
  14153. */
  14154. Engine.prototype.setBool = function (uniform, bool) {
  14155. if (!uniform)
  14156. return;
  14157. this._gl.uniform1i(uniform, bool);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to a vec4
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param x defines the 1st component of the value
  14163. * @param y defines the 2nd component of the value
  14164. * @param z defines the 3rd component of the value
  14165. * @param w defines the 4th component of the value
  14166. */
  14167. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14168. if (!uniform)
  14169. return;
  14170. this._gl.uniform4f(uniform, x, y, z, w);
  14171. };
  14172. /**
  14173. * Set the value of an uniform to a Color3
  14174. * @param uniform defines the webGL uniform location where to store the value
  14175. * @param color3 defines the color to store
  14176. */
  14177. Engine.prototype.setColor3 = function (uniform, color3) {
  14178. if (!uniform)
  14179. return;
  14180. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14181. };
  14182. /**
  14183. * Set the value of an uniform to a Color3 and an alpha value
  14184. * @param uniform defines the webGL uniform location where to store the value
  14185. * @param color3 defines the color to store
  14186. * @param alpha defines the alpha component to store
  14187. */
  14188. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14189. if (!uniform)
  14190. return;
  14191. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14192. };
  14193. /**
  14194. * Sets a Color4 on a uniform variable
  14195. * @param uniform defines the uniform location
  14196. * @param color4 defines the value to be set
  14197. */
  14198. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14199. if (!uniform)
  14200. return;
  14201. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14202. };
  14203. // States
  14204. /**
  14205. * Set various states to the webGL context
  14206. * @param culling defines backface culling state
  14207. * @param zOffset defines the value to apply to zOffset (0 by default)
  14208. * @param force defines if states must be applied even if cache is up to date
  14209. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14210. */
  14211. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14212. if (zOffset === void 0) { zOffset = 0; }
  14213. if (reverseSide === void 0) { reverseSide = false; }
  14214. // Culling
  14215. if (this._depthCullingState.cull !== culling || force) {
  14216. this._depthCullingState.cull = culling;
  14217. }
  14218. // Cull face
  14219. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14220. if (this._depthCullingState.cullFace !== cullFace || force) {
  14221. this._depthCullingState.cullFace = cullFace;
  14222. }
  14223. // Z offset
  14224. this.setZOffset(zOffset);
  14225. // Front face
  14226. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14227. if (this._depthCullingState.frontFace !== frontFace || force) {
  14228. this._depthCullingState.frontFace = frontFace;
  14229. }
  14230. };
  14231. /**
  14232. * Set the z offset to apply to current rendering
  14233. * @param value defines the offset to apply
  14234. */
  14235. Engine.prototype.setZOffset = function (value) {
  14236. this._depthCullingState.zOffset = value;
  14237. };
  14238. /**
  14239. * Gets the current value of the zOffset
  14240. * @returns the current zOffset state
  14241. */
  14242. Engine.prototype.getZOffset = function () {
  14243. return this._depthCullingState.zOffset;
  14244. };
  14245. /**
  14246. * Enable or disable depth buffering
  14247. * @param enable defines the state to set
  14248. */
  14249. Engine.prototype.setDepthBuffer = function (enable) {
  14250. this._depthCullingState.depthTest = enable;
  14251. };
  14252. /**
  14253. * Gets a boolean indicating if depth writing is enabled
  14254. * @returns the current depth writing state
  14255. */
  14256. Engine.prototype.getDepthWrite = function () {
  14257. return this._depthCullingState.depthMask;
  14258. };
  14259. /**
  14260. * Enable or disable depth writing
  14261. * @param enable defines the state to set
  14262. */
  14263. Engine.prototype.setDepthWrite = function (enable) {
  14264. this._depthCullingState.depthMask = enable;
  14265. };
  14266. /**
  14267. * Enable or disable color writing
  14268. * @param enable defines the state to set
  14269. */
  14270. Engine.prototype.setColorWrite = function (enable) {
  14271. this._gl.colorMask(enable, enable, enable, enable);
  14272. this._colorWrite = enable;
  14273. };
  14274. /**
  14275. * Gets a boolean indicating if color writing is enabled
  14276. * @returns the current color writing state
  14277. */
  14278. Engine.prototype.getColorWrite = function () {
  14279. return this._colorWrite;
  14280. };
  14281. /**
  14282. * Sets alpha constants used by some alpha blending modes
  14283. * @param r defines the red component
  14284. * @param g defines the green component
  14285. * @param b defines the blue component
  14286. * @param a defines the alpha component
  14287. */
  14288. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14289. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14290. };
  14291. /**
  14292. * Sets the current alpha mode
  14293. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14294. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14295. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14296. */
  14297. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14298. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14299. if (this._alphaMode === mode) {
  14300. return;
  14301. }
  14302. switch (mode) {
  14303. case Engine.ALPHA_DISABLE:
  14304. this._alphaState.alphaBlend = false;
  14305. break;
  14306. case Engine.ALPHA_PREMULTIPLIED:
  14307. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14308. this._alphaState.alphaBlend = true;
  14309. break;
  14310. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14311. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14312. this._alphaState.alphaBlend = true;
  14313. break;
  14314. case Engine.ALPHA_COMBINE:
  14315. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14316. this._alphaState.alphaBlend = true;
  14317. break;
  14318. case Engine.ALPHA_ONEONE:
  14319. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14320. this._alphaState.alphaBlend = true;
  14321. break;
  14322. case Engine.ALPHA_ADD:
  14323. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14324. this._alphaState.alphaBlend = true;
  14325. break;
  14326. case Engine.ALPHA_SUBTRACT:
  14327. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14328. this._alphaState.alphaBlend = true;
  14329. break;
  14330. case Engine.ALPHA_MULTIPLY:
  14331. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14332. this._alphaState.alphaBlend = true;
  14333. break;
  14334. case Engine.ALPHA_MAXIMIZED:
  14335. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14336. this._alphaState.alphaBlend = true;
  14337. break;
  14338. case Engine.ALPHA_INTERPOLATE:
  14339. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14340. this._alphaState.alphaBlend = true;
  14341. break;
  14342. case Engine.ALPHA_SCREENMODE:
  14343. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14344. this._alphaState.alphaBlend = true;
  14345. break;
  14346. }
  14347. if (!noDepthWriteChange) {
  14348. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14349. }
  14350. this._alphaMode = mode;
  14351. };
  14352. /**
  14353. * Gets the current alpha mode
  14354. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14355. * @returns the current alpha mode
  14356. */
  14357. Engine.prototype.getAlphaMode = function () {
  14358. return this._alphaMode;
  14359. };
  14360. // Textures
  14361. /**
  14362. * Clears the list of texture accessible through engine.
  14363. * This can help preventing texture load conflict due to name collision.
  14364. */
  14365. Engine.prototype.clearInternalTexturesCache = function () {
  14366. this._internalTexturesCache = [];
  14367. };
  14368. /**
  14369. * Force the entire cache to be cleared
  14370. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14371. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14372. */
  14373. Engine.prototype.wipeCaches = function (bruteForce) {
  14374. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14375. return;
  14376. }
  14377. this._currentEffect = null;
  14378. this._viewportCached.x = 0;
  14379. this._viewportCached.y = 0;
  14380. this._viewportCached.z = 0;
  14381. this._viewportCached.w = 0;
  14382. if (bruteForce) {
  14383. this.resetTextureCache();
  14384. this._currentProgram = null;
  14385. this._stencilState.reset();
  14386. this._depthCullingState.reset();
  14387. this.setDepthFunctionToLessOrEqual();
  14388. this._alphaState.reset();
  14389. this._unpackFlipYCached = null;
  14390. }
  14391. this._resetVertexBufferBinding();
  14392. this._cachedIndexBuffer = null;
  14393. this._cachedEffectForVertexBuffers = null;
  14394. this._unbindVertexArrayObject();
  14395. this.bindIndexBuffer(null);
  14396. };
  14397. /**
  14398. * Set the compressed texture format to use, based on the formats you have, and the formats
  14399. * supported by the hardware / browser.
  14400. *
  14401. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14402. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14403. * to API arguments needed to compressed textures. This puts the burden on the container
  14404. * generator to house the arcane code for determining these for current & future formats.
  14405. *
  14406. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14407. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14408. *
  14409. * Note: The result of this call is not taken into account when a texture is base64.
  14410. *
  14411. * @param formatsAvailable defines the list of those format families you have created
  14412. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14413. *
  14414. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14415. * @returns The extension selected.
  14416. */
  14417. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14418. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14419. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14420. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14421. return this._textureFormatInUse = this._texturesSupported[i];
  14422. }
  14423. }
  14424. }
  14425. // actively set format to nothing, to allow this to be called more than once
  14426. // and possibly fail the 2nd time
  14427. this._textureFormatInUse = null;
  14428. return null;
  14429. };
  14430. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14431. var gl = this._gl;
  14432. var magFilter = gl.NEAREST;
  14433. var minFilter = gl.NEAREST;
  14434. switch (samplingMode) {
  14435. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14436. magFilter = gl.LINEAR;
  14437. if (generateMipMaps) {
  14438. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14439. }
  14440. else {
  14441. minFilter = gl.LINEAR;
  14442. }
  14443. break;
  14444. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14445. magFilter = gl.LINEAR;
  14446. if (generateMipMaps) {
  14447. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14448. }
  14449. else {
  14450. minFilter = gl.LINEAR;
  14451. }
  14452. break;
  14453. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14454. magFilter = gl.NEAREST;
  14455. if (generateMipMaps) {
  14456. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14457. }
  14458. else {
  14459. minFilter = gl.NEAREST;
  14460. }
  14461. break;
  14462. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14463. magFilter = gl.NEAREST;
  14464. if (generateMipMaps) {
  14465. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14466. }
  14467. else {
  14468. minFilter = gl.NEAREST;
  14469. }
  14470. break;
  14471. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14472. magFilter = gl.NEAREST;
  14473. if (generateMipMaps) {
  14474. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14475. }
  14476. else {
  14477. minFilter = gl.LINEAR;
  14478. }
  14479. break;
  14480. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14481. magFilter = gl.NEAREST;
  14482. if (generateMipMaps) {
  14483. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14484. }
  14485. else {
  14486. minFilter = gl.LINEAR;
  14487. }
  14488. break;
  14489. case Engine.TEXTURE_NEAREST_LINEAR:
  14490. magFilter = gl.NEAREST;
  14491. minFilter = gl.LINEAR;
  14492. break;
  14493. case Engine.TEXTURE_NEAREST_NEAREST:
  14494. magFilter = gl.NEAREST;
  14495. minFilter = gl.NEAREST;
  14496. break;
  14497. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14498. magFilter = gl.LINEAR;
  14499. if (generateMipMaps) {
  14500. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14501. }
  14502. else {
  14503. minFilter = gl.NEAREST;
  14504. }
  14505. break;
  14506. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14507. magFilter = gl.LINEAR;
  14508. if (generateMipMaps) {
  14509. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14510. }
  14511. else {
  14512. minFilter = gl.NEAREST;
  14513. }
  14514. break;
  14515. case Engine.TEXTURE_LINEAR_LINEAR:
  14516. magFilter = gl.LINEAR;
  14517. minFilter = gl.LINEAR;
  14518. break;
  14519. case Engine.TEXTURE_LINEAR_NEAREST:
  14520. magFilter = gl.LINEAR;
  14521. minFilter = gl.NEAREST;
  14522. break;
  14523. }
  14524. return {
  14525. min: minFilter,
  14526. mag: magFilter
  14527. };
  14528. };
  14529. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14530. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14531. var img;
  14532. var onload = function () {
  14533. loadedImages[index] = img;
  14534. loadedImages._internalCount++;
  14535. if (scene) {
  14536. scene._removePendingData(img);
  14537. }
  14538. if (loadedImages._internalCount === 6) {
  14539. onfinish(loadedImages);
  14540. }
  14541. };
  14542. var onerror = function (message, exception) {
  14543. if (scene) {
  14544. scene._removePendingData(img);
  14545. }
  14546. if (onErrorCallBack) {
  14547. onErrorCallBack(message, exception);
  14548. }
  14549. };
  14550. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14551. if (scene) {
  14552. scene._addPendingData(img);
  14553. }
  14554. };
  14555. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14556. if (onError === void 0) { onError = null; }
  14557. var loadedImages = [];
  14558. loadedImages._internalCount = 0;
  14559. for (var index = 0; index < 6; index++) {
  14560. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14561. }
  14562. };
  14563. ;
  14564. /** @hidden */
  14565. Engine.prototype._createTexture = function () {
  14566. var texture = this._gl.createTexture();
  14567. if (!texture) {
  14568. throw new Error("Unable to create texture");
  14569. }
  14570. return texture;
  14571. };
  14572. /**
  14573. * Usually called from BABYLON.Texture.ts.
  14574. * Passed information to create a WebGLTexture
  14575. * @param urlArg defines a value which contains one of the following:
  14576. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14577. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14578. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14579. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14580. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14581. * @param scene needed for loading to the correct scene
  14582. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14583. * @param onLoad optional callback to be called upon successful completion
  14584. * @param onError optional callback to be called upon failure
  14585. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14586. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14587. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14588. * @param forcedExtension defines the extension to use to pick the right loader
  14589. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14590. */
  14591. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14592. var _this = this;
  14593. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14594. if (onLoad === void 0) { onLoad = null; }
  14595. if (onError === void 0) { onError = null; }
  14596. if (buffer === void 0) { buffer = null; }
  14597. if (fallback === void 0) { fallback = null; }
  14598. if (format === void 0) { format = null; }
  14599. if (forcedExtension === void 0) { forcedExtension = null; }
  14600. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14601. var fromData = url.substr(0, 5) === "data:";
  14602. var fromBlob = url.substr(0, 5) === "blob:";
  14603. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14604. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14605. // establish the file extension, if possible
  14606. var lastDot = url.lastIndexOf('.');
  14607. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14608. var loader = null;
  14609. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14610. var availableLoader = _a[_i];
  14611. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14612. loader = availableLoader;
  14613. break;
  14614. }
  14615. }
  14616. if (loader) {
  14617. url = loader.transformUrl(url, this._textureFormatInUse);
  14618. }
  14619. if (scene) {
  14620. scene._addPendingData(texture);
  14621. }
  14622. texture.url = url;
  14623. texture.generateMipMaps = !noMipmap;
  14624. texture.samplingMode = samplingMode;
  14625. texture.invertY = invertY;
  14626. if (!this._doNotHandleContextLost) {
  14627. // Keep a link to the buffer only if we plan to handle context lost
  14628. texture._buffer = buffer;
  14629. }
  14630. var onLoadObserver = null;
  14631. if (onLoad && !fallback) {
  14632. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14633. }
  14634. if (!fallback)
  14635. this._internalTexturesCache.push(texture);
  14636. var onInternalError = function (message, exception) {
  14637. if (scene) {
  14638. scene._removePendingData(texture);
  14639. }
  14640. var customFallback = false;
  14641. if (loader) {
  14642. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14643. if (fallbackUrl) {
  14644. // Add Back
  14645. customFallback = true;
  14646. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14647. }
  14648. }
  14649. if (!customFallback) {
  14650. if (onLoadObserver) {
  14651. texture.onLoadedObservable.remove(onLoadObserver);
  14652. }
  14653. if (BABYLON.Tools.UseFallbackTexture) {
  14654. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14655. }
  14656. }
  14657. if (onError) {
  14658. onError(message || "Unknown error", exception);
  14659. }
  14660. };
  14661. // processing for non-image formats
  14662. if (loader) {
  14663. var callback = function (data) {
  14664. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14665. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14666. done();
  14667. return false;
  14668. }, samplingMode);
  14669. });
  14670. };
  14671. if (!buffer) {
  14672. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14673. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14674. });
  14675. }
  14676. else {
  14677. callback(buffer);
  14678. }
  14679. }
  14680. else {
  14681. var onload = function (img) {
  14682. if (fromBlob && !_this._doNotHandleContextLost) {
  14683. // We need to store the image if we need to rebuild the texture
  14684. // in case of a webgl context lost
  14685. texture._buffer = img;
  14686. }
  14687. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14688. var gl = _this._gl;
  14689. var isPot = (img.width === potWidth && img.height === potHeight);
  14690. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14691. if (isPot) {
  14692. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14693. return false;
  14694. }
  14695. var maxTextureSize = _this._caps.maxTextureSize;
  14696. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14697. _this._prepareWorkingCanvas();
  14698. if (!_this._workingCanvas || !_this._workingContext) {
  14699. return false;
  14700. }
  14701. _this._workingCanvas.width = potWidth;
  14702. _this._workingCanvas.height = potHeight;
  14703. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14704. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14705. texture.width = potWidth;
  14706. texture.height = potHeight;
  14707. return false;
  14708. }
  14709. else {
  14710. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14711. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14712. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14713. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14716. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14717. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14718. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14719. _this._releaseTexture(source_1);
  14720. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14721. continuationCallback();
  14722. });
  14723. }
  14724. return true;
  14725. }, samplingMode);
  14726. };
  14727. if (!fromData || isBase64) {
  14728. if (buffer instanceof HTMLImageElement) {
  14729. onload(buffer);
  14730. }
  14731. else {
  14732. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14733. }
  14734. }
  14735. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14736. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14737. }
  14738. else {
  14739. onload(buffer);
  14740. }
  14741. }
  14742. return texture;
  14743. };
  14744. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14745. var _this = this;
  14746. var rtt = this.createRenderTargetTexture({
  14747. width: destination.width,
  14748. height: destination.height,
  14749. }, {
  14750. generateMipMaps: false,
  14751. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14752. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14753. generateDepthBuffer: false,
  14754. generateStencilBuffer: false
  14755. });
  14756. if (!this._rescalePostProcess) {
  14757. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14758. }
  14759. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14760. _this._rescalePostProcess.onApply = function (effect) {
  14761. effect._bindTexture("textureSampler", source);
  14762. };
  14763. var hostingScene = scene;
  14764. if (!hostingScene) {
  14765. hostingScene = _this.scenes[_this.scenes.length - 1];
  14766. }
  14767. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14768. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14769. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14770. _this.unBindFramebuffer(rtt);
  14771. _this._releaseTexture(rtt);
  14772. if (onComplete) {
  14773. onComplete();
  14774. }
  14775. });
  14776. };
  14777. /**
  14778. * Update a raw texture
  14779. * @param texture defines the texture to update
  14780. * @param data defines the data to store in the texture
  14781. * @param format defines the format of the data
  14782. * @param invertY defines if data must be stored with Y axis inverted
  14783. * @param compression defines the compression used (null by default)
  14784. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14785. */
  14786. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14787. if (compression === void 0) { compression = null; }
  14788. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14789. if (!texture) {
  14790. return;
  14791. }
  14792. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14793. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14794. // babylon's internalFormat but gl's texImage2D format
  14795. var internalFormat = this._getInternalFormat(format);
  14796. var textureType = this._getWebGLTextureType(type);
  14797. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14798. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14799. if (!this._doNotHandleContextLost) {
  14800. texture._bufferView = data;
  14801. texture.format = format;
  14802. texture.type = type;
  14803. texture.invertY = invertY;
  14804. texture._compression = compression;
  14805. }
  14806. if (texture.width % 4 !== 0) {
  14807. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14808. }
  14809. if (compression && data) {
  14810. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14811. }
  14812. else {
  14813. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14814. }
  14815. if (texture.generateMipMaps) {
  14816. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14817. }
  14818. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14819. // this.resetTextureCache();
  14820. texture.isReady = true;
  14821. };
  14822. /**
  14823. * Creates a raw texture
  14824. * @param data defines the data to store in the texture
  14825. * @param width defines the width of the texture
  14826. * @param height defines the height of the texture
  14827. * @param format defines the format of the data
  14828. * @param generateMipMaps defines if the engine should generate the mip levels
  14829. * @param invertY defines if data must be stored with Y axis inverted
  14830. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14831. * @param compression defines the compression used (null by default)
  14832. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14833. * @returns the raw texture inside an InternalTexture
  14834. */
  14835. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14836. if (compression === void 0) { compression = null; }
  14837. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14838. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14839. texture.baseWidth = width;
  14840. texture.baseHeight = height;
  14841. texture.width = width;
  14842. texture.height = height;
  14843. texture.format = format;
  14844. texture.generateMipMaps = generateMipMaps;
  14845. texture.samplingMode = samplingMode;
  14846. texture.invertY = invertY;
  14847. texture._compression = compression;
  14848. texture.type = type;
  14849. if (!this._doNotHandleContextLost) {
  14850. texture._bufferView = data;
  14851. }
  14852. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14853. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14854. // Filters
  14855. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14856. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14857. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14858. if (generateMipMaps) {
  14859. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14860. }
  14861. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14862. this._internalTexturesCache.push(texture);
  14863. return texture;
  14864. };
  14865. /** @hidden */
  14866. Engine.prototype._unpackFlipY = function (value) {
  14867. if (this._unpackFlipYCached !== value) {
  14868. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14869. if (this.enableUnpackFlipYCached) {
  14870. this._unpackFlipYCached = value;
  14871. }
  14872. }
  14873. };
  14874. /** @hidden */
  14875. Engine.prototype._getUnpackAlignement = function () {
  14876. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14877. };
  14878. /**
  14879. * Creates a dynamic texture
  14880. * @param width defines the width of the texture
  14881. * @param height defines the height of the texture
  14882. * @param generateMipMaps defines if the engine should generate the mip levels
  14883. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14884. * @returns the dynamic texture inside an InternalTexture
  14885. */
  14886. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14887. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14888. texture.baseWidth = width;
  14889. texture.baseHeight = height;
  14890. if (generateMipMaps) {
  14891. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14892. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14893. }
  14894. // this.resetTextureCache();
  14895. texture.width = width;
  14896. texture.height = height;
  14897. texture.isReady = false;
  14898. texture.generateMipMaps = generateMipMaps;
  14899. texture.samplingMode = samplingMode;
  14900. this.updateTextureSamplingMode(samplingMode, texture);
  14901. this._internalTexturesCache.push(texture);
  14902. return texture;
  14903. };
  14904. /**
  14905. * Update the sampling mode of a given texture
  14906. * @param samplingMode defines the required sampling mode
  14907. * @param texture defines the texture to update
  14908. */
  14909. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14910. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14911. if (texture.isCube) {
  14912. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14913. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14914. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14915. }
  14916. else if (texture.is3D) {
  14917. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14918. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14919. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14920. }
  14921. else {
  14922. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14923. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14924. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14925. }
  14926. texture.samplingMode = samplingMode;
  14927. };
  14928. /**
  14929. * Update the content of a dynamic texture
  14930. * @param texture defines the texture to update
  14931. * @param canvas defines the canvas containing the source
  14932. * @param invertY defines if data must be stored with Y axis inverted
  14933. * @param premulAlpha defines if alpha is stored as premultiplied
  14934. * @param format defines the format of the data
  14935. */
  14936. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14937. if (premulAlpha === void 0) { premulAlpha = false; }
  14938. if (!texture) {
  14939. return;
  14940. }
  14941. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14942. this._unpackFlipY(invertY);
  14943. if (premulAlpha) {
  14944. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14945. }
  14946. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14947. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14948. if (texture.generateMipMaps) {
  14949. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14950. }
  14951. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14952. if (premulAlpha) {
  14953. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14954. }
  14955. texture.isReady = true;
  14956. };
  14957. /**
  14958. * Update a video texture
  14959. * @param texture defines the texture to update
  14960. * @param video defines the video element to use
  14961. * @param invertY defines if data must be stored with Y axis inverted
  14962. */
  14963. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14964. if (!texture || texture._isDisabled) {
  14965. return;
  14966. }
  14967. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14968. this._unpackFlipY(!invertY); // Video are upside down by default
  14969. try {
  14970. // Testing video texture support
  14971. if (this._videoTextureSupported === undefined) {
  14972. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14973. if (this._gl.getError() !== 0) {
  14974. this._videoTextureSupported = false;
  14975. }
  14976. else {
  14977. this._videoTextureSupported = true;
  14978. }
  14979. }
  14980. // Copy video through the current working canvas if video texture is not supported
  14981. if (!this._videoTextureSupported) {
  14982. if (!texture._workingCanvas) {
  14983. texture._workingCanvas = document.createElement("canvas");
  14984. var context = texture._workingCanvas.getContext("2d");
  14985. if (!context) {
  14986. throw new Error("Unable to get 2d context");
  14987. }
  14988. texture._workingContext = context;
  14989. texture._workingCanvas.width = texture.width;
  14990. texture._workingCanvas.height = texture.height;
  14991. }
  14992. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14993. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14994. }
  14995. else {
  14996. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14997. }
  14998. if (texture.generateMipMaps) {
  14999. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15000. }
  15001. if (!wasPreviouslyBound) {
  15002. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15003. }
  15004. // this.resetTextureCache();
  15005. texture.isReady = true;
  15006. }
  15007. catch (ex) {
  15008. // Something unexpected
  15009. // Let's disable the texture
  15010. texture._isDisabled = true;
  15011. }
  15012. };
  15013. /**
  15014. * Updates a depth texture Comparison Mode and Function.
  15015. * If the comparison Function is equal to 0, the mode will be set to none.
  15016. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15017. * @param texture The texture to set the comparison function for
  15018. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15019. */
  15020. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15021. if (this.webGLVersion === 1) {
  15022. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15023. return;
  15024. }
  15025. var gl = this._gl;
  15026. if (texture.isCube) {
  15027. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15028. if (comparisonFunction === 0) {
  15029. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15030. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15031. }
  15032. else {
  15033. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15034. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15035. }
  15036. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15037. }
  15038. else {
  15039. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15040. if (comparisonFunction === 0) {
  15041. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15042. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15043. }
  15044. else {
  15045. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15046. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15047. }
  15048. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15049. }
  15050. texture._comparisonFunction = comparisonFunction;
  15051. };
  15052. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15053. var width = size.width || size;
  15054. var height = size.height || size;
  15055. internalTexture.baseWidth = width;
  15056. internalTexture.baseHeight = height;
  15057. internalTexture.width = width;
  15058. internalTexture.height = height;
  15059. internalTexture.isReady = true;
  15060. internalTexture.samples = 1;
  15061. internalTexture.generateMipMaps = false;
  15062. internalTexture._generateDepthBuffer = true;
  15063. internalTexture._generateStencilBuffer = generateStencil;
  15064. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15065. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15066. internalTexture._comparisonFunction = comparisonFunction;
  15067. var gl = this._gl;
  15068. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15069. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15070. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15071. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15072. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15073. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15074. if (comparisonFunction === 0) {
  15075. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15076. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15077. }
  15078. else {
  15079. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15080. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15081. }
  15082. };
  15083. /**
  15084. * Creates a depth stencil texture.
  15085. * This is only available in WebGL 2 or with the depth texture extension available.
  15086. * @param size The size of face edge in the texture.
  15087. * @param options The options defining the texture.
  15088. * @returns The texture
  15089. */
  15090. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15091. if (options.isCube) {
  15092. var width = size.width || size;
  15093. return this._createDepthStencilCubeTexture(width, options);
  15094. }
  15095. else {
  15096. return this._createDepthStencilTexture(size, options);
  15097. }
  15098. };
  15099. /**
  15100. * Creates a depth stencil texture.
  15101. * This is only available in WebGL 2 or with the depth texture extension available.
  15102. * @param size The size of face edge in the texture.
  15103. * @param options The options defining the texture.
  15104. * @returns The texture
  15105. */
  15106. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15107. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15108. if (!this._caps.depthTextureExtension) {
  15109. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15110. return internalTexture;
  15111. }
  15112. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15113. var gl = this._gl;
  15114. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15115. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15116. if (this.webGLVersion > 1) {
  15117. if (internalOptions.generateStencil) {
  15118. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15119. }
  15120. else {
  15121. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15122. }
  15123. }
  15124. else {
  15125. if (internalOptions.generateStencil) {
  15126. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15127. }
  15128. else {
  15129. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15130. }
  15131. }
  15132. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15133. return internalTexture;
  15134. };
  15135. /**
  15136. * Creates a depth stencil cube texture.
  15137. * This is only available in WebGL 2.
  15138. * @param size The size of face edge in the cube texture.
  15139. * @param options The options defining the cube texture.
  15140. * @returns The cube texture
  15141. */
  15142. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15143. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15144. internalTexture.isCube = true;
  15145. if (this.webGLVersion === 1) {
  15146. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15147. return internalTexture;
  15148. }
  15149. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15150. var gl = this._gl;
  15151. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15152. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15153. // Create the depth/stencil buffer
  15154. for (var face = 0; face < 6; face++) {
  15155. if (internalOptions.generateStencil) {
  15156. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15157. }
  15158. else {
  15159. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15160. }
  15161. }
  15162. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15163. return internalTexture;
  15164. };
  15165. /**
  15166. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15167. * @param renderTarget The render target to set the frame buffer for
  15168. */
  15169. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15170. // Create the framebuffer
  15171. var internalTexture = renderTarget.getInternalTexture();
  15172. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15173. return;
  15174. }
  15175. var gl = this._gl;
  15176. var depthStencilTexture = renderTarget.depthStencilTexture;
  15177. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15178. if (depthStencilTexture.isCube) {
  15179. if (depthStencilTexture._generateStencilBuffer) {
  15180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15181. }
  15182. else {
  15183. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15184. }
  15185. }
  15186. else {
  15187. if (depthStencilTexture._generateStencilBuffer) {
  15188. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15189. }
  15190. else {
  15191. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15192. }
  15193. }
  15194. this.bindUnboundFramebuffer(null);
  15195. };
  15196. /**
  15197. * Creates a new render target texture
  15198. * @param size defines the size of the texture
  15199. * @param options defines the options used to create the texture
  15200. * @returns a new render target texture stored in an InternalTexture
  15201. */
  15202. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15203. var fullOptions = new RenderTargetCreationOptions();
  15204. if (options !== undefined && typeof options === "object") {
  15205. fullOptions.generateMipMaps = options.generateMipMaps;
  15206. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15207. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15208. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15209. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15210. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15211. }
  15212. else {
  15213. fullOptions.generateMipMaps = options;
  15214. fullOptions.generateDepthBuffer = true;
  15215. fullOptions.generateStencilBuffer = false;
  15216. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15217. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15218. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15219. }
  15220. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15221. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15222. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15223. }
  15224. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15225. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15226. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15227. }
  15228. var gl = this._gl;
  15229. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15230. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15231. var width = size.width || size;
  15232. var height = size.height || size;
  15233. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15234. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15235. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15236. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15237. }
  15238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15242. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15243. // Create the framebuffer
  15244. var currentFrameBuffer = this._currentFramebuffer;
  15245. var framebuffer = gl.createFramebuffer();
  15246. this.bindUnboundFramebuffer(framebuffer);
  15247. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15248. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15249. if (fullOptions.generateMipMaps) {
  15250. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15251. }
  15252. // Unbind
  15253. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15254. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15255. this.bindUnboundFramebuffer(currentFrameBuffer);
  15256. texture._framebuffer = framebuffer;
  15257. texture.baseWidth = width;
  15258. texture.baseHeight = height;
  15259. texture.width = width;
  15260. texture.height = height;
  15261. texture.isReady = true;
  15262. texture.samples = 1;
  15263. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15264. texture.samplingMode = fullOptions.samplingMode;
  15265. texture.type = fullOptions.type;
  15266. texture.format = fullOptions.format;
  15267. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15268. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15269. // this.resetTextureCache();
  15270. this._internalTexturesCache.push(texture);
  15271. return texture;
  15272. };
  15273. /**
  15274. * Create a multi render target texture
  15275. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15276. * @param size defines the size of the texture
  15277. * @param options defines the creation options
  15278. * @returns the cube texture as an InternalTexture
  15279. */
  15280. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15281. var generateMipMaps = false;
  15282. var generateDepthBuffer = true;
  15283. var generateStencilBuffer = false;
  15284. var generateDepthTexture = false;
  15285. var textureCount = 1;
  15286. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15287. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15288. var types = new Array();
  15289. var samplingModes = new Array();
  15290. if (options !== undefined) {
  15291. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15292. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15293. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15294. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15295. textureCount = options.textureCount || 1;
  15296. if (options.types) {
  15297. types = options.types;
  15298. }
  15299. if (options.samplingModes) {
  15300. samplingModes = options.samplingModes;
  15301. }
  15302. }
  15303. var gl = this._gl;
  15304. // Create the framebuffer
  15305. var framebuffer = gl.createFramebuffer();
  15306. this.bindUnboundFramebuffer(framebuffer);
  15307. var width = size.width || size;
  15308. var height = size.height || size;
  15309. var textures = [];
  15310. var attachments = [];
  15311. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15312. for (var i = 0; i < textureCount; i++) {
  15313. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15314. var type = types[i] || defaultType;
  15315. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15316. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15317. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15318. }
  15319. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15320. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15321. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15322. }
  15323. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15324. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15325. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15326. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15327. }
  15328. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15329. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15330. textures.push(texture);
  15331. attachments.push(attachment);
  15332. gl.activeTexture(gl["TEXTURE" + i]);
  15333. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15334. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15335. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15338. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15339. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15340. if (generateMipMaps) {
  15341. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15342. }
  15343. // Unbind
  15344. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15345. texture._framebuffer = framebuffer;
  15346. texture._depthStencilBuffer = depthStencilBuffer;
  15347. texture.baseWidth = width;
  15348. texture.baseHeight = height;
  15349. texture.width = width;
  15350. texture.height = height;
  15351. texture.isReady = true;
  15352. texture.samples = 1;
  15353. texture.generateMipMaps = generateMipMaps;
  15354. texture.samplingMode = samplingMode;
  15355. texture.type = type;
  15356. texture._generateDepthBuffer = generateDepthBuffer;
  15357. texture._generateStencilBuffer = generateStencilBuffer;
  15358. texture._attachments = attachments;
  15359. this._internalTexturesCache.push(texture);
  15360. }
  15361. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15362. // Depth texture
  15363. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15364. gl.activeTexture(gl.TEXTURE0);
  15365. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15369. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15370. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  15371. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15372. depthTexture._framebuffer = framebuffer;
  15373. depthTexture.baseWidth = width;
  15374. depthTexture.baseHeight = height;
  15375. depthTexture.width = width;
  15376. depthTexture.height = height;
  15377. depthTexture.isReady = true;
  15378. depthTexture.samples = 1;
  15379. depthTexture.generateMipMaps = generateMipMaps;
  15380. depthTexture.samplingMode = gl.NEAREST;
  15381. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15382. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15383. textures.push(depthTexture);
  15384. this._internalTexturesCache.push(depthTexture);
  15385. }
  15386. gl.drawBuffers(attachments);
  15387. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15388. this.bindUnboundFramebuffer(null);
  15389. this.resetTextureCache();
  15390. return textures;
  15391. };
  15392. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15393. if (samples === void 0) { samples = 1; }
  15394. var depthStencilBuffer = null;
  15395. var gl = this._gl;
  15396. // Create the depth/stencil buffer
  15397. if (generateStencilBuffer) {
  15398. depthStencilBuffer = gl.createRenderbuffer();
  15399. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15400. if (samples > 1) {
  15401. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15402. }
  15403. else {
  15404. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15405. }
  15406. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15407. }
  15408. else if (generateDepthBuffer) {
  15409. depthStencilBuffer = gl.createRenderbuffer();
  15410. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15411. if (samples > 1) {
  15412. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15413. }
  15414. else {
  15415. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15416. }
  15417. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15418. }
  15419. return depthStencilBuffer;
  15420. };
  15421. /**
  15422. * Updates the sample count of a render target texture
  15423. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15424. * @param texture defines the texture to update
  15425. * @param samples defines the sample count to set
  15426. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15427. */
  15428. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15429. if (this.webGLVersion < 2 || !texture) {
  15430. return 1;
  15431. }
  15432. if (texture.samples === samples) {
  15433. return samples;
  15434. }
  15435. var gl = this._gl;
  15436. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15437. // Dispose previous render buffers
  15438. if (texture._depthStencilBuffer) {
  15439. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15440. texture._depthStencilBuffer = null;
  15441. }
  15442. if (texture._MSAAFramebuffer) {
  15443. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15444. texture._MSAAFramebuffer = null;
  15445. }
  15446. if (texture._MSAARenderBuffer) {
  15447. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15448. texture._MSAARenderBuffer = null;
  15449. }
  15450. if (samples > 1) {
  15451. var framebuffer = gl.createFramebuffer();
  15452. if (!framebuffer) {
  15453. throw new Error("Unable to create multi sampled framebuffer");
  15454. }
  15455. texture._MSAAFramebuffer = framebuffer;
  15456. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15457. var colorRenderbuffer = gl.createRenderbuffer();
  15458. if (!colorRenderbuffer) {
  15459. throw new Error("Unable to create multi sampled framebuffer");
  15460. }
  15461. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15462. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15463. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15464. texture._MSAARenderBuffer = colorRenderbuffer;
  15465. }
  15466. else {
  15467. this.bindUnboundFramebuffer(texture._framebuffer);
  15468. }
  15469. texture.samples = samples;
  15470. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15471. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15472. this.bindUnboundFramebuffer(null);
  15473. return samples;
  15474. };
  15475. /**
  15476. * Update the sample count for a given multiple render target texture
  15477. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15478. * @param textures defines the textures to update
  15479. * @param samples defines the sample count to set
  15480. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15481. */
  15482. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15483. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15484. return 1;
  15485. }
  15486. if (textures[0].samples === samples) {
  15487. return samples;
  15488. }
  15489. var gl = this._gl;
  15490. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15491. // Dispose previous render buffers
  15492. if (textures[0]._depthStencilBuffer) {
  15493. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15494. textures[0]._depthStencilBuffer = null;
  15495. }
  15496. if (textures[0]._MSAAFramebuffer) {
  15497. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15498. textures[0]._MSAAFramebuffer = null;
  15499. }
  15500. for (var i = 0; i < textures.length; i++) {
  15501. if (textures[i]._MSAARenderBuffer) {
  15502. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15503. textures[i]._MSAARenderBuffer = null;
  15504. }
  15505. }
  15506. if (samples > 1) {
  15507. var framebuffer = gl.createFramebuffer();
  15508. if (!framebuffer) {
  15509. throw new Error("Unable to create multi sampled framebuffer");
  15510. }
  15511. this.bindUnboundFramebuffer(framebuffer);
  15512. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15513. var attachments = [];
  15514. for (var i = 0; i < textures.length; i++) {
  15515. var texture = textures[i];
  15516. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15517. var colorRenderbuffer = gl.createRenderbuffer();
  15518. if (!colorRenderbuffer) {
  15519. throw new Error("Unable to create multi sampled framebuffer");
  15520. }
  15521. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15522. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15523. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15524. texture._MSAAFramebuffer = framebuffer;
  15525. texture._MSAARenderBuffer = colorRenderbuffer;
  15526. texture.samples = samples;
  15527. texture._depthStencilBuffer = depthStencilBuffer;
  15528. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15529. attachments.push(attachment);
  15530. }
  15531. gl.drawBuffers(attachments);
  15532. }
  15533. else {
  15534. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15535. }
  15536. this.bindUnboundFramebuffer(null);
  15537. return samples;
  15538. };
  15539. /** @hidden */
  15540. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15541. if (faceIndex === void 0) { faceIndex = 0; }
  15542. if (lod === void 0) { lod = 0; }
  15543. var gl = this._gl;
  15544. var target = gl.TEXTURE_2D;
  15545. if (texture.isCube) {
  15546. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15547. }
  15548. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15549. };
  15550. /** @hidden */
  15551. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15552. if (faceIndex === void 0) { faceIndex = 0; }
  15553. if (lod === void 0) { lod = 0; }
  15554. var gl = this._gl;
  15555. var textureType = this._getWebGLTextureType(texture.type);
  15556. var format = this._getInternalFormat(texture.format);
  15557. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15558. this._unpackFlipY(texture.invertY);
  15559. var target = gl.TEXTURE_2D;
  15560. if (texture.isCube) {
  15561. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15562. }
  15563. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15564. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15565. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15566. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15567. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15568. };
  15569. /** @hidden */
  15570. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15571. if (faceIndex === void 0) { faceIndex = 0; }
  15572. if (lod === void 0) { lod = 0; }
  15573. var gl = this._gl;
  15574. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15575. this._bindTextureDirectly(bindTarget, texture, true);
  15576. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15577. this._bindTextureDirectly(bindTarget, null, true);
  15578. };
  15579. /** @hidden */
  15580. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15581. if (faceIndex === void 0) { faceIndex = 0; }
  15582. if (lod === void 0) { lod = 0; }
  15583. var gl = this._gl;
  15584. var textureType = this._getWebGLTextureType(texture.type);
  15585. var format = this._getInternalFormat(texture.format);
  15586. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15587. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15588. this._bindTextureDirectly(bindTarget, texture, true);
  15589. this._unpackFlipY(texture.invertY);
  15590. var target = gl.TEXTURE_2D;
  15591. if (texture.isCube) {
  15592. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15593. }
  15594. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15595. this._bindTextureDirectly(bindTarget, null, true);
  15596. };
  15597. /**
  15598. * Creates a new render target cube texture
  15599. * @param size defines the size of the texture
  15600. * @param options defines the options used to create the texture
  15601. * @returns a new render target cube texture stored in an InternalTexture
  15602. */
  15603. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15604. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15605. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15606. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15607. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15608. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15609. }
  15610. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15611. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15612. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15613. }
  15614. var gl = this._gl;
  15615. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15616. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15617. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15618. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15619. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15620. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15621. }
  15622. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15626. for (var face = 0; face < 6; face++) {
  15627. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15628. }
  15629. // Create the framebuffer
  15630. var framebuffer = gl.createFramebuffer();
  15631. this.bindUnboundFramebuffer(framebuffer);
  15632. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15633. // MipMaps
  15634. if (fullOptions.generateMipMaps) {
  15635. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15636. }
  15637. // Unbind
  15638. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15639. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15640. this.bindUnboundFramebuffer(null);
  15641. texture._framebuffer = framebuffer;
  15642. texture.width = size;
  15643. texture.height = size;
  15644. texture.isReady = true;
  15645. texture.isCube = true;
  15646. texture.samples = 1;
  15647. texture.generateMipMaps = fullOptions.generateMipMaps;
  15648. texture.samplingMode = fullOptions.samplingMode;
  15649. texture.type = fullOptions.type;
  15650. texture.format = fullOptions.format;
  15651. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15652. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15653. this._internalTexturesCache.push(texture);
  15654. return texture;
  15655. };
  15656. /**
  15657. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15658. * @param rootUrl defines the url where the file to load is located
  15659. * @param scene defines the current scene
  15660. * @param lodScale defines scale to apply to the mip map selection
  15661. * @param lodOffset defines offset to apply to the mip map selection
  15662. * @param onLoad defines an optional callback raised when the texture is loaded
  15663. * @param onError defines an optional callback raised if there is an issue to load the texture
  15664. * @param format defines the format of the data
  15665. * @param forcedExtension defines the extension to use to pick the right loader
  15666. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15667. * @returns the cube texture as an InternalTexture
  15668. */
  15669. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15670. var _this = this;
  15671. if (onLoad === void 0) { onLoad = null; }
  15672. if (onError === void 0) { onError = null; }
  15673. if (forcedExtension === void 0) { forcedExtension = null; }
  15674. if (createPolynomials === void 0) { createPolynomials = true; }
  15675. var callback = function (loadData) {
  15676. if (!loadData) {
  15677. if (onLoad) {
  15678. onLoad(null);
  15679. }
  15680. return;
  15681. }
  15682. var texture = loadData.texture;
  15683. if (!createPolynomials) {
  15684. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15685. }
  15686. else if (loadData.info.sphericalPolynomial) {
  15687. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15688. }
  15689. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15690. if (_this._caps.textureLOD) {
  15691. // Do not add extra process if texture lod is supported.
  15692. if (onLoad) {
  15693. onLoad(texture);
  15694. }
  15695. return;
  15696. }
  15697. var mipSlices = 3;
  15698. var gl = _this._gl;
  15699. var width = loadData.width;
  15700. if (!width) {
  15701. return;
  15702. }
  15703. var textures = [];
  15704. for (var i = 0; i < mipSlices; i++) {
  15705. //compute LOD from even spacing in smoothness (matching shader calculation)
  15706. var smoothness = i / (mipSlices - 1);
  15707. var roughness = 1 - smoothness;
  15708. var minLODIndex = lodOffset; // roughness = 0
  15709. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15710. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15711. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15712. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15713. glTextureFromLod.type = texture.type;
  15714. glTextureFromLod.format = texture.format;
  15715. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15716. glTextureFromLod.height = glTextureFromLod.width;
  15717. glTextureFromLod.isCube = true;
  15718. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15723. if (loadData.isDDS) {
  15724. var info = loadData.info;
  15725. var data = loadData.data;
  15726. _this._unpackFlipY(info.isCompressed);
  15727. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15728. }
  15729. else {
  15730. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15731. }
  15732. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15733. // Wrap in a base texture for easy binding.
  15734. var lodTexture = new BABYLON.BaseTexture(scene);
  15735. lodTexture.isCube = true;
  15736. lodTexture._texture = glTextureFromLod;
  15737. glTextureFromLod.isReady = true;
  15738. textures.push(lodTexture);
  15739. }
  15740. texture._lodTextureHigh = textures[2];
  15741. texture._lodTextureMid = textures[1];
  15742. texture._lodTextureLow = textures[0];
  15743. if (onLoad) {
  15744. onLoad(texture);
  15745. }
  15746. };
  15747. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15748. };
  15749. /**
  15750. * Creates a cube texture
  15751. * @param rootUrl defines the url where the files to load is located
  15752. * @param scene defines the current scene
  15753. * @param files defines the list of files to load (1 per face)
  15754. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15755. * @param onLoad defines an optional callback raised when the texture is loaded
  15756. * @param onError defines an optional callback raised if there is an issue to load the texture
  15757. * @param format defines the format of the data
  15758. * @param forcedExtension defines the extension to use to pick the right loader
  15759. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15760. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15761. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15762. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15763. * @returns the cube texture as an InternalTexture
  15764. */
  15765. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15766. var _this = this;
  15767. if (onLoad === void 0) { onLoad = null; }
  15768. if (onError === void 0) { onError = null; }
  15769. if (forcedExtension === void 0) { forcedExtension = null; }
  15770. if (createPolynomials === void 0) { createPolynomials = false; }
  15771. if (lodScale === void 0) { lodScale = 0; }
  15772. if (lodOffset === void 0) { lodOffset = 0; }
  15773. if (fallback === void 0) { fallback = null; }
  15774. var gl = this._gl;
  15775. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15776. texture.isCube = true;
  15777. texture.url = rootUrl;
  15778. texture.generateMipMaps = !noMipmap;
  15779. texture._lodGenerationScale = lodScale;
  15780. texture._lodGenerationOffset = lodOffset;
  15781. if (!this._doNotHandleContextLost) {
  15782. texture._extension = forcedExtension;
  15783. texture._files = files;
  15784. }
  15785. var lastDot = rootUrl.lastIndexOf('.');
  15786. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15787. var loader = null;
  15788. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15789. var availableLoader = _a[_i];
  15790. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15791. loader = availableLoader;
  15792. break;
  15793. }
  15794. }
  15795. var onInternalError = function (request, exception) {
  15796. if (loader) {
  15797. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15798. if (fallbackUrl) {
  15799. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15800. }
  15801. }
  15802. if (onError && request) {
  15803. onError(request.status + " " + request.statusText, exception);
  15804. }
  15805. };
  15806. if (loader) {
  15807. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15808. var onloaddata = function (data) {
  15809. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15810. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15811. };
  15812. if (files && files.length === 6) {
  15813. if (loader.supportCascades) {
  15814. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15815. }
  15816. else if (onError) {
  15817. onError("Textures type does not support cascades.");
  15818. }
  15819. }
  15820. else {
  15821. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15822. }
  15823. }
  15824. else {
  15825. if (!files) {
  15826. throw new Error("Cannot load cubemap because files were not defined");
  15827. }
  15828. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15829. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15830. var height = width;
  15831. _this._prepareWorkingCanvas();
  15832. if (!_this._workingCanvas || !_this._workingContext) {
  15833. return;
  15834. }
  15835. _this._workingCanvas.width = width;
  15836. _this._workingCanvas.height = height;
  15837. var faces = [
  15838. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15839. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15840. ];
  15841. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15842. _this._unpackFlipY(false);
  15843. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15844. for (var index = 0; index < faces.length; index++) {
  15845. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15846. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15847. }
  15848. if (!noMipmap) {
  15849. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15850. }
  15851. _this._setCubeMapTextureParams(!noMipmap);
  15852. texture.width = width;
  15853. texture.height = height;
  15854. texture.isReady = true;
  15855. if (format) {
  15856. texture.format = format;
  15857. }
  15858. texture.onLoadedObservable.notifyObservers(texture);
  15859. texture.onLoadedObservable.clear();
  15860. if (onLoad) {
  15861. onLoad();
  15862. }
  15863. }, files, onError);
  15864. }
  15865. this._internalTexturesCache.push(texture);
  15866. return texture;
  15867. };
  15868. /**
  15869. * @hidden
  15870. */
  15871. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15872. var gl = this._gl;
  15873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15877. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15878. // this.resetTextureCache();
  15879. };
  15880. /**
  15881. * Update a raw cube texture
  15882. * @param texture defines the texture to udpdate
  15883. * @param data defines the data to store
  15884. * @param format defines the data format
  15885. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15886. * @param invertY defines if data must be stored with Y axis inverted
  15887. * @param compression defines the compression used (null by default)
  15888. * @param level defines which level of the texture to update
  15889. */
  15890. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15891. if (compression === void 0) { compression = null; }
  15892. if (level === void 0) { level = 0; }
  15893. texture._bufferViewArray = data;
  15894. texture.format = format;
  15895. texture.type = type;
  15896. texture.invertY = invertY;
  15897. texture._compression = compression;
  15898. var gl = this._gl;
  15899. var textureType = this._getWebGLTextureType(type);
  15900. var internalFormat = this._getInternalFormat(format);
  15901. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15902. var needConversion = false;
  15903. if (internalFormat === gl.RGB) {
  15904. internalFormat = gl.RGBA;
  15905. needConversion = true;
  15906. }
  15907. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15908. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15909. if (texture.width % 4 !== 0) {
  15910. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15911. }
  15912. // Data are known to be in +X +Y +Z -X -Y -Z
  15913. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15914. var faceData = data[faceIndex];
  15915. if (compression) {
  15916. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15917. }
  15918. else {
  15919. if (needConversion) {
  15920. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15921. }
  15922. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15923. }
  15924. }
  15925. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15926. if (isPot && texture.generateMipMaps && level === 0) {
  15927. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15928. }
  15929. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15930. // this.resetTextureCache();
  15931. texture.isReady = true;
  15932. };
  15933. /**
  15934. * Creates a new raw cube texture
  15935. * @param data defines the array of data to use to create each face
  15936. * @param size defines the size of the textures
  15937. * @param format defines the format of the data
  15938. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15939. * @param generateMipMaps defines if the engine should generate the mip levels
  15940. * @param invertY defines if data must be stored with Y axis inverted
  15941. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15942. * @param compression defines the compression used (null by default)
  15943. * @returns the cube texture as an InternalTexture
  15944. */
  15945. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15946. if (compression === void 0) { compression = null; }
  15947. var gl = this._gl;
  15948. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15949. texture.isCube = true;
  15950. texture.format = format;
  15951. texture.type = type;
  15952. if (!this._doNotHandleContextLost) {
  15953. texture._bufferViewArray = data;
  15954. }
  15955. var textureType = this._getWebGLTextureType(type);
  15956. var internalFormat = this._getInternalFormat(format);
  15957. if (internalFormat === gl.RGB) {
  15958. internalFormat = gl.RGBA;
  15959. }
  15960. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15961. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15962. generateMipMaps = false;
  15963. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15964. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15965. }
  15966. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15967. generateMipMaps = false;
  15968. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15969. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15970. }
  15971. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15972. generateMipMaps = false;
  15973. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15974. }
  15975. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15976. generateMipMaps = false;
  15977. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15978. }
  15979. var width = size;
  15980. var height = width;
  15981. texture.width = width;
  15982. texture.height = height;
  15983. // Double check on POT to generate Mips.
  15984. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15985. if (!isPot) {
  15986. generateMipMaps = false;
  15987. }
  15988. // Upload data if needed. The texture won't be ready until then.
  15989. if (data) {
  15990. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15991. }
  15992. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15993. // Filters
  15994. if (data && generateMipMaps) {
  15995. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15996. }
  15997. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15998. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15999. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16002. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16003. texture.generateMipMaps = generateMipMaps;
  16004. return texture;
  16005. };
  16006. /**
  16007. * Creates a new raw cube texture from a specified url
  16008. * @param url defines the url where the data is located
  16009. * @param scene defines the current scene
  16010. * @param size defines the size of the textures
  16011. * @param format defines the format of the data
  16012. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16013. * @param noMipmap defines if the engine should avoid generating the mip levels
  16014. * @param callback defines a callback used to extract texture data from loaded data
  16015. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16016. * @param onLoad defines a callback called when texture is loaded
  16017. * @param onError defines a callback called if there is an error
  16018. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16019. * @param invertY defines if data must be stored with Y axis inverted
  16020. * @returns the cube texture as an InternalTexture
  16021. */
  16022. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16023. var _this = this;
  16024. if (onLoad === void 0) { onLoad = null; }
  16025. if (onError === void 0) { onError = null; }
  16026. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16027. if (invertY === void 0) { invertY = false; }
  16028. var gl = this._gl;
  16029. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16030. scene._addPendingData(texture);
  16031. texture.url = url;
  16032. this._internalTexturesCache.push(texture);
  16033. var onerror = function (request, exception) {
  16034. scene._removePendingData(texture);
  16035. if (onError && request) {
  16036. onError(request.status + " " + request.statusText, exception);
  16037. }
  16038. };
  16039. var internalCallback = function (data) {
  16040. var width = texture.width;
  16041. var faceDataArrays = callback(data);
  16042. if (!faceDataArrays) {
  16043. return;
  16044. }
  16045. if (mipmapGenerator) {
  16046. var textureType = _this._getWebGLTextureType(type);
  16047. var internalFormat = _this._getInternalFormat(format);
  16048. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16049. var needConversion = false;
  16050. if (internalFormat === gl.RGB) {
  16051. internalFormat = gl.RGBA;
  16052. needConversion = true;
  16053. }
  16054. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16055. _this._unpackFlipY(false);
  16056. var mipData = mipmapGenerator(faceDataArrays);
  16057. for (var level = 0; level < mipData.length; level++) {
  16058. var mipSize = width >> level;
  16059. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16060. var mipFaceData = mipData[level][faceIndex];
  16061. if (needConversion) {
  16062. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16063. }
  16064. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16065. }
  16066. }
  16067. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16068. }
  16069. else {
  16070. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16071. }
  16072. texture.isReady = true;
  16073. // this.resetTextureCache();
  16074. scene._removePendingData(texture);
  16075. if (onLoad) {
  16076. onLoad();
  16077. }
  16078. };
  16079. this._loadFile(url, function (data) {
  16080. internalCallback(data);
  16081. }, undefined, scene.database, true, onerror);
  16082. return texture;
  16083. };
  16084. ;
  16085. /**
  16086. * Update a raw 3D texture
  16087. * @param texture defines the texture to update
  16088. * @param data defines the data to store
  16089. * @param format defines the data format
  16090. * @param invertY defines if data must be stored with Y axis inverted
  16091. * @param compression defines the used compression (can be null)
  16092. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16093. */
  16094. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16095. if (compression === void 0) { compression = null; }
  16096. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16097. var internalType = this._getWebGLTextureType(textureType);
  16098. var internalFormat = this._getInternalFormat(format);
  16099. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16100. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16101. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16102. if (!this._doNotHandleContextLost) {
  16103. texture._bufferView = data;
  16104. texture.format = format;
  16105. texture.invertY = invertY;
  16106. texture._compression = compression;
  16107. }
  16108. if (texture.width % 4 !== 0) {
  16109. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16110. }
  16111. if (compression && data) {
  16112. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16113. }
  16114. else {
  16115. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16116. }
  16117. if (texture.generateMipMaps) {
  16118. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16119. }
  16120. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16121. // this.resetTextureCache();
  16122. texture.isReady = true;
  16123. };
  16124. /**
  16125. * Creates a new raw 3D texture
  16126. * @param data defines the data used to create the texture
  16127. * @param width defines the width of the texture
  16128. * @param height defines the height of the texture
  16129. * @param depth defines the depth of the texture
  16130. * @param format defines the format of the texture
  16131. * @param generateMipMaps defines if the engine must generate mip levels
  16132. * @param invertY defines if data must be stored with Y axis inverted
  16133. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16134. * @param compression defines the compressed used (can be null)
  16135. * @param textureType defines the compressed used (can be null)
  16136. * @returns a new raw 3D texture (stored in an InternalTexture)
  16137. */
  16138. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16139. if (compression === void 0) { compression = null; }
  16140. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16141. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16142. texture.baseWidth = width;
  16143. texture.baseHeight = height;
  16144. texture.baseDepth = depth;
  16145. texture.width = width;
  16146. texture.height = height;
  16147. texture.depth = depth;
  16148. texture.format = format;
  16149. texture.type = textureType;
  16150. texture.generateMipMaps = generateMipMaps;
  16151. texture.samplingMode = samplingMode;
  16152. texture.is3D = true;
  16153. if (!this._doNotHandleContextLost) {
  16154. texture._bufferView = data;
  16155. }
  16156. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16157. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16158. // Filters
  16159. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16160. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16161. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16162. if (generateMipMaps) {
  16163. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16164. }
  16165. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16166. this._internalTexturesCache.push(texture);
  16167. return texture;
  16168. };
  16169. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16170. var gl = this._gl;
  16171. if (!gl) {
  16172. return;
  16173. }
  16174. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16177. if (!noMipmap && !isCompressed) {
  16178. gl.generateMipmap(gl.TEXTURE_2D);
  16179. }
  16180. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16181. // this.resetTextureCache();
  16182. if (scene) {
  16183. scene._removePendingData(texture);
  16184. }
  16185. texture.onLoadedObservable.notifyObservers(texture);
  16186. texture.onLoadedObservable.clear();
  16187. };
  16188. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16189. var _this = this;
  16190. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16191. var maxTextureSize = this.getCaps().maxTextureSize;
  16192. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16193. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16194. var gl = this._gl;
  16195. if (!gl) {
  16196. return;
  16197. }
  16198. if (!texture._webGLTexture) {
  16199. // this.resetTextureCache();
  16200. if (scene) {
  16201. scene._removePendingData(texture);
  16202. }
  16203. return;
  16204. }
  16205. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16206. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16207. texture.baseWidth = width;
  16208. texture.baseHeight = height;
  16209. texture.width = potWidth;
  16210. texture.height = potHeight;
  16211. texture.isReady = true;
  16212. if (processFunction(potWidth, potHeight, function () {
  16213. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16214. })) {
  16215. // Returning as texture needs extra async steps
  16216. return;
  16217. }
  16218. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16219. };
  16220. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16221. // Create new RGBA data container.
  16222. var rgbaData;
  16223. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16224. rgbaData = new Float32Array(width * height * 4);
  16225. }
  16226. else {
  16227. rgbaData = new Uint32Array(width * height * 4);
  16228. }
  16229. // Convert each pixel.
  16230. for (var x = 0; x < width; x++) {
  16231. for (var y = 0; y < height; y++) {
  16232. var index = (y * width + x) * 3;
  16233. var newIndex = (y * width + x) * 4;
  16234. // Map Old Value to new value.
  16235. rgbaData[newIndex + 0] = rgbData[index + 0];
  16236. rgbaData[newIndex + 1] = rgbData[index + 1];
  16237. rgbaData[newIndex + 2] = rgbData[index + 2];
  16238. // Add fully opaque alpha channel.
  16239. rgbaData[newIndex + 3] = 1;
  16240. }
  16241. }
  16242. return rgbaData;
  16243. };
  16244. /** @hidden */
  16245. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16246. var gl = this._gl;
  16247. if (texture._framebuffer) {
  16248. gl.deleteFramebuffer(texture._framebuffer);
  16249. texture._framebuffer = null;
  16250. }
  16251. if (texture._depthStencilBuffer) {
  16252. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16253. texture._depthStencilBuffer = null;
  16254. }
  16255. if (texture._MSAAFramebuffer) {
  16256. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16257. texture._MSAAFramebuffer = null;
  16258. }
  16259. if (texture._MSAARenderBuffer) {
  16260. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16261. texture._MSAARenderBuffer = null;
  16262. }
  16263. };
  16264. /** @hidden */
  16265. Engine.prototype._releaseTexture = function (texture) {
  16266. var gl = this._gl;
  16267. this._releaseFramebufferObjects(texture);
  16268. gl.deleteTexture(texture._webGLTexture);
  16269. // Unbind channels
  16270. this.unbindAllTextures();
  16271. var index = this._internalTexturesCache.indexOf(texture);
  16272. if (index !== -1) {
  16273. this._internalTexturesCache.splice(index, 1);
  16274. }
  16275. // Integrated fixed lod samplers.
  16276. if (texture._lodTextureHigh) {
  16277. texture._lodTextureHigh.dispose();
  16278. }
  16279. if (texture._lodTextureMid) {
  16280. texture._lodTextureMid.dispose();
  16281. }
  16282. if (texture._lodTextureLow) {
  16283. texture._lodTextureLow.dispose();
  16284. }
  16285. // Set output texture of post process to null if the texture has been released/disposed
  16286. this.scenes.forEach(function (scene) {
  16287. scene.postProcesses.forEach(function (postProcess) {
  16288. if (postProcess._outputTexture == texture) {
  16289. postProcess._outputTexture = null;
  16290. }
  16291. });
  16292. scene.cameras.forEach(function (camera) {
  16293. camera._postProcesses.forEach(function (postProcess) {
  16294. if (postProcess) {
  16295. if (postProcess._outputTexture == texture) {
  16296. postProcess._outputTexture = null;
  16297. }
  16298. }
  16299. });
  16300. });
  16301. });
  16302. };
  16303. Engine.prototype.setProgram = function (program) {
  16304. if (this._currentProgram !== program) {
  16305. this._gl.useProgram(program);
  16306. this._currentProgram = program;
  16307. }
  16308. };
  16309. /**
  16310. * Binds an effect to the webGL context
  16311. * @param effect defines the effect to bind
  16312. */
  16313. Engine.prototype.bindSamplers = function (effect) {
  16314. this.setProgram(effect.getProgram());
  16315. var samplers = effect.getSamplers();
  16316. for (var index = 0; index < samplers.length; index++) {
  16317. var uniform = effect.getUniform(samplers[index]);
  16318. if (uniform) {
  16319. this._boundUniforms[index] = uniform;
  16320. }
  16321. }
  16322. this._currentEffect = null;
  16323. };
  16324. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16325. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16326. return;
  16327. }
  16328. // Remove
  16329. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16330. // Bind last to it
  16331. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16332. // Bind to dummy
  16333. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16334. };
  16335. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16336. if (!internalTexture) {
  16337. return -1;
  16338. }
  16339. internalTexture._initialSlot = channel;
  16340. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16341. if (channel !== internalTexture._designatedSlot) {
  16342. this._textureCollisions.addCount(1, false);
  16343. }
  16344. }
  16345. else {
  16346. if (channel !== internalTexture._designatedSlot) {
  16347. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16348. return internalTexture._designatedSlot;
  16349. }
  16350. else {
  16351. // No slot for this texture, let's pick a new one (if we find a free slot)
  16352. if (this._nextFreeTextureSlots.length) {
  16353. return this._nextFreeTextureSlots[0];
  16354. }
  16355. // We need to recycle the oldest bound texture, sorry.
  16356. this._textureCollisions.addCount(1, false);
  16357. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16358. }
  16359. }
  16360. }
  16361. return channel;
  16362. };
  16363. Engine.prototype._linkTrackers = function (previous, next) {
  16364. previous.next = next;
  16365. next.previous = previous;
  16366. };
  16367. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16368. var currentSlot = internalTexture._designatedSlot;
  16369. if (currentSlot === -1) {
  16370. return -1;
  16371. }
  16372. internalTexture._designatedSlot = -1;
  16373. if (this.disableTextureBindingOptimization) {
  16374. return -1;
  16375. }
  16376. // Remove from bound list
  16377. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16378. // Free the slot
  16379. this._boundTexturesCache[currentSlot] = null;
  16380. this._nextFreeTextureSlots.push(currentSlot);
  16381. return currentSlot;
  16382. };
  16383. Engine.prototype._activateCurrentTexture = function () {
  16384. if (this._currentTextureChannel !== this._activeChannel) {
  16385. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16386. this._currentTextureChannel = this._activeChannel;
  16387. }
  16388. };
  16389. /** @hidden */
  16390. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16391. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16392. if (force === void 0) { force = false; }
  16393. var wasPreviouslyBound = false;
  16394. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16395. this._activeChannel = texture._designatedSlot;
  16396. }
  16397. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16398. var isTextureForRendering = texture && texture._initialSlot > -1;
  16399. if (currentTextureBound !== texture || force) {
  16400. if (currentTextureBound) {
  16401. this._removeDesignatedSlot(currentTextureBound);
  16402. }
  16403. this._activateCurrentTexture();
  16404. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16405. this._boundTexturesCache[this._activeChannel] = texture;
  16406. if (texture) {
  16407. if (!this.disableTextureBindingOptimization) {
  16408. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16409. if (slotIndex > -1) {
  16410. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16411. }
  16412. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16413. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16414. }
  16415. texture._designatedSlot = this._activeChannel;
  16416. }
  16417. }
  16418. else if (forTextureDataUpdate) {
  16419. wasPreviouslyBound = true;
  16420. this._activateCurrentTexture();
  16421. }
  16422. if (isTextureForRendering && !forTextureDataUpdate) {
  16423. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16424. }
  16425. return wasPreviouslyBound;
  16426. };
  16427. /** @hidden */
  16428. Engine.prototype._bindTexture = function (channel, texture) {
  16429. if (channel < 0) {
  16430. return;
  16431. }
  16432. if (texture) {
  16433. channel = this._getCorrectTextureChannel(channel, texture);
  16434. }
  16435. this._activeChannel = channel;
  16436. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16437. };
  16438. /**
  16439. * Sets a texture to the webGL context from a postprocess
  16440. * @param channel defines the channel to use
  16441. * @param postProcess defines the source postprocess
  16442. */
  16443. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16444. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16445. };
  16446. /**
  16447. * Binds the output of the passed in post process to the texture channel specified
  16448. * @param channel The channel the texture should be bound to
  16449. * @param postProcess The post process which's output should be bound
  16450. */
  16451. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16452. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16453. };
  16454. /**
  16455. * Unbind all textures from the webGL context
  16456. */
  16457. Engine.prototype.unbindAllTextures = function () {
  16458. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16459. this._activeChannel = channel;
  16460. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16461. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16462. if (this.webGLVersion > 1) {
  16463. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16464. }
  16465. }
  16466. };
  16467. /**
  16468. * Sets a texture to the according uniform.
  16469. * @param channel The texture channel
  16470. * @param uniform The uniform to set
  16471. * @param texture The texture to apply
  16472. */
  16473. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16474. if (channel < 0) {
  16475. return;
  16476. }
  16477. if (uniform) {
  16478. this._boundUniforms[channel] = uniform;
  16479. }
  16480. this._setTexture(channel, texture);
  16481. };
  16482. /**
  16483. * Sets a depth stencil texture from a render target to the according uniform.
  16484. * @param channel The texture channel
  16485. * @param uniform The uniform to set
  16486. * @param texture The render target texture containing the depth stencil texture to apply
  16487. */
  16488. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16489. if (channel < 0) {
  16490. return;
  16491. }
  16492. if (uniform) {
  16493. this._boundUniforms[channel] = uniform;
  16494. }
  16495. if (!texture || !texture.depthStencilTexture) {
  16496. this._setTexture(channel, null);
  16497. }
  16498. else {
  16499. this._setTexture(channel, texture, false, true);
  16500. }
  16501. };
  16502. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16503. var uniform = this._boundUniforms[sourceSlot];
  16504. if (uniform._currentState === destination) {
  16505. return;
  16506. }
  16507. this._gl.uniform1i(uniform, destination);
  16508. uniform._currentState = destination;
  16509. };
  16510. Engine.prototype._getTextureWrapMode = function (mode) {
  16511. switch (mode) {
  16512. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16513. return this._gl.REPEAT;
  16514. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16515. return this._gl.CLAMP_TO_EDGE;
  16516. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16517. return this._gl.MIRRORED_REPEAT;
  16518. }
  16519. return this._gl.REPEAT;
  16520. };
  16521. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16522. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16523. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16524. // Not ready?
  16525. if (!texture) {
  16526. if (this._boundTexturesCache[channel] != null) {
  16527. this._activeChannel = channel;
  16528. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16529. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16530. if (this.webGLVersion > 1) {
  16531. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16532. }
  16533. }
  16534. return false;
  16535. }
  16536. // Video
  16537. if (texture.video) {
  16538. this._activeChannel = channel;
  16539. texture.update();
  16540. }
  16541. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16542. texture.delayLoad();
  16543. return false;
  16544. }
  16545. var internalTexture;
  16546. if (depthStencilTexture) {
  16547. internalTexture = texture.depthStencilTexture;
  16548. }
  16549. else if (texture.isReady()) {
  16550. internalTexture = texture.getInternalTexture();
  16551. }
  16552. else if (texture.isCube) {
  16553. internalTexture = this.emptyCubeTexture;
  16554. }
  16555. else if (texture.is3D) {
  16556. internalTexture = this.emptyTexture3D;
  16557. }
  16558. else {
  16559. internalTexture = this.emptyTexture;
  16560. }
  16561. if (!isPartOfTextureArray) {
  16562. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16563. }
  16564. var needToBind = true;
  16565. if (this._boundTexturesCache[channel] === internalTexture) {
  16566. this._moveBoundTextureOnTop(internalTexture);
  16567. if (!isPartOfTextureArray) {
  16568. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16569. }
  16570. needToBind = false;
  16571. }
  16572. this._activeChannel = channel;
  16573. if (internalTexture && internalTexture.is3D) {
  16574. if (needToBind) {
  16575. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16576. }
  16577. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16578. internalTexture._cachedWrapU = texture.wrapU;
  16579. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16580. }
  16581. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16582. internalTexture._cachedWrapV = texture.wrapV;
  16583. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16584. }
  16585. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16586. internalTexture._cachedWrapR = texture.wrapR;
  16587. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16588. }
  16589. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16590. }
  16591. else if (internalTexture && internalTexture.isCube) {
  16592. if (needToBind) {
  16593. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16594. }
  16595. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16596. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16597. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16598. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16599. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16600. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16601. }
  16602. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16603. }
  16604. else {
  16605. if (needToBind) {
  16606. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16607. }
  16608. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16609. internalTexture._cachedWrapU = texture.wrapU;
  16610. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16611. }
  16612. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16613. internalTexture._cachedWrapV = texture.wrapV;
  16614. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16615. }
  16616. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16617. }
  16618. return true;
  16619. };
  16620. /**
  16621. * Sets an array of texture to the webGL context
  16622. * @param channel defines the channel where the texture array must be set
  16623. * @param uniform defines the associated uniform location
  16624. * @param textures defines the array of textures to bind
  16625. */
  16626. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16627. if (channel < 0 || !uniform) {
  16628. return;
  16629. }
  16630. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16631. this._textureUnits = new Int32Array(textures.length);
  16632. }
  16633. for (var i = 0; i < textures.length; i++) {
  16634. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16635. }
  16636. this._gl.uniform1iv(uniform, this._textureUnits);
  16637. for (var index = 0; index < textures.length; index++) {
  16638. this._setTexture(this._textureUnits[index], textures[index], true);
  16639. }
  16640. };
  16641. /** @hidden */
  16642. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16643. var internalTexture = texture.getInternalTexture();
  16644. if (!internalTexture) {
  16645. return;
  16646. }
  16647. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16648. var value = texture.anisotropicFilteringLevel;
  16649. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16650. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16651. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16652. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16653. }
  16654. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16655. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16656. internalTexture._cachedAnisotropicFilteringLevel = value;
  16657. }
  16658. };
  16659. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16660. this._bindTextureDirectly(target, texture, true, true);
  16661. this._gl.texParameterf(target, parameter, value);
  16662. };
  16663. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16664. if (texture) {
  16665. this._bindTextureDirectly(target, texture, true, true);
  16666. }
  16667. this._gl.texParameteri(target, parameter, value);
  16668. };
  16669. /**
  16670. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16671. * @param x defines the x coordinate of the rectangle where pixels must be read
  16672. * @param y defines the y coordinate of the rectangle where pixels must be read
  16673. * @param width defines the width of the rectangle where pixels must be read
  16674. * @param height defines the height of the rectangle where pixels must be read
  16675. * @returns a Uint8Array containing RGBA colors
  16676. */
  16677. Engine.prototype.readPixels = function (x, y, width, height) {
  16678. var data = new Uint8Array(height * width * 4);
  16679. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16680. return data;
  16681. };
  16682. /**
  16683. * Add an externaly attached data from its key.
  16684. * This method call will fail and return false, if such key already exists.
  16685. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16686. * @param key the unique key that identifies the data
  16687. * @param data the data object to associate to the key for this Engine instance
  16688. * @return true if no such key were already present and the data was added successfully, false otherwise
  16689. */
  16690. Engine.prototype.addExternalData = function (key, data) {
  16691. if (!this._externalData) {
  16692. this._externalData = new BABYLON.StringDictionary();
  16693. }
  16694. return this._externalData.add(key, data);
  16695. };
  16696. /**
  16697. * Get an externaly attached data from its key
  16698. * @param key the unique key that identifies the data
  16699. * @return the associated data, if present (can be null), or undefined if not present
  16700. */
  16701. Engine.prototype.getExternalData = function (key) {
  16702. if (!this._externalData) {
  16703. this._externalData = new BABYLON.StringDictionary();
  16704. }
  16705. return this._externalData.get(key);
  16706. };
  16707. /**
  16708. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16709. * @param key the unique key that identifies the data
  16710. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16711. * @return the associated data, can be null if the factory returned null.
  16712. */
  16713. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16714. if (!this._externalData) {
  16715. this._externalData = new BABYLON.StringDictionary();
  16716. }
  16717. return this._externalData.getOrAddWithFactory(key, factory);
  16718. };
  16719. /**
  16720. * Remove an externaly attached data from the Engine instance
  16721. * @param key the unique key that identifies the data
  16722. * @return true if the data was successfully removed, false if it doesn't exist
  16723. */
  16724. Engine.prototype.removeExternalData = function (key) {
  16725. if (!this._externalData) {
  16726. this._externalData = new BABYLON.StringDictionary();
  16727. }
  16728. return this._externalData.remove(key);
  16729. };
  16730. /**
  16731. * Unbind all vertex attributes from the webGL context
  16732. */
  16733. Engine.prototype.unbindAllAttributes = function () {
  16734. if (this._mustWipeVertexAttributes) {
  16735. this._mustWipeVertexAttributes = false;
  16736. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16737. this._gl.disableVertexAttribArray(i);
  16738. this._vertexAttribArraysEnabled[i] = false;
  16739. this._currentBufferPointers[i].active = false;
  16740. }
  16741. return;
  16742. }
  16743. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16744. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16745. continue;
  16746. }
  16747. this._gl.disableVertexAttribArray(i);
  16748. this._vertexAttribArraysEnabled[i] = false;
  16749. this._currentBufferPointers[i].active = false;
  16750. }
  16751. };
  16752. /**
  16753. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16754. */
  16755. Engine.prototype.releaseEffects = function () {
  16756. for (var name in this._compiledEffects) {
  16757. this._deleteProgram(this._compiledEffects[name]._program);
  16758. }
  16759. this._compiledEffects = {};
  16760. };
  16761. /**
  16762. * Dispose and release all associated resources
  16763. */
  16764. Engine.prototype.dispose = function () {
  16765. this.hideLoadingUI();
  16766. this.stopRenderLoop();
  16767. // Release postProcesses
  16768. while (this.postProcesses.length) {
  16769. this.postProcesses[0].dispose();
  16770. }
  16771. // Empty texture
  16772. if (this._emptyTexture) {
  16773. this._releaseTexture(this._emptyTexture);
  16774. this._emptyTexture = null;
  16775. }
  16776. if (this._emptyCubeTexture) {
  16777. this._releaseTexture(this._emptyCubeTexture);
  16778. this._emptyCubeTexture = null;
  16779. }
  16780. // Rescale PP
  16781. if (this._rescalePostProcess) {
  16782. this._rescalePostProcess.dispose();
  16783. }
  16784. // Release scenes
  16785. while (this.scenes.length) {
  16786. this.scenes[0].dispose();
  16787. }
  16788. // Release audio engine
  16789. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16790. Engine.audioEngine.dispose();
  16791. }
  16792. // Release effects
  16793. this.releaseEffects();
  16794. // Unbind
  16795. this.unbindAllAttributes();
  16796. this._boundUniforms = [];
  16797. if (this._dummyFramebuffer) {
  16798. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16799. }
  16800. //WebVR
  16801. this.disableVR();
  16802. // Events
  16803. if (BABYLON.Tools.IsWindowObjectExist()) {
  16804. window.removeEventListener("blur", this._onBlur);
  16805. window.removeEventListener("focus", this._onFocus);
  16806. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16807. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16808. if (this._renderingCanvas) {
  16809. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16810. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16811. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16812. if (!this._doNotHandleContextLost) {
  16813. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16814. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16815. }
  16816. }
  16817. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16818. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16819. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16820. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16821. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16822. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16823. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16824. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16825. if (this._onVrDisplayConnect) {
  16826. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16827. if (this._onVrDisplayDisconnect) {
  16828. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16829. }
  16830. if (this._onVrDisplayPresentChange) {
  16831. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16832. }
  16833. this._onVrDisplayConnect = null;
  16834. this._onVrDisplayDisconnect = null;
  16835. }
  16836. }
  16837. // Remove from Instances
  16838. var index = Engine.Instances.indexOf(this);
  16839. if (index >= 0) {
  16840. Engine.Instances.splice(index, 1);
  16841. }
  16842. this._workingCanvas = null;
  16843. this._workingContext = null;
  16844. this._currentBufferPointers = [];
  16845. this._renderingCanvas = null;
  16846. this._currentProgram = null;
  16847. this._bindedRenderFunction = null;
  16848. this.onResizeObservable.clear();
  16849. this.onCanvasBlurObservable.clear();
  16850. this.onCanvasFocusObservable.clear();
  16851. this.onCanvasPointerOutObservable.clear();
  16852. this.onBeginFrameObservable.clear();
  16853. this.onEndFrameObservable.clear();
  16854. BABYLON.Effect.ResetCache();
  16855. // Abort active requests
  16856. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16857. var request = _a[_i];
  16858. request.abort();
  16859. }
  16860. };
  16861. // Loading screen
  16862. /**
  16863. * Display the loading screen
  16864. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16865. */
  16866. Engine.prototype.displayLoadingUI = function () {
  16867. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16868. return;
  16869. }
  16870. var loadingScreen = this.loadingScreen;
  16871. if (loadingScreen) {
  16872. loadingScreen.displayLoadingUI();
  16873. }
  16874. };
  16875. /**
  16876. * Hide the loading screen
  16877. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16878. */
  16879. Engine.prototype.hideLoadingUI = function () {
  16880. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16881. return;
  16882. }
  16883. var loadingScreen = this.loadingScreen;
  16884. if (loadingScreen) {
  16885. loadingScreen.hideLoadingUI();
  16886. }
  16887. };
  16888. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16889. /**
  16890. * Gets the current loading screen object
  16891. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16892. */
  16893. get: function () {
  16894. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16895. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16896. return this._loadingScreen;
  16897. },
  16898. /**
  16899. * Sets the current loading screen object
  16900. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16901. */
  16902. set: function (loadingScreen) {
  16903. this._loadingScreen = loadingScreen;
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16909. /**
  16910. * Sets the current loading screen text
  16911. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16912. */
  16913. set: function (text) {
  16914. this.loadingScreen.loadingUIText = text;
  16915. },
  16916. enumerable: true,
  16917. configurable: true
  16918. });
  16919. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16920. /**
  16921. * Sets the current loading screen background color
  16922. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16923. */
  16924. set: function (color) {
  16925. this.loadingScreen.loadingUIBackgroundColor = color;
  16926. },
  16927. enumerable: true,
  16928. configurable: true
  16929. });
  16930. /**
  16931. * Attach a new callback raised when context lost event is fired
  16932. * @param callback defines the callback to call
  16933. */
  16934. Engine.prototype.attachContextLostEvent = function (callback) {
  16935. if (this._renderingCanvas) {
  16936. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16937. }
  16938. };
  16939. /**
  16940. * Attach a new callback raised when context restored event is fired
  16941. * @param callback defines the callback to call
  16942. */
  16943. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16944. if (this._renderingCanvas) {
  16945. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16946. }
  16947. };
  16948. /**
  16949. * Gets the source code of the vertex shader associated with a specific webGL program
  16950. * @param program defines the program to use
  16951. * @returns a string containing the source code of the vertex shader associated with the program
  16952. */
  16953. Engine.prototype.getVertexShaderSource = function (program) {
  16954. var shaders = this._gl.getAttachedShaders(program);
  16955. if (!shaders) {
  16956. return null;
  16957. }
  16958. return this._gl.getShaderSource(shaders[0]);
  16959. };
  16960. /**
  16961. * Gets the source code of the fragment shader associated with a specific webGL program
  16962. * @param program defines the program to use
  16963. * @returns a string containing the source code of the fragment shader associated with the program
  16964. */
  16965. Engine.prototype.getFragmentShaderSource = function (program) {
  16966. var shaders = this._gl.getAttachedShaders(program);
  16967. if (!shaders) {
  16968. return null;
  16969. }
  16970. return this._gl.getShaderSource(shaders[1]);
  16971. };
  16972. /**
  16973. * Get the current error code of the webGL context
  16974. * @returns the error code
  16975. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16976. */
  16977. Engine.prototype.getError = function () {
  16978. return this._gl.getError();
  16979. };
  16980. // FPS
  16981. /**
  16982. * Gets the current framerate
  16983. * @returns a number representing the framerate
  16984. */
  16985. Engine.prototype.getFps = function () {
  16986. return this._fps;
  16987. };
  16988. /**
  16989. * Gets the time spent between current and previous frame
  16990. * @returns a number representing the delta time in ms
  16991. */
  16992. Engine.prototype.getDeltaTime = function () {
  16993. return this._deltaTime;
  16994. };
  16995. Engine.prototype._measureFps = function () {
  16996. this._performanceMonitor.sampleFrame();
  16997. this._fps = this._performanceMonitor.averageFPS;
  16998. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16999. };
  17000. /** @hidden */
  17001. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17002. if (faceIndex === void 0) { faceIndex = -1; }
  17003. if (level === void 0) { level = 0; }
  17004. if (buffer === void 0) { buffer = null; }
  17005. var gl = this._gl;
  17006. if (!this._dummyFramebuffer) {
  17007. var dummy = gl.createFramebuffer();
  17008. if (!dummy) {
  17009. throw new Error("Unable to create dummy framebuffer");
  17010. }
  17011. this._dummyFramebuffer = dummy;
  17012. }
  17013. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17014. if (faceIndex > -1) {
  17015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17016. }
  17017. else {
  17018. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17019. }
  17020. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17021. switch (readType) {
  17022. case gl.UNSIGNED_BYTE:
  17023. if (!buffer) {
  17024. buffer = new Uint8Array(4 * width * height);
  17025. }
  17026. readType = gl.UNSIGNED_BYTE;
  17027. break;
  17028. default:
  17029. if (!buffer) {
  17030. buffer = new Float32Array(4 * width * height);
  17031. }
  17032. readType = gl.FLOAT;
  17033. break;
  17034. }
  17035. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17036. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17037. return buffer;
  17038. };
  17039. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17040. if (this._webGLVersion > 1) {
  17041. return this._caps.colorBufferFloat;
  17042. }
  17043. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17044. };
  17045. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17046. if (this._webGLVersion > 1) {
  17047. return this._caps.colorBufferFloat;
  17048. }
  17049. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17050. };
  17051. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17052. Engine.prototype._canRenderToFramebuffer = function (type) {
  17053. var gl = this._gl;
  17054. //clear existing errors
  17055. while (gl.getError() !== gl.NO_ERROR) { }
  17056. var successful = true;
  17057. var texture = gl.createTexture();
  17058. gl.bindTexture(gl.TEXTURE_2D, texture);
  17059. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17062. var fb = gl.createFramebuffer();
  17063. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17064. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17065. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17066. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17067. successful = successful && (gl.getError() === gl.NO_ERROR);
  17068. //try render by clearing frame buffer's color buffer
  17069. if (successful) {
  17070. gl.clear(gl.COLOR_BUFFER_BIT);
  17071. successful = successful && (gl.getError() === gl.NO_ERROR);
  17072. }
  17073. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17074. if (successful) {
  17075. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17076. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17077. var readFormat = gl.RGBA;
  17078. var readType = gl.UNSIGNED_BYTE;
  17079. var buffer = new Uint8Array(4);
  17080. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17081. successful = successful && (gl.getError() === gl.NO_ERROR);
  17082. }
  17083. //clean up
  17084. gl.deleteTexture(texture);
  17085. gl.deleteFramebuffer(fb);
  17086. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17087. //clear accumulated errors
  17088. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17089. return successful;
  17090. };
  17091. /** @hidden */
  17092. Engine.prototype._getWebGLTextureType = function (type) {
  17093. if (this._webGLVersion === 1) {
  17094. switch (type) {
  17095. case Engine.TEXTURETYPE_FLOAT:
  17096. return this._gl.FLOAT;
  17097. case Engine.TEXTURETYPE_HALF_FLOAT:
  17098. return this._gl.HALF_FLOAT_OES;
  17099. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17100. return this._gl.UNSIGNED_BYTE;
  17101. }
  17102. return this._gl.UNSIGNED_BYTE;
  17103. }
  17104. switch (type) {
  17105. case Engine.TEXTURETYPE_BYTE:
  17106. return this._gl.BYTE;
  17107. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17108. return this._gl.UNSIGNED_BYTE;
  17109. case Engine.TEXTURETYPE_SHORT:
  17110. return this._gl.SHORT;
  17111. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17112. return this._gl.UNSIGNED_SHORT;
  17113. case Engine.TEXTURETYPE_INT:
  17114. return this._gl.INT;
  17115. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17116. return this._gl.UNSIGNED_INT;
  17117. case Engine.TEXTURETYPE_FLOAT:
  17118. return this._gl.FLOAT;
  17119. case Engine.TEXTURETYPE_HALF_FLOAT:
  17120. return this._gl.HALF_FLOAT;
  17121. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17122. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17123. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17124. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17125. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17126. return this._gl.UNSIGNED_SHORT_5_6_5;
  17127. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17128. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17129. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17130. return this._gl.UNSIGNED_INT_24_8;
  17131. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17132. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17133. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17134. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17135. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17136. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17137. }
  17138. return this._gl.UNSIGNED_BYTE;
  17139. };
  17140. ;
  17141. Engine.prototype._getInternalFormat = function (format) {
  17142. var internalFormat = this._gl.RGBA;
  17143. switch (format) {
  17144. case Engine.TEXTUREFORMAT_ALPHA:
  17145. internalFormat = this._gl.ALPHA;
  17146. break;
  17147. case Engine.TEXTUREFORMAT_LUMINANCE:
  17148. internalFormat = this._gl.LUMINANCE;
  17149. break;
  17150. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17151. internalFormat = this._gl.LUMINANCE_ALPHA;
  17152. break;
  17153. case Engine.TEXTUREFORMAT_RED:
  17154. internalFormat = this._gl.RED;
  17155. break;
  17156. case Engine.TEXTUREFORMAT_RG:
  17157. internalFormat = this._gl.RG;
  17158. break;
  17159. case Engine.TEXTUREFORMAT_RGB:
  17160. internalFormat = this._gl.RGB;
  17161. break;
  17162. case Engine.TEXTUREFORMAT_RGBA:
  17163. internalFormat = this._gl.RGBA;
  17164. break;
  17165. }
  17166. if (this._webGLVersion > 1) {
  17167. switch (format) {
  17168. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17169. internalFormat = this._gl.RED_INTEGER;
  17170. break;
  17171. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17172. internalFormat = this._gl.RG_INTEGER;
  17173. break;
  17174. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17175. internalFormat = this._gl.RGB_INTEGER;
  17176. break;
  17177. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17178. internalFormat = this._gl.RGBA_INTEGER;
  17179. break;
  17180. }
  17181. }
  17182. return internalFormat;
  17183. };
  17184. /** @hidden */
  17185. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17186. if (this._webGLVersion === 1) {
  17187. if (format !== undefined) {
  17188. switch (format) {
  17189. case Engine.TEXTUREFORMAT_ALPHA:
  17190. return this._gl.ALPHA;
  17191. case Engine.TEXTUREFORMAT_LUMINANCE:
  17192. return this._gl.LUMINANCE;
  17193. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17194. return this._gl.LUMINANCE_ALPHA;
  17195. }
  17196. }
  17197. return this._gl.RGBA;
  17198. }
  17199. switch (type) {
  17200. case Engine.TEXTURETYPE_BYTE:
  17201. switch (format) {
  17202. case Engine.TEXTUREFORMAT_RED:
  17203. return this._gl.R8_SNORM;
  17204. case Engine.TEXTUREFORMAT_RG:
  17205. return this._gl.RG8_SNORM;
  17206. case Engine.TEXTUREFORMAT_RGB:
  17207. return this._gl.RGB8_SNORM;
  17208. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17209. return this._gl.R8I;
  17210. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17211. return this._gl.RG8I;
  17212. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17213. return this._gl.RGB8I;
  17214. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17215. return this._gl.RGBA8I;
  17216. default:
  17217. return this._gl.RGBA8_SNORM;
  17218. }
  17219. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17220. switch (format) {
  17221. case Engine.TEXTUREFORMAT_RED:
  17222. return this._gl.R8;
  17223. case Engine.TEXTUREFORMAT_RG:
  17224. return this._gl.RG8;
  17225. case Engine.TEXTUREFORMAT_RGB:
  17226. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17227. case Engine.TEXTUREFORMAT_RGBA:
  17228. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17229. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17230. return this._gl.R8UI;
  17231. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17232. return this._gl.RG8UI;
  17233. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17234. return this._gl.RGB8UI;
  17235. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17236. return this._gl.RGBA8UI;
  17237. default:
  17238. return this._gl.RGBA8;
  17239. }
  17240. case Engine.TEXTURETYPE_SHORT:
  17241. switch (format) {
  17242. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17243. return this._gl.R16I;
  17244. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17245. return this._gl.RG16I;
  17246. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17247. return this._gl.RGB16I;
  17248. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17249. return this._gl.RGBA16I;
  17250. default:
  17251. return this._gl.RGBA16I;
  17252. }
  17253. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17254. switch (format) {
  17255. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17256. return this._gl.R16UI;
  17257. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17258. return this._gl.RG16UI;
  17259. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17260. return this._gl.RGB16UI;
  17261. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17262. return this._gl.RGBA16UI;
  17263. default:
  17264. return this._gl.RGBA16UI;
  17265. }
  17266. case Engine.TEXTURETYPE_INT:
  17267. switch (format) {
  17268. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17269. return this._gl.R32I;
  17270. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17271. return this._gl.RG32I;
  17272. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17273. return this._gl.RGB32I;
  17274. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17275. return this._gl.RGBA32I;
  17276. default:
  17277. return this._gl.RGBA32I;
  17278. }
  17279. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17280. switch (format) {
  17281. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17282. return this._gl.R32UI;
  17283. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17284. return this._gl.RG32UI;
  17285. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17286. return this._gl.RGB32UI;
  17287. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17288. return this._gl.RGBA32UI;
  17289. default:
  17290. return this._gl.RGBA32UI;
  17291. }
  17292. case Engine.TEXTURETYPE_FLOAT:
  17293. switch (format) {
  17294. case Engine.TEXTUREFORMAT_RED:
  17295. return this._gl.R32F; // By default. Other possibility is R16F.
  17296. case Engine.TEXTUREFORMAT_RG:
  17297. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17298. case Engine.TEXTUREFORMAT_RGB:
  17299. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17300. case Engine.TEXTUREFORMAT_RGBA:
  17301. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17302. default:
  17303. return this._gl.RGBA32F;
  17304. }
  17305. case Engine.TEXTURETYPE_HALF_FLOAT:
  17306. switch (format) {
  17307. case Engine.TEXTUREFORMAT_RED:
  17308. return this._gl.R16F;
  17309. case Engine.TEXTUREFORMAT_RG:
  17310. return this._gl.RG16F;
  17311. case Engine.TEXTUREFORMAT_RGB:
  17312. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17313. case Engine.TEXTUREFORMAT_RGBA:
  17314. return this._gl.RGBA16F;
  17315. default:
  17316. return this._gl.RGBA16F;
  17317. }
  17318. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17319. return this._gl.RGB565;
  17320. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17321. return this._gl.R11F_G11F_B10F;
  17322. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17323. return this._gl.RGB9_E5;
  17324. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17325. return this._gl.RGBA4;
  17326. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17327. return this._gl.RGB5_A1;
  17328. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17329. switch (format) {
  17330. case Engine.TEXTUREFORMAT_RGBA:
  17331. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17332. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17333. return this._gl.RGB10_A2UI;
  17334. default:
  17335. return this._gl.RGB10_A2;
  17336. }
  17337. }
  17338. return this._gl.RGBA8;
  17339. };
  17340. ;
  17341. /** @hidden */
  17342. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17343. if (type === Engine.TEXTURETYPE_FLOAT) {
  17344. return this._gl.RGBA32F;
  17345. }
  17346. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17347. return this._gl.RGBA16F;
  17348. }
  17349. return this._gl.RGBA8;
  17350. };
  17351. ;
  17352. /** @hidden */
  17353. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17354. var _this = this;
  17355. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17356. this._activeRequests.push(request);
  17357. request.onCompleteObservable.add(function (request) {
  17358. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17359. });
  17360. return request;
  17361. };
  17362. /** @hidden */
  17363. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17364. var _this = this;
  17365. return new Promise(function (resolve, reject) {
  17366. _this._loadFile(url, function (data) {
  17367. resolve(data);
  17368. }, undefined, database, useArrayBuffer, function (request, exception) {
  17369. reject(exception);
  17370. });
  17371. });
  17372. };
  17373. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17374. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17375. var onload = function (data) {
  17376. loadedFiles[index] = data;
  17377. loadedFiles._internalCount++;
  17378. if (loadedFiles._internalCount === 6) {
  17379. onfinish(loadedFiles);
  17380. }
  17381. };
  17382. var onerror = function (request, exception) {
  17383. if (onErrorCallBack && request) {
  17384. onErrorCallBack(request.status + " " + request.statusText, exception);
  17385. }
  17386. };
  17387. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17388. };
  17389. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17390. if (onError === void 0) { onError = null; }
  17391. var loadedFiles = [];
  17392. loadedFiles._internalCount = 0;
  17393. for (var index = 0; index < 6; index++) {
  17394. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17395. }
  17396. };
  17397. // Statics
  17398. /**
  17399. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17400. * @returns true if the engine can be created
  17401. * @ignorenaming
  17402. */
  17403. Engine.isSupported = function () {
  17404. try {
  17405. var tempcanvas = document.createElement("canvas");
  17406. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17407. return gl != null && !!window.WebGLRenderingContext;
  17408. }
  17409. catch (e) {
  17410. return false;
  17411. }
  17412. };
  17413. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17414. Engine.ExceptionList = [
  17415. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17416. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17417. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17418. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17419. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17420. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17421. ];
  17422. /** Gets the list of created engines */
  17423. Engine.Instances = new Array();
  17424. /**
  17425. * Hidden
  17426. */
  17427. Engine._TextureLoaders = [];
  17428. // Const statics
  17429. /** Defines that alpha blending is disabled */
  17430. Engine.ALPHA_DISABLE = 0;
  17431. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17432. Engine.ALPHA_ADD = 1;
  17433. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17434. Engine.ALPHA_COMBINE = 2;
  17435. /** Defines that alpha blending to DEST - SRC * DEST */
  17436. Engine.ALPHA_SUBTRACT = 3;
  17437. /** Defines that alpha blending to SRC * DEST */
  17438. Engine.ALPHA_MULTIPLY = 4;
  17439. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17440. Engine.ALPHA_MAXIMIZED = 5;
  17441. /** Defines that alpha blending to SRC + DEST */
  17442. Engine.ALPHA_ONEONE = 6;
  17443. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17444. Engine.ALPHA_PREMULTIPLIED = 7;
  17445. /**
  17446. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17447. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17448. */
  17449. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17450. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17451. Engine.ALPHA_INTERPOLATE = 9;
  17452. /**
  17453. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17454. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17455. */
  17456. Engine.ALPHA_SCREENMODE = 10;
  17457. /** Defines that the ressource is not delayed*/
  17458. Engine.DELAYLOADSTATE_NONE = 0;
  17459. /** Defines that the ressource was successfully delay loaded */
  17460. Engine.DELAYLOADSTATE_LOADED = 1;
  17461. /** Defines that the ressource is currently delay loading */
  17462. Engine.DELAYLOADSTATE_LOADING = 2;
  17463. /** Defines that the ressource is delayed and has not started loading */
  17464. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17465. // Depht or Stencil test Constants.
  17466. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17467. Engine.NEVER = 0x0200;
  17468. /** 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 */
  17469. Engine.ALWAYS = 0x0207;
  17470. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17471. Engine.LESS = 0x0201;
  17472. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17473. Engine.EQUAL = 0x0202;
  17474. /** 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 */
  17475. Engine.LEQUAL = 0x0203;
  17476. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17477. Engine.GREATER = 0x0204;
  17478. /** 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 */
  17479. Engine.GEQUAL = 0x0206;
  17480. /** 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 */
  17481. Engine.NOTEQUAL = 0x0205;
  17482. // Stencil Actions Constants.
  17483. /** Passed to stencilOperation to specify that stencil value must be kept */
  17484. Engine.KEEP = 0x1E00;
  17485. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17486. Engine.REPLACE = 0x1E01;
  17487. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17488. Engine.INCR = 0x1E02;
  17489. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17490. Engine.DECR = 0x1E03;
  17491. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17492. Engine.INVERT = 0x150A;
  17493. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17494. Engine.INCR_WRAP = 0x8507;
  17495. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17496. Engine.DECR_WRAP = 0x8508;
  17497. /** Texture is not repeating outside of 0..1 UVs */
  17498. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17499. /** Texture is repeating outside of 0..1 UVs */
  17500. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17501. /** Texture is repeating and mirrored */
  17502. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17503. /** ALPHA */
  17504. Engine.TEXTUREFORMAT_ALPHA = 0;
  17505. /** LUMINANCE */
  17506. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17507. /** LUMINANCE_ALPHA */
  17508. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17509. /** RGB */
  17510. Engine.TEXTUREFORMAT_RGB = 4;
  17511. /** RGBA */
  17512. Engine.TEXTUREFORMAT_RGBA = 5;
  17513. /** RED */
  17514. Engine.TEXTUREFORMAT_RED = 6;
  17515. /** RED (2nd reference) */
  17516. Engine.TEXTUREFORMAT_R = 6;
  17517. /** RG */
  17518. Engine.TEXTUREFORMAT_RG = 7;
  17519. /** RED_INTEGER */
  17520. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17521. /** RED_INTEGER (2nd reference) */
  17522. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17523. /** RG_INTEGER */
  17524. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17525. /** RGB_INTEGER */
  17526. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17527. /** RGBA_INTEGER */
  17528. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17529. /** UNSIGNED_BYTE */
  17530. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17531. /** UNSIGNED_BYTE (2nd reference) */
  17532. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17533. /** FLOAT */
  17534. Engine.TEXTURETYPE_FLOAT = 1;
  17535. /** HALF_FLOAT */
  17536. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17537. /** BYTE */
  17538. Engine.TEXTURETYPE_BYTE = 3;
  17539. /** SHORT */
  17540. Engine.TEXTURETYPE_SHORT = 4;
  17541. /** UNSIGNED_SHORT */
  17542. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17543. /** INT */
  17544. Engine.TEXTURETYPE_INT = 6;
  17545. /** UNSIGNED_INT */
  17546. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17547. /** UNSIGNED_SHORT_4_4_4_4 */
  17548. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17549. /** UNSIGNED_SHORT_5_5_5_1 */
  17550. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17551. /** UNSIGNED_SHORT_5_6_5 */
  17552. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17553. /** UNSIGNED_INT_2_10_10_10_REV */
  17554. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17555. /** UNSIGNED_INT_24_8 */
  17556. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17557. /** UNSIGNED_INT_10F_11F_11F_REV */
  17558. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17559. /** UNSIGNED_INT_5_9_9_9_REV */
  17560. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17561. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17562. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17563. /** nearest is mag = nearest and min = nearest and mip = linear */
  17564. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17565. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17566. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17567. /** Trilinear is mag = linear and min = linear and mip = linear */
  17568. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17569. /** nearest is mag = nearest and min = nearest and mip = linear */
  17570. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17571. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17572. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17573. /** Trilinear is mag = linear and min = linear and mip = linear */
  17574. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17575. /** mag = nearest and min = nearest and mip = nearest */
  17576. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17577. /** mag = nearest and min = linear and mip = nearest */
  17578. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17579. /** mag = nearest and min = linear and mip = linear */
  17580. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17581. /** mag = nearest and min = linear and mip = none */
  17582. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17583. /** mag = nearest and min = nearest and mip = none */
  17584. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17585. /** mag = linear and min = nearest and mip = nearest */
  17586. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17587. /** mag = linear and min = nearest and mip = linear */
  17588. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17589. /** mag = linear and min = linear and mip = none */
  17590. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17591. /** mag = linear and min = nearest and mip = none */
  17592. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17593. /** Explicit coordinates mode */
  17594. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17595. /** Spherical coordinates mode */
  17596. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17597. /** Planar coordinates mode */
  17598. Engine.TEXTURE_PLANAR_MODE = 2;
  17599. /** Cubic coordinates mode */
  17600. Engine.TEXTURE_CUBIC_MODE = 3;
  17601. /** Projection coordinates mode */
  17602. Engine.TEXTURE_PROJECTION_MODE = 4;
  17603. /** Skybox coordinates mode */
  17604. Engine.TEXTURE_SKYBOX_MODE = 5;
  17605. /** Inverse Cubic coordinates mode */
  17606. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17607. /** Equirectangular coordinates mode */
  17608. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17609. /** Equirectangular Fixed coordinates mode */
  17610. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17611. /** Equirectangular Fixed Mirrored coordinates mode */
  17612. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17613. // Texture rescaling mode
  17614. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17615. Engine.SCALEMODE_FLOOR = 1;
  17616. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17617. Engine.SCALEMODE_NEAREST = 2;
  17618. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17619. Engine.SCALEMODE_CEILING = 3;
  17620. // Updatable statics so stick with vars here
  17621. /**
  17622. * Gets or sets the epsilon value used by collision engine
  17623. */
  17624. Engine.CollisionsEpsilon = 0.001;
  17625. /**
  17626. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17627. */
  17628. Engine.CodeRepository = "src/";
  17629. /**
  17630. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17631. */
  17632. Engine.ShadersRepository = "src/Shaders/";
  17633. return Engine;
  17634. }());
  17635. BABYLON.Engine = Engine;
  17636. })(BABYLON || (BABYLON = {}));
  17637. //# sourceMappingURL=babylon.engine.js.map
  17638. var BABYLON;
  17639. (function (BABYLON) {
  17640. /**
  17641. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17642. */
  17643. var Node = /** @class */ (function () {
  17644. /**
  17645. * Creates a new Node
  17646. * @param {string} name - the name and id to be given to this node
  17647. * @param {BABYLON.Scene} the scene this node will be added to
  17648. */
  17649. function Node(name, scene) {
  17650. if (scene === void 0) { scene = null; }
  17651. /**
  17652. * Gets or sets a string used to store user defined state for the node
  17653. */
  17654. this.state = "";
  17655. /**
  17656. * Gets or sets an object used to store user defined information for the node
  17657. */
  17658. this.metadata = null;
  17659. /**
  17660. * Gets or sets a boolean used to define if the node must be serialized
  17661. */
  17662. this.doNotSerialize = false;
  17663. /** @hidden */
  17664. this._isDisposed = false;
  17665. /**
  17666. * Gets a list of Animations associated with the node
  17667. */
  17668. this.animations = new Array();
  17669. this._ranges = {};
  17670. this._isEnabled = true;
  17671. this._isParentEnabled = true;
  17672. this._isReady = true;
  17673. /** @hidden */
  17674. this._currentRenderId = -1;
  17675. this._parentRenderId = -1;
  17676. this._childRenderId = -1;
  17677. /** @hidden */
  17678. this._worldMatrix = BABYLON.Matrix.Identity();
  17679. /** @hidden */
  17680. this._worldMatrixDeterminant = 0;
  17681. this._animationPropertiesOverride = null;
  17682. /**
  17683. * An event triggered when the mesh is disposed
  17684. */
  17685. this.onDisposeObservable = new BABYLON.Observable();
  17686. // Behaviors
  17687. this._behaviors = new Array();
  17688. this.name = name;
  17689. this.id = name;
  17690. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17691. this.uniqueId = this._scene.getUniqueId();
  17692. this._initCache();
  17693. this._scene.rootNodes.push(this);
  17694. }
  17695. /**
  17696. * Add a new node constructor
  17697. * @param type defines the type name of the node to construct
  17698. * @param constructorFunc defines the constructor function
  17699. */
  17700. Node.AddNodeConstructor = function (type, constructorFunc) {
  17701. this._NodeConstructors[type] = constructorFunc;
  17702. };
  17703. /**
  17704. * Returns a node constructor based on type name
  17705. * @param type defines the type name
  17706. * @param name defines the new node name
  17707. * @param scene defines the hosting scene
  17708. * @param options defines optional options to transmit to constructors
  17709. * @returns the new constructor or null
  17710. */
  17711. Node.Construct = function (type, name, scene, options) {
  17712. var constructorFunc = this._NodeConstructors[type];
  17713. if (!constructorFunc) {
  17714. return null;
  17715. }
  17716. return constructorFunc(name, scene, options);
  17717. };
  17718. /**
  17719. * Gets a boolean indicating if the node has been disposed
  17720. * @returns true if the node was disposed
  17721. */
  17722. Node.prototype.isDisposed = function () {
  17723. return this._isDisposed;
  17724. };
  17725. Object.defineProperty(Node.prototype, "parent", {
  17726. get: function () {
  17727. return this._parentNode;
  17728. },
  17729. /**
  17730. * Gets or sets the parent of the node
  17731. */
  17732. set: function (parent) {
  17733. if (this._parentNode === parent) {
  17734. return;
  17735. }
  17736. var previousParentNode = this._parentNode;
  17737. // Remove self from list of children of parent
  17738. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17739. var index = this._parentNode._children.indexOf(this);
  17740. if (index !== -1) {
  17741. this._parentNode._children.splice(index, 1);
  17742. }
  17743. if (!parent) {
  17744. // Need to add this node to the rootNodes
  17745. this._scene.rootNodes.push(this);
  17746. }
  17747. }
  17748. // Store new parent
  17749. this._parentNode = parent;
  17750. // Add as child to new parent
  17751. if (this._parentNode) {
  17752. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17753. this._parentNode._children = new Array();
  17754. }
  17755. this._parentNode._children.push(this);
  17756. if (!previousParentNode) {
  17757. // Need to remove from rootNodes
  17758. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17759. if (rootNodeIndex > -1) {
  17760. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17761. }
  17762. }
  17763. }
  17764. // Enabled state
  17765. this._syncParentEnabledState();
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17771. /**
  17772. * Gets or sets the animation properties override
  17773. */
  17774. get: function () {
  17775. if (!this._animationPropertiesOverride) {
  17776. return this._scene.animationPropertiesOverride;
  17777. }
  17778. return this._animationPropertiesOverride;
  17779. },
  17780. set: function (value) {
  17781. this._animationPropertiesOverride = value;
  17782. },
  17783. enumerable: true,
  17784. configurable: true
  17785. });
  17786. /**
  17787. * Gets a string idenfifying the name of the class
  17788. * @returns "Node" string
  17789. */
  17790. Node.prototype.getClassName = function () {
  17791. return "Node";
  17792. };
  17793. Object.defineProperty(Node.prototype, "onDispose", {
  17794. /**
  17795. * Sets a callback that will be raised when the node will be disposed
  17796. */
  17797. set: function (callback) {
  17798. if (this._onDisposeObserver) {
  17799. this.onDisposeObservable.remove(this._onDisposeObserver);
  17800. }
  17801. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17802. },
  17803. enumerable: true,
  17804. configurable: true
  17805. });
  17806. /**
  17807. * Gets the scene of the node
  17808. * @returns a {BABYLON.Scene}
  17809. */
  17810. Node.prototype.getScene = function () {
  17811. return this._scene;
  17812. };
  17813. /**
  17814. * Gets the engine of the node
  17815. * @returns a {BABYLON.Engine}
  17816. */
  17817. Node.prototype.getEngine = function () {
  17818. return this._scene.getEngine();
  17819. };
  17820. /**
  17821. * Attach a behavior to the node
  17822. * @see http://doc.babylonjs.com/features/behaviour
  17823. * @param behavior defines the behavior to attach
  17824. * @returns the current Node
  17825. */
  17826. Node.prototype.addBehavior = function (behavior) {
  17827. var _this = this;
  17828. var index = this._behaviors.indexOf(behavior);
  17829. if (index !== -1) {
  17830. return this;
  17831. }
  17832. behavior.init();
  17833. if (this._scene.isLoading) {
  17834. // We defer the attach when the scene will be loaded
  17835. this._scene.onDataLoadedObservable.addOnce(function () {
  17836. behavior.attach(_this);
  17837. });
  17838. }
  17839. else {
  17840. behavior.attach(this);
  17841. }
  17842. this._behaviors.push(behavior);
  17843. return this;
  17844. };
  17845. /**
  17846. * Remove an attached behavior
  17847. * @see http://doc.babylonjs.com/features/behaviour
  17848. * @param behavior defines the behavior to attach
  17849. * @returns the current Node
  17850. */
  17851. Node.prototype.removeBehavior = function (behavior) {
  17852. var index = this._behaviors.indexOf(behavior);
  17853. if (index === -1) {
  17854. return this;
  17855. }
  17856. this._behaviors[index].detach();
  17857. this._behaviors.splice(index, 1);
  17858. return this;
  17859. };
  17860. Object.defineProperty(Node.prototype, "behaviors", {
  17861. /**
  17862. * Gets the list of attached behaviors
  17863. * @see http://doc.babylonjs.com/features/behaviour
  17864. */
  17865. get: function () {
  17866. return this._behaviors;
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. /**
  17872. * Gets an attached behavior by name
  17873. * @param name defines the name of the behavior to look for
  17874. * @see http://doc.babylonjs.com/features/behaviour
  17875. * @returns null if behavior was not found else the requested behavior
  17876. */
  17877. Node.prototype.getBehaviorByName = function (name) {
  17878. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17879. var behavior = _a[_i];
  17880. if (behavior.name === name) {
  17881. return behavior;
  17882. }
  17883. }
  17884. return null;
  17885. };
  17886. /**
  17887. * Returns the latest update of the World matrix
  17888. * @returns a Matrix
  17889. */
  17890. Node.prototype.getWorldMatrix = function () {
  17891. if (this._currentRenderId !== this._scene.getRenderId()) {
  17892. this.computeWorldMatrix();
  17893. }
  17894. return this._worldMatrix;
  17895. };
  17896. /** @hidden */
  17897. Node.prototype._getWorldMatrixDeterminant = function () {
  17898. return this._worldMatrixDeterminant;
  17899. };
  17900. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17901. /**
  17902. * Returns directly the latest state of the mesh World matrix.
  17903. * A Matrix is returned.
  17904. */
  17905. get: function () {
  17906. return this._worldMatrix;
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. // override it in derived class if you add new variables to the cache
  17912. // and call the parent class method
  17913. /** @hidden */
  17914. Node.prototype._initCache = function () {
  17915. this._cache = {};
  17916. this._cache.parent = undefined;
  17917. };
  17918. /** @hidden */
  17919. Node.prototype.updateCache = function (force) {
  17920. if (!force && this.isSynchronized())
  17921. return;
  17922. this._cache.parent = this.parent;
  17923. this._updateCache();
  17924. };
  17925. // override it in derived class if you add new variables to the cache
  17926. // and call the parent class method if !ignoreParentClass
  17927. /** @hidden */
  17928. Node.prototype._updateCache = function (ignoreParentClass) {
  17929. };
  17930. // override it in derived class if you add new variables to the cache
  17931. /** @hidden */
  17932. Node.prototype._isSynchronized = function () {
  17933. return true;
  17934. };
  17935. /** @hidden */
  17936. Node.prototype._markSyncedWithParent = function () {
  17937. if (this._parentNode) {
  17938. this._parentRenderId = this._parentNode._childRenderId;
  17939. }
  17940. };
  17941. /** @hidden */
  17942. Node.prototype.isSynchronizedWithParent = function () {
  17943. if (!this._parentNode) {
  17944. return true;
  17945. }
  17946. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17947. return false;
  17948. }
  17949. return this._parentNode.isSynchronized();
  17950. };
  17951. /** @hidden */
  17952. Node.prototype.isSynchronized = function () {
  17953. if (this._cache.parent != this._parentNode) {
  17954. this._cache.parent = this._parentNode;
  17955. return false;
  17956. }
  17957. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17958. return false;
  17959. }
  17960. return this._isSynchronized();
  17961. };
  17962. /**
  17963. * Is this node ready to be used/rendered
  17964. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17965. * @return true if the node is ready
  17966. */
  17967. Node.prototype.isReady = function (completeCheck) {
  17968. if (completeCheck === void 0) { completeCheck = false; }
  17969. return this._isReady;
  17970. };
  17971. /**
  17972. * Is this node enabled?
  17973. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  17974. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  17975. * @return whether this node (and its parent) is enabled
  17976. */
  17977. Node.prototype.isEnabled = function (checkAncestors) {
  17978. if (checkAncestors === void 0) { checkAncestors = true; }
  17979. if (checkAncestors === false) {
  17980. return this._isEnabled;
  17981. }
  17982. if (!this._isEnabled) {
  17983. return false;
  17984. }
  17985. return this._isParentEnabled;
  17986. };
  17987. /** @hidden */
  17988. Node.prototype._syncParentEnabledState = function () {
  17989. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  17990. if (this._children) {
  17991. this._children.forEach(function (c) {
  17992. c._syncParentEnabledState(); // Force children to update accordingly
  17993. });
  17994. }
  17995. };
  17996. /**
  17997. * Set the enabled state of this node
  17998. * @param value defines the new enabled state
  17999. */
  18000. Node.prototype.setEnabled = function (value) {
  18001. this._isEnabled = value;
  18002. this._syncParentEnabledState();
  18003. };
  18004. /**
  18005. * Is this node a descendant of the given node?
  18006. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18007. * @param ancestor defines the parent node to inspect
  18008. * @returns a boolean indicating if this node is a descendant of the given node
  18009. */
  18010. Node.prototype.isDescendantOf = function (ancestor) {
  18011. if (this.parent) {
  18012. if (this.parent === ancestor) {
  18013. return true;
  18014. }
  18015. return this.parent.isDescendantOf(ancestor);
  18016. }
  18017. return false;
  18018. };
  18019. /** @hidden */
  18020. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18021. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18022. if (!this._children) {
  18023. return;
  18024. }
  18025. for (var index = 0; index < this._children.length; index++) {
  18026. var item = this._children[index];
  18027. if (!predicate || predicate(item)) {
  18028. results.push(item);
  18029. }
  18030. if (!directDescendantsOnly) {
  18031. item._getDescendants(results, false, predicate);
  18032. }
  18033. }
  18034. };
  18035. /**
  18036. * Will return all nodes that have this node as ascendant
  18037. * @param directDescendantsOnly defines 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
  18038. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18039. * @return all children nodes of all types
  18040. */
  18041. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18042. var results = new Array();
  18043. this._getDescendants(results, directDescendantsOnly, predicate);
  18044. return results;
  18045. };
  18046. /**
  18047. * Get all child-meshes of this node
  18048. * @param directDescendantsOnly defines 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
  18049. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18050. * @returns an array of {BABYLON.AbstractMesh}
  18051. */
  18052. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18053. var results = [];
  18054. this._getDescendants(results, directDescendantsOnly, function (node) {
  18055. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18056. });
  18057. return results;
  18058. };
  18059. /**
  18060. * Get all child-transformNodes of this node
  18061. * @param directDescendantsOnly defines 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
  18062. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18063. * @returns an array of {BABYLON.TransformNode}
  18064. */
  18065. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18066. var results = [];
  18067. this._getDescendants(results, directDescendantsOnly, function (node) {
  18068. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18069. });
  18070. return results;
  18071. };
  18072. /**
  18073. * Get all direct children of this node
  18074. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18075. * @returns an array of {BABYLON.Node}
  18076. */
  18077. Node.prototype.getChildren = function (predicate) {
  18078. if (!predicate) {
  18079. return this._children;
  18080. }
  18081. return this.getDescendants(true, predicate);
  18082. };
  18083. /** @hidden */
  18084. Node.prototype._setReady = function (state) {
  18085. if (state === this._isReady) {
  18086. return;
  18087. }
  18088. if (!state) {
  18089. this._isReady = false;
  18090. return;
  18091. }
  18092. if (this.onReady) {
  18093. this.onReady(this);
  18094. }
  18095. this._isReady = true;
  18096. };
  18097. /**
  18098. * Get an animation by name
  18099. * @param name defines the name of the animation to look for
  18100. * @returns null if not found else the requested animation
  18101. */
  18102. Node.prototype.getAnimationByName = function (name) {
  18103. for (var i = 0; i < this.animations.length; i++) {
  18104. var animation = this.animations[i];
  18105. if (animation.name === name) {
  18106. return animation;
  18107. }
  18108. }
  18109. return null;
  18110. };
  18111. /**
  18112. * Creates an animation range for this node
  18113. * @param name defines the name of the range
  18114. * @param from defines the starting key
  18115. * @param to defines the end key
  18116. */
  18117. Node.prototype.createAnimationRange = function (name, from, to) {
  18118. // check name not already in use
  18119. if (!this._ranges[name]) {
  18120. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18121. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18122. if (this.animations[i]) {
  18123. this.animations[i].createRange(name, from, to);
  18124. }
  18125. }
  18126. }
  18127. };
  18128. /**
  18129. * Delete a specific animation range
  18130. * @param name defines the name of the range to delete
  18131. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18132. */
  18133. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18134. if (deleteFrames === void 0) { deleteFrames = true; }
  18135. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18136. if (this.animations[i]) {
  18137. this.animations[i].deleteRange(name, deleteFrames);
  18138. }
  18139. }
  18140. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18141. };
  18142. /**
  18143. * Get an animation range by name
  18144. * @param name defines the name of the animation range to look for
  18145. * @returns null if not found else the requested animation range
  18146. */
  18147. Node.prototype.getAnimationRange = function (name) {
  18148. return this._ranges[name];
  18149. };
  18150. /**
  18151. * Will start the animation sequence
  18152. * @param name defines the range frames for animation sequence
  18153. * @param loop defines if the animation should loop (false by default)
  18154. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18155. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18156. * @returns the object created for this animation. If range does not exist, it will return null
  18157. */
  18158. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18159. var range = this.getAnimationRange(name);
  18160. if (!range) {
  18161. return null;
  18162. }
  18163. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18164. };
  18165. /**
  18166. * Serialize animation ranges into a JSON compatible object
  18167. * @returns serialization object
  18168. */
  18169. Node.prototype.serializeAnimationRanges = function () {
  18170. var serializationRanges = [];
  18171. for (var name in this._ranges) {
  18172. var localRange = this._ranges[name];
  18173. if (!localRange) {
  18174. continue;
  18175. }
  18176. var range = {};
  18177. range.name = name;
  18178. range.from = localRange.from;
  18179. range.to = localRange.to;
  18180. serializationRanges.push(range);
  18181. }
  18182. return serializationRanges;
  18183. };
  18184. /**
  18185. * Computes the world matrix of the node
  18186. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18187. * @returns the world matrix
  18188. */
  18189. Node.prototype.computeWorldMatrix = function (force) {
  18190. if (!this._worldMatrix) {
  18191. this._worldMatrix = BABYLON.Matrix.Identity();
  18192. }
  18193. return this._worldMatrix;
  18194. };
  18195. /**
  18196. * Releases resources associated with this node.
  18197. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18198. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18199. */
  18200. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18201. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18202. if (!doNotRecurse) {
  18203. var nodes = this.getDescendants(true);
  18204. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18205. var node = nodes_1[_i];
  18206. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18207. }
  18208. }
  18209. else {
  18210. var transformNodes = this.getChildTransformNodes(true);
  18211. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18212. var transformNode = transformNodes_1[_a];
  18213. transformNode.parent = null;
  18214. transformNode.computeWorldMatrix(true);
  18215. }
  18216. }
  18217. if (!this.parent) {
  18218. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18219. if (rootNodeIndex > -1) {
  18220. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18221. }
  18222. }
  18223. else {
  18224. this.parent = null;
  18225. }
  18226. // Callback
  18227. this.onDisposeObservable.notifyObservers(this);
  18228. this.onDisposeObservable.clear();
  18229. // Behaviors
  18230. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18231. var behavior = _c[_b];
  18232. behavior.detach();
  18233. }
  18234. this._behaviors = [];
  18235. this._isDisposed = true;
  18236. };
  18237. /**
  18238. * Parse animation range data from a serialization object and store them into a given node
  18239. * @param node defines where to store the animation ranges
  18240. * @param parsedNode defines the serialization object to read data from
  18241. * @param scene defines the hosting scene
  18242. */
  18243. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18244. if (parsedNode.ranges) {
  18245. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18246. var data = parsedNode.ranges[index];
  18247. node.createAnimationRange(data.name, data.from, data.to);
  18248. }
  18249. }
  18250. };
  18251. Node._NodeConstructors = {};
  18252. __decorate([
  18253. BABYLON.serialize()
  18254. ], Node.prototype, "name", void 0);
  18255. __decorate([
  18256. BABYLON.serialize()
  18257. ], Node.prototype, "id", void 0);
  18258. __decorate([
  18259. BABYLON.serialize()
  18260. ], Node.prototype, "uniqueId", void 0);
  18261. __decorate([
  18262. BABYLON.serialize()
  18263. ], Node.prototype, "state", void 0);
  18264. __decorate([
  18265. BABYLON.serialize()
  18266. ], Node.prototype, "metadata", void 0);
  18267. return Node;
  18268. }());
  18269. BABYLON.Node = Node;
  18270. })(BABYLON || (BABYLON = {}));
  18271. //# sourceMappingURL=babylon.node.js.map
  18272. var BABYLON;
  18273. (function (BABYLON) {
  18274. // This matrix is used as a value to reset the bounding box.
  18275. var _identityMatrix = BABYLON.Matrix.Identity();
  18276. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18277. var BoundingSphere = /** @class */ (function () {
  18278. /**
  18279. * Creates a new bounding sphere
  18280. * @param min defines the minimum vector (in local space)
  18281. * @param max defines the maximum vector (in local space)
  18282. */
  18283. function BoundingSphere(min, max) {
  18284. this.center = BABYLON.Vector3.Zero();
  18285. this.centerWorld = BABYLON.Vector3.Zero();
  18286. this.reConstruct(min, max);
  18287. }
  18288. /**
  18289. * Recreates the entire bounding sphere from scratch
  18290. * @param min defines the new minimum vector (in local space)
  18291. * @param max defines the new maximum vector (in local space)
  18292. */
  18293. BoundingSphere.prototype.reConstruct = function (min, max) {
  18294. this.minimum = min.clone();
  18295. this.maximum = max.clone();
  18296. var distance = BABYLON.Vector3.Distance(min, max);
  18297. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18298. this.radius = distance * 0.5;
  18299. this.centerWorld.set(0, 0, 0);
  18300. this._update(_identityMatrix);
  18301. };
  18302. /**
  18303. * Scale the current bounding sphere by applying a scale factor
  18304. * @param factor defines the scale factor to apply
  18305. * @returns the current bounding box
  18306. */
  18307. BoundingSphere.prototype.scale = function (factor) {
  18308. var newRadius = this.radius * factor;
  18309. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18310. var min = this.center.subtract(_tempRadiusVector);
  18311. var max = this.center.add(_tempRadiusVector);
  18312. this.reConstruct(min, max);
  18313. return this;
  18314. };
  18315. // Methods
  18316. /** @hidden */
  18317. BoundingSphere.prototype._update = function (world) {
  18318. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18319. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18320. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18321. };
  18322. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18323. for (var i = 0; i < 6; i++) {
  18324. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18325. return false;
  18326. }
  18327. return true;
  18328. };
  18329. BoundingSphere.prototype.intersectsPoint = function (point) {
  18330. var x = this.centerWorld.x - point.x;
  18331. var y = this.centerWorld.y - point.y;
  18332. var z = this.centerWorld.z - point.z;
  18333. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18334. if (this.radiusWorld < distance)
  18335. return false;
  18336. return true;
  18337. };
  18338. // Statics
  18339. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18340. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18341. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18342. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18343. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18344. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18345. return false;
  18346. return true;
  18347. };
  18348. return BoundingSphere;
  18349. }());
  18350. BABYLON.BoundingSphere = BoundingSphere;
  18351. })(BABYLON || (BABYLON = {}));
  18352. //# sourceMappingURL=babylon.boundingSphere.js.map
  18353. var BABYLON;
  18354. (function (BABYLON) {
  18355. var BoundingBox = /** @class */ (function () {
  18356. /**
  18357. * Creates a new bounding box
  18358. * @param min defines the minimum vector (in local space)
  18359. * @param max defines the maximum vector (in local space)
  18360. */
  18361. function BoundingBox(min, max) {
  18362. this.vectorsWorld = new Array();
  18363. this.reConstruct(min, max);
  18364. }
  18365. // Methods
  18366. /**
  18367. * Recreates the entire bounding box from scratch
  18368. * @param min defines the new minimum vector (in local space)
  18369. * @param max defines the new maximum vector (in local space)
  18370. */
  18371. BoundingBox.prototype.reConstruct = function (min, max) {
  18372. this.minimum = min.clone();
  18373. this.maximum = max.clone();
  18374. // Bounding vectors
  18375. this.vectors = [
  18376. this.minimum.clone(),
  18377. this.maximum.clone(),
  18378. this.minimum.clone(),
  18379. this.minimum.clone(),
  18380. this.minimum.clone(),
  18381. this.maximum.clone(),
  18382. this.maximum.clone(),
  18383. this.maximum.clone()
  18384. ];
  18385. this.vectors[2].x = this.maximum.x;
  18386. this.vectors[3].y = this.maximum.y;
  18387. this.vectors[4].z = this.maximum.z;
  18388. this.vectors[5].z = this.minimum.z;
  18389. this.vectors[6].x = this.minimum.x;
  18390. this.vectors[7].y = this.minimum.y;
  18391. // OBB
  18392. this.center = this.maximum.add(this.minimum).scale(0.5);
  18393. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18394. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18395. // World
  18396. for (var index = 0; index < this.vectors.length; index++) {
  18397. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18398. }
  18399. this.minimumWorld = BABYLON.Vector3.Zero();
  18400. this.maximumWorld = BABYLON.Vector3.Zero();
  18401. this.centerWorld = BABYLON.Vector3.Zero();
  18402. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18403. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18404. };
  18405. /**
  18406. * Scale the current bounding box by applying a scale factor
  18407. * @param factor defines the scale factor to apply
  18408. * @returns the current bounding box
  18409. */
  18410. BoundingBox.prototype.scale = function (factor) {
  18411. var diff = this.maximum.subtract(this.minimum);
  18412. var distance = diff.length() * factor;
  18413. diff.normalize();
  18414. var newRadius = diff.scale(distance / 2);
  18415. var min = this.center.subtract(newRadius);
  18416. var max = this.center.add(newRadius);
  18417. this.reConstruct(min, max);
  18418. return this;
  18419. };
  18420. BoundingBox.prototype.getWorldMatrix = function () {
  18421. return this._worldMatrix;
  18422. };
  18423. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18424. this._worldMatrix.copyFrom(matrix);
  18425. return this;
  18426. };
  18427. /** @hidden */
  18428. BoundingBox.prototype._update = function (world) {
  18429. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18430. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18431. for (var index = 0; index < this.vectors.length; index++) {
  18432. var v = this.vectorsWorld[index];
  18433. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18434. if (v.x < this.minimumWorld.x)
  18435. this.minimumWorld.x = v.x;
  18436. if (v.y < this.minimumWorld.y)
  18437. this.minimumWorld.y = v.y;
  18438. if (v.z < this.minimumWorld.z)
  18439. this.minimumWorld.z = v.z;
  18440. if (v.x > this.maximumWorld.x)
  18441. this.maximumWorld.x = v.x;
  18442. if (v.y > this.maximumWorld.y)
  18443. this.maximumWorld.y = v.y;
  18444. if (v.z > this.maximumWorld.z)
  18445. this.maximumWorld.z = v.z;
  18446. }
  18447. // Extend
  18448. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18449. this.extendSizeWorld.scaleInPlace(0.5);
  18450. // OBB
  18451. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18452. this.centerWorld.scaleInPlace(0.5);
  18453. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18454. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18455. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18456. this._worldMatrix = world;
  18457. };
  18458. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18459. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18460. };
  18461. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18462. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18463. };
  18464. BoundingBox.prototype.intersectsPoint = function (point) {
  18465. var delta = -BABYLON.Epsilon;
  18466. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18467. return false;
  18468. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18469. return false;
  18470. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18471. return false;
  18472. return true;
  18473. };
  18474. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18475. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18476. };
  18477. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18478. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18479. return false;
  18480. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18481. return false;
  18482. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18483. return false;
  18484. return true;
  18485. };
  18486. // Statics
  18487. BoundingBox.Intersects = function (box0, box1) {
  18488. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18489. return false;
  18490. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18491. return false;
  18492. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18493. return false;
  18494. return true;
  18495. };
  18496. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18497. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18498. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18499. return (num <= (sphereRadius * sphereRadius));
  18500. };
  18501. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18502. for (var p = 0; p < 6; p++) {
  18503. for (var i = 0; i < 8; i++) {
  18504. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18505. return false;
  18506. }
  18507. }
  18508. }
  18509. return true;
  18510. };
  18511. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18512. for (var p = 0; p < 6; p++) {
  18513. var inCount = 8;
  18514. for (var i = 0; i < 8; i++) {
  18515. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18516. --inCount;
  18517. }
  18518. else {
  18519. break;
  18520. }
  18521. }
  18522. if (inCount === 0)
  18523. return false;
  18524. }
  18525. return true;
  18526. };
  18527. return BoundingBox;
  18528. }());
  18529. BABYLON.BoundingBox = BoundingBox;
  18530. })(BABYLON || (BABYLON = {}));
  18531. //# sourceMappingURL=babylon.boundingBox.js.map
  18532. var BABYLON;
  18533. (function (BABYLON) {
  18534. var computeBoxExtents = function (axis, box) {
  18535. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18536. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18537. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18538. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18539. var r = r0 + r1 + r2;
  18540. return {
  18541. min: p - r,
  18542. max: p + r
  18543. };
  18544. };
  18545. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18546. var axisOverlap = function (axis, box0, box1) {
  18547. var result0 = computeBoxExtents(axis, box0);
  18548. var result1 = computeBoxExtents(axis, box1);
  18549. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18550. };
  18551. var BoundingInfo = /** @class */ (function () {
  18552. function BoundingInfo(minimum, maximum) {
  18553. this.minimum = minimum;
  18554. this.maximum = maximum;
  18555. this._isLocked = false;
  18556. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18557. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18558. }
  18559. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18560. get: function () {
  18561. return this._isLocked;
  18562. },
  18563. set: function (value) {
  18564. this._isLocked = value;
  18565. },
  18566. enumerable: true,
  18567. configurable: true
  18568. });
  18569. // Methods
  18570. BoundingInfo.prototype.update = function (world) {
  18571. if (this._isLocked) {
  18572. return;
  18573. }
  18574. this.boundingBox._update(world);
  18575. this.boundingSphere._update(world);
  18576. };
  18577. /**
  18578. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18579. * @param center New center of the bounding info
  18580. * @param extend New extend of the bounding info
  18581. */
  18582. BoundingInfo.prototype.centerOn = function (center, extend) {
  18583. this.minimum = center.subtract(extend);
  18584. this.maximum = center.add(extend);
  18585. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18586. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18587. return this;
  18588. };
  18589. /**
  18590. * Scale the current bounding info by applying a scale factor
  18591. * @param factor defines the scale factor to apply
  18592. * @returns the current bounding info
  18593. */
  18594. BoundingInfo.prototype.scale = function (factor) {
  18595. this.boundingBox.scale(factor);
  18596. this.boundingSphere.scale(factor);
  18597. return this;
  18598. };
  18599. /**
  18600. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18601. * @param frustumPlanes defines the frustum to test
  18602. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18603. * @returns true if the bounding info is in the frustum planes
  18604. */
  18605. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18606. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18607. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18608. return false;
  18609. }
  18610. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18611. return true;
  18612. }
  18613. return this.boundingBox.isInFrustum(frustumPlanes);
  18614. };
  18615. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18616. /**
  18617. * Gets the world distance between the min and max points of the bounding box
  18618. */
  18619. get: function () {
  18620. var boundingBox = this.boundingBox;
  18621. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18622. return size.length();
  18623. },
  18624. enumerable: true,
  18625. configurable: true
  18626. });
  18627. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18628. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18629. };
  18630. /** @hidden */
  18631. BoundingInfo.prototype._checkCollision = function (collider) {
  18632. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18633. };
  18634. BoundingInfo.prototype.intersectsPoint = function (point) {
  18635. if (!this.boundingSphere.centerWorld) {
  18636. return false;
  18637. }
  18638. if (!this.boundingSphere.intersectsPoint(point)) {
  18639. return false;
  18640. }
  18641. if (!this.boundingBox.intersectsPoint(point)) {
  18642. return false;
  18643. }
  18644. return true;
  18645. };
  18646. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18647. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18648. return false;
  18649. }
  18650. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18651. return false;
  18652. }
  18653. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18654. return false;
  18655. }
  18656. if (!precise) {
  18657. return true;
  18658. }
  18659. var box0 = this.boundingBox;
  18660. var box1 = boundingInfo.boundingBox;
  18661. if (!axisOverlap(box0.directions[0], box0, box1))
  18662. return false;
  18663. if (!axisOverlap(box0.directions[1], box0, box1))
  18664. return false;
  18665. if (!axisOverlap(box0.directions[2], box0, box1))
  18666. return false;
  18667. if (!axisOverlap(box1.directions[0], box0, box1))
  18668. return false;
  18669. if (!axisOverlap(box1.directions[1], box0, box1))
  18670. return false;
  18671. if (!axisOverlap(box1.directions[2], box0, box1))
  18672. return false;
  18673. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18674. return false;
  18675. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18676. return false;
  18677. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18678. return false;
  18679. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18680. return false;
  18681. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18682. return false;
  18683. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18684. return false;
  18685. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18686. return false;
  18687. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18688. return false;
  18689. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18690. return false;
  18691. return true;
  18692. };
  18693. return BoundingInfo;
  18694. }());
  18695. BABYLON.BoundingInfo = BoundingInfo;
  18696. })(BABYLON || (BABYLON = {}));
  18697. //# sourceMappingURL=babylon.boundingInfo.js.map
  18698. var BABYLON;
  18699. (function (BABYLON) {
  18700. var TransformNode = /** @class */ (function (_super) {
  18701. __extends(TransformNode, _super);
  18702. function TransformNode(name, scene, isPure) {
  18703. if (scene === void 0) { scene = null; }
  18704. if (isPure === void 0) { isPure = true; }
  18705. var _this = _super.call(this, name, scene) || this;
  18706. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18707. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18708. _this._up = new BABYLON.Vector3(0, 1, 0);
  18709. _this._right = new BABYLON.Vector3(1, 0, 0);
  18710. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18711. // Properties
  18712. _this._position = BABYLON.Vector3.Zero();
  18713. _this._rotation = BABYLON.Vector3.Zero();
  18714. _this._scaling = BABYLON.Vector3.One();
  18715. _this._isDirty = false;
  18716. /**
  18717. * Set the billboard mode. Default is 0.
  18718. *
  18719. * | Value | Type | Description |
  18720. * | --- | --- | --- |
  18721. * | 0 | BILLBOARDMODE_NONE | |
  18722. * | 1 | BILLBOARDMODE_X | |
  18723. * | 2 | BILLBOARDMODE_Y | |
  18724. * | 4 | BILLBOARDMODE_Z | |
  18725. * | 7 | BILLBOARDMODE_ALL | |
  18726. *
  18727. */
  18728. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18729. _this.scalingDeterminant = 1;
  18730. _this.infiniteDistance = false;
  18731. /**
  18732. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18733. * By default the system will update normals to compensate
  18734. */
  18735. _this.ignoreNonUniformScaling = false;
  18736. _this._localWorld = BABYLON.Matrix.Zero();
  18737. _this._absolutePosition = BABYLON.Vector3.Zero();
  18738. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18739. _this._postMultiplyPivotMatrix = false;
  18740. _this._isWorldMatrixFrozen = false;
  18741. /**
  18742. * An event triggered after the world matrix is updated
  18743. */
  18744. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18745. _this._nonUniformScaling = false;
  18746. if (isPure) {
  18747. _this.getScene().addTransformNode(_this);
  18748. }
  18749. return _this;
  18750. }
  18751. /**
  18752. * Gets a string identifying the name of the class
  18753. * @returns "TransformNode" string
  18754. */
  18755. TransformNode.prototype.getClassName = function () {
  18756. return "TransformNode";
  18757. };
  18758. Object.defineProperty(TransformNode.prototype, "position", {
  18759. /**
  18760. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18761. */
  18762. get: function () {
  18763. return this._position;
  18764. },
  18765. set: function (newPosition) {
  18766. this._position = newPosition;
  18767. this._isDirty = true;
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. Object.defineProperty(TransformNode.prototype, "rotation", {
  18773. /**
  18774. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18775. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18776. */
  18777. get: function () {
  18778. return this._rotation;
  18779. },
  18780. set: function (newRotation) {
  18781. this._rotation = newRotation;
  18782. this._isDirty = true;
  18783. },
  18784. enumerable: true,
  18785. configurable: true
  18786. });
  18787. Object.defineProperty(TransformNode.prototype, "scaling", {
  18788. /**
  18789. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18790. */
  18791. get: function () {
  18792. return this._scaling;
  18793. },
  18794. set: function (newScaling) {
  18795. this._scaling = newScaling;
  18796. this._isDirty = true;
  18797. },
  18798. enumerable: true,
  18799. configurable: true
  18800. });
  18801. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18802. /**
  18803. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18804. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18805. */
  18806. get: function () {
  18807. return this._rotationQuaternion;
  18808. },
  18809. set: function (quaternion) {
  18810. this._rotationQuaternion = quaternion;
  18811. //reset the rotation vector.
  18812. if (quaternion && this.rotation.length()) {
  18813. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18814. }
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. Object.defineProperty(TransformNode.prototype, "forward", {
  18820. /**
  18821. * The forward direction of that transform in world space.
  18822. */
  18823. get: function () {
  18824. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18825. },
  18826. enumerable: true,
  18827. configurable: true
  18828. });
  18829. Object.defineProperty(TransformNode.prototype, "up", {
  18830. /**
  18831. * The up direction of that transform in world space.
  18832. */
  18833. get: function () {
  18834. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. Object.defineProperty(TransformNode.prototype, "right", {
  18840. /**
  18841. * The right direction of that transform in world space.
  18842. */
  18843. get: function () {
  18844. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18845. },
  18846. enumerable: true,
  18847. configurable: true
  18848. });
  18849. /**
  18850. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18851. * Returns the TransformNode.
  18852. */
  18853. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18854. this._poseMatrix.copyFrom(matrix);
  18855. return this;
  18856. };
  18857. /**
  18858. * Returns the mesh Pose matrix.
  18859. * Returned object : Matrix
  18860. */
  18861. TransformNode.prototype.getPoseMatrix = function () {
  18862. return this._poseMatrix;
  18863. };
  18864. /** @hidden */
  18865. TransformNode.prototype._isSynchronized = function () {
  18866. if (this._isDirty) {
  18867. return false;
  18868. }
  18869. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18870. return false;
  18871. if (this._cache.pivotMatrixUpdated) {
  18872. return false;
  18873. }
  18874. if (this.infiniteDistance) {
  18875. return false;
  18876. }
  18877. if (!this._cache.position.equals(this._position))
  18878. return false;
  18879. if (this._rotationQuaternion) {
  18880. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18881. return false;
  18882. }
  18883. if (!this._cache.rotation.equals(this._rotation))
  18884. return false;
  18885. if (!this._cache.scaling.equals(this._scaling))
  18886. return false;
  18887. return true;
  18888. };
  18889. /** @hidden */
  18890. TransformNode.prototype._initCache = function () {
  18891. _super.prototype._initCache.call(this);
  18892. this._cache.localMatrixUpdated = false;
  18893. this._cache.position = BABYLON.Vector3.Zero();
  18894. this._cache.scaling = BABYLON.Vector3.Zero();
  18895. this._cache.rotation = BABYLON.Vector3.Zero();
  18896. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18897. this._cache.billboardMode = -1;
  18898. };
  18899. TransformNode.prototype.markAsDirty = function (property) {
  18900. if (property === "rotation") {
  18901. this.rotationQuaternion = null;
  18902. }
  18903. this._currentRenderId = Number.MAX_VALUE;
  18904. this._isDirty = true;
  18905. return this;
  18906. };
  18907. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18908. /**
  18909. * Returns the current mesh absolute position.
  18910. * Returns a Vector3.
  18911. */
  18912. get: function () {
  18913. return this._absolutePosition;
  18914. },
  18915. enumerable: true,
  18916. configurable: true
  18917. });
  18918. /**
  18919. * Sets a new matrix to apply before all other transformation
  18920. * @param matrix defines the transform matrix
  18921. * @returns the current TransformNode
  18922. */
  18923. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18924. return this.setPivotMatrix(matrix, false);
  18925. };
  18926. /**
  18927. * Sets a new pivot matrix to the current node
  18928. * @param matrix defines the new pivot matrix to use
  18929. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  18930. * @returns the current TransformNode
  18931. */
  18932. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18933. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18934. this._pivotMatrix = matrix.clone();
  18935. this._cache.pivotMatrixUpdated = true;
  18936. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18937. if (this._postMultiplyPivotMatrix) {
  18938. if (!this._pivotMatrixInverse) {
  18939. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18940. }
  18941. else {
  18942. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18943. }
  18944. }
  18945. return this;
  18946. };
  18947. /**
  18948. * Returns the mesh pivot matrix.
  18949. * Default : Identity.
  18950. * A Matrix is returned.
  18951. */
  18952. TransformNode.prototype.getPivotMatrix = function () {
  18953. return this._pivotMatrix;
  18954. };
  18955. /**
  18956. * Prevents the World matrix to be computed any longer.
  18957. * Returns the TransformNode.
  18958. */
  18959. TransformNode.prototype.freezeWorldMatrix = function () {
  18960. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18961. this.computeWorldMatrix(true);
  18962. this._isWorldMatrixFrozen = true;
  18963. return this;
  18964. };
  18965. /**
  18966. * Allows back the World matrix computation.
  18967. * Returns the TransformNode.
  18968. */
  18969. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18970. this._isWorldMatrixFrozen = false;
  18971. this.computeWorldMatrix(true);
  18972. return this;
  18973. };
  18974. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18975. /**
  18976. * True if the World matrix has been frozen.
  18977. * Returns a boolean.
  18978. */
  18979. get: function () {
  18980. return this._isWorldMatrixFrozen;
  18981. },
  18982. enumerable: true,
  18983. configurable: true
  18984. });
  18985. /**
  18986. * Retuns the mesh absolute position in the World.
  18987. * Returns a Vector3.
  18988. */
  18989. TransformNode.prototype.getAbsolutePosition = function () {
  18990. this.computeWorldMatrix();
  18991. return this._absolutePosition;
  18992. };
  18993. /**
  18994. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18995. * Returns the TransformNode.
  18996. */
  18997. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18998. if (!absolutePosition) {
  18999. return this;
  19000. }
  19001. var absolutePositionX;
  19002. var absolutePositionY;
  19003. var absolutePositionZ;
  19004. if (absolutePosition.x === undefined) {
  19005. if (arguments.length < 3) {
  19006. return this;
  19007. }
  19008. absolutePositionX = arguments[0];
  19009. absolutePositionY = arguments[1];
  19010. absolutePositionZ = arguments[2];
  19011. }
  19012. else {
  19013. absolutePositionX = absolutePosition.x;
  19014. absolutePositionY = absolutePosition.y;
  19015. absolutePositionZ = absolutePosition.z;
  19016. }
  19017. if (this.parent) {
  19018. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19019. invertParentWorldMatrix.invert();
  19020. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19021. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19022. }
  19023. else {
  19024. this.position.x = absolutePositionX;
  19025. this.position.y = absolutePositionY;
  19026. this.position.z = absolutePositionZ;
  19027. }
  19028. return this;
  19029. };
  19030. /**
  19031. * Sets the mesh position in its local space.
  19032. * Returns the TransformNode.
  19033. */
  19034. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19035. this.computeWorldMatrix();
  19036. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19037. return this;
  19038. };
  19039. /**
  19040. * Returns the mesh position in the local space from the current World matrix values.
  19041. * Returns a new Vector3.
  19042. */
  19043. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19044. this.computeWorldMatrix();
  19045. var invLocalWorldMatrix = this._localWorld.clone();
  19046. invLocalWorldMatrix.invert();
  19047. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19048. };
  19049. /**
  19050. * Translates the mesh along the passed Vector3 in its local space.
  19051. * Returns the TransformNode.
  19052. */
  19053. TransformNode.prototype.locallyTranslate = function (vector3) {
  19054. this.computeWorldMatrix(true);
  19055. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19056. return this;
  19057. };
  19058. /**
  19059. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19060. * @param targetPoint the position (must be in same space as current mesh) to look at
  19061. * @param yawCor optional yaw (y-axis) correction in radians
  19062. * @param pitchCor optional pitch (x-axis) correction in radians
  19063. * @param rollCor optional roll (z-axis) correction in radians
  19064. * @param space the choosen space of the target
  19065. * @returns the TransformNode.
  19066. */
  19067. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19068. if (yawCor === void 0) { yawCor = 0; }
  19069. if (pitchCor === void 0) { pitchCor = 0; }
  19070. if (rollCor === void 0) { rollCor = 0; }
  19071. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19072. var dv = TransformNode._lookAtVectorCache;
  19073. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19074. targetPoint.subtractToRef(pos, dv);
  19075. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19076. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19077. var pitch = Math.atan2(dv.y, len);
  19078. if (this.rotationQuaternion) {
  19079. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19080. }
  19081. else {
  19082. this.rotation.x = pitch + pitchCor;
  19083. this.rotation.y = yaw + yawCor;
  19084. this.rotation.z = rollCor;
  19085. }
  19086. return this;
  19087. };
  19088. /**
  19089. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19090. * This Vector3 is expressed in the World space.
  19091. */
  19092. TransformNode.prototype.getDirection = function (localAxis) {
  19093. var result = BABYLON.Vector3.Zero();
  19094. this.getDirectionToRef(localAxis, result);
  19095. return result;
  19096. };
  19097. /**
  19098. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19099. * localAxis is expressed in the mesh local space.
  19100. * result is computed in the Wordl space from the mesh World matrix.
  19101. * Returns the TransformNode.
  19102. */
  19103. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19104. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19105. return this;
  19106. };
  19107. /**
  19108. * Sets a new pivot point to the current node
  19109. * @param point defines the new pivot point to use
  19110. * @param space defines if the point is in world or local space (local by default)
  19111. * @returns the current TransformNode
  19112. */
  19113. TransformNode.prototype.setPivotPoint = function (point, space) {
  19114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19115. if (this.getScene().getRenderId() == 0) {
  19116. this.computeWorldMatrix(true);
  19117. }
  19118. var wm = this.getWorldMatrix();
  19119. if (space == BABYLON.Space.WORLD) {
  19120. var tmat = BABYLON.Tmp.Matrix[0];
  19121. wm.invertToRef(tmat);
  19122. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19123. }
  19124. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19125. };
  19126. /**
  19127. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19128. */
  19129. TransformNode.prototype.getPivotPoint = function () {
  19130. var point = BABYLON.Vector3.Zero();
  19131. this.getPivotPointToRef(point);
  19132. return point;
  19133. };
  19134. /**
  19135. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19136. * Returns the TransformNode.
  19137. */
  19138. TransformNode.prototype.getPivotPointToRef = function (result) {
  19139. result.x = -this._pivotMatrix.m[12];
  19140. result.y = -this._pivotMatrix.m[13];
  19141. result.z = -this._pivotMatrix.m[14];
  19142. return this;
  19143. };
  19144. /**
  19145. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19146. */
  19147. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19148. var point = BABYLON.Vector3.Zero();
  19149. this.getAbsolutePivotPointToRef(point);
  19150. return point;
  19151. };
  19152. /**
  19153. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19154. * Returns the TransformNode.
  19155. */
  19156. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19157. result.x = this._pivotMatrix.m[12];
  19158. result.y = this._pivotMatrix.m[13];
  19159. result.z = this._pivotMatrix.m[14];
  19160. this.getPivotPointToRef(result);
  19161. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19162. return this;
  19163. };
  19164. /**
  19165. * Defines the passed node as the parent of the current node.
  19166. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19167. * Returns the TransformNode.
  19168. */
  19169. TransformNode.prototype.setParent = function (node) {
  19170. if (!node && !this.parent) {
  19171. return this;
  19172. }
  19173. if (!node) {
  19174. var rotation = BABYLON.Tmp.Quaternion[0];
  19175. var position = BABYLON.Tmp.Vector3[0];
  19176. var scale = BABYLON.Tmp.Vector3[1];
  19177. if (this.parent && this.parent.computeWorldMatrix) {
  19178. this.parent.computeWorldMatrix(true);
  19179. }
  19180. this.computeWorldMatrix(true);
  19181. this.getWorldMatrix().decompose(scale, rotation, position);
  19182. if (this.rotationQuaternion) {
  19183. this.rotationQuaternion.copyFrom(rotation);
  19184. }
  19185. else {
  19186. rotation.toEulerAnglesToRef(this.rotation);
  19187. }
  19188. this.scaling.x = scale.x;
  19189. this.scaling.y = scale.y;
  19190. this.scaling.z = scale.z;
  19191. this.position.x = position.x;
  19192. this.position.y = position.y;
  19193. this.position.z = position.z;
  19194. }
  19195. else {
  19196. var rotation = BABYLON.Tmp.Quaternion[0];
  19197. var position = BABYLON.Tmp.Vector3[0];
  19198. var scale = BABYLON.Tmp.Vector3[1];
  19199. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19200. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19201. this.computeWorldMatrix(true);
  19202. node.computeWorldMatrix(true);
  19203. node.getWorldMatrix().invertToRef(invParentMatrix);
  19204. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19205. diffMatrix.decompose(scale, rotation, position);
  19206. if (this.rotationQuaternion) {
  19207. this.rotationQuaternion.copyFrom(rotation);
  19208. }
  19209. else {
  19210. rotation.toEulerAnglesToRef(this.rotation);
  19211. }
  19212. this.position.x = position.x;
  19213. this.position.y = position.y;
  19214. this.position.z = position.z;
  19215. this.scaling.x = scale.x;
  19216. this.scaling.y = scale.y;
  19217. this.scaling.z = scale.z;
  19218. }
  19219. this.parent = node;
  19220. return this;
  19221. };
  19222. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19223. get: function () {
  19224. return this._nonUniformScaling;
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. /** @hidden */
  19230. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19231. if (this._nonUniformScaling === value) {
  19232. return false;
  19233. }
  19234. this._nonUniformScaling = value;
  19235. return true;
  19236. };
  19237. /**
  19238. * Attach the current TransformNode to another TransformNode associated with a bone
  19239. * @param bone Bone affecting the TransformNode
  19240. * @param affectedTransformNode TransformNode associated with the bone
  19241. */
  19242. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19243. this._transformToBoneReferal = affectedTransformNode;
  19244. this.parent = bone;
  19245. if (bone.getWorldMatrix().determinant() < 0) {
  19246. this.scalingDeterminant *= -1;
  19247. }
  19248. return this;
  19249. };
  19250. TransformNode.prototype.detachFromBone = function () {
  19251. if (!this.parent) {
  19252. return this;
  19253. }
  19254. if (this.parent.getWorldMatrix().determinant() < 0) {
  19255. this.scalingDeterminant *= -1;
  19256. }
  19257. this._transformToBoneReferal = null;
  19258. this.parent = null;
  19259. return this;
  19260. };
  19261. /**
  19262. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19263. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19264. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19265. * The passed axis is also normalized.
  19266. * Returns the TransformNode.
  19267. */
  19268. TransformNode.prototype.rotate = function (axis, amount, space) {
  19269. axis.normalize();
  19270. if (!this.rotationQuaternion) {
  19271. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19272. this.rotation = BABYLON.Vector3.Zero();
  19273. }
  19274. var rotationQuaternion;
  19275. if (!space || space === BABYLON.Space.LOCAL) {
  19276. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19277. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19278. }
  19279. else {
  19280. if (this.parent) {
  19281. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19282. invertParentWorldMatrix.invert();
  19283. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19284. }
  19285. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19286. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19287. }
  19288. return this;
  19289. };
  19290. /**
  19291. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19292. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19293. * The passed axis is also normalized.
  19294. * Returns the TransformNode.
  19295. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19296. */
  19297. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19298. axis.normalize();
  19299. if (!this.rotationQuaternion) {
  19300. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19301. this.rotation.copyFromFloats(0, 0, 0);
  19302. }
  19303. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19304. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19305. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19306. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19307. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19308. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19309. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19310. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19311. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19312. return this;
  19313. };
  19314. /**
  19315. * Translates the mesh along the axis vector for the passed distance in the given space.
  19316. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19317. * Returns the TransformNode.
  19318. */
  19319. TransformNode.prototype.translate = function (axis, distance, space) {
  19320. var displacementVector = axis.scale(distance);
  19321. if (!space || space === BABYLON.Space.LOCAL) {
  19322. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19323. this.setPositionWithLocalVector(tempV3);
  19324. }
  19325. else {
  19326. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19327. }
  19328. return this;
  19329. };
  19330. /**
  19331. * Adds a rotation step to the mesh current rotation.
  19332. * x, y, z are Euler angles expressed in radians.
  19333. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19334. * This means this rotation is made in the mesh local space only.
  19335. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19336. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19337. * ```javascript
  19338. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19339. * ```
  19340. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19341. * 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.
  19342. * Returns the TransformNode.
  19343. */
  19344. TransformNode.prototype.addRotation = function (x, y, z) {
  19345. var rotationQuaternion;
  19346. if (this.rotationQuaternion) {
  19347. rotationQuaternion = this.rotationQuaternion;
  19348. }
  19349. else {
  19350. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19351. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19352. }
  19353. var accumulation = BABYLON.Tmp.Quaternion[0];
  19354. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19355. rotationQuaternion.multiplyInPlace(accumulation);
  19356. if (!this.rotationQuaternion) {
  19357. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19358. }
  19359. return this;
  19360. };
  19361. /**
  19362. * Computes the world matrix of the node
  19363. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19364. * @returns the world matrix
  19365. */
  19366. TransformNode.prototype.computeWorldMatrix = function (force) {
  19367. if (this._isWorldMatrixFrozen) {
  19368. return this._worldMatrix;
  19369. }
  19370. if (!force && this.isSynchronized()) {
  19371. this._currentRenderId = this.getScene().getRenderId();
  19372. return this._worldMatrix;
  19373. }
  19374. this._updateCache();
  19375. this._cache.position.copyFrom(this.position);
  19376. this._cache.scaling.copyFrom(this.scaling);
  19377. this._cache.pivotMatrixUpdated = false;
  19378. this._cache.billboardMode = this.billboardMode;
  19379. this._currentRenderId = this.getScene().getRenderId();
  19380. this._childRenderId = this.getScene().getRenderId();
  19381. this._isDirty = false;
  19382. // Scaling
  19383. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19384. // Rotation
  19385. //rotate, if quaternion is set and rotation was used
  19386. if (this.rotationQuaternion) {
  19387. var len = this.rotation.length();
  19388. if (len) {
  19389. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19390. this.rotation.copyFromFloats(0, 0, 0);
  19391. }
  19392. }
  19393. if (this.rotationQuaternion) {
  19394. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19395. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19396. }
  19397. else {
  19398. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19399. this._cache.rotation.copyFrom(this.rotation);
  19400. }
  19401. // Translation
  19402. var camera = this.getScene().activeCamera;
  19403. if (this.infiniteDistance && !this.parent && camera) {
  19404. var cameraWorldMatrix = camera.getWorldMatrix();
  19405. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19406. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19407. }
  19408. else {
  19409. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19410. }
  19411. // Composing transformations
  19412. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19413. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19414. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19415. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19416. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19417. // Need to decompose each rotation here
  19418. var currentPosition = BABYLON.Tmp.Vector3[3];
  19419. if (this.parent && this.parent.getWorldMatrix) {
  19420. if (this._transformToBoneReferal) {
  19421. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19422. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19423. }
  19424. else {
  19425. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19426. }
  19427. }
  19428. else {
  19429. currentPosition.copyFrom(this.position);
  19430. }
  19431. currentPosition.subtractInPlace(camera.globalPosition);
  19432. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19433. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19434. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19435. }
  19436. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19437. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19438. }
  19439. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19440. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19441. }
  19442. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19443. }
  19444. else {
  19445. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19446. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19447. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19448. }
  19449. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19450. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19451. }
  19452. // Post multiply inverse of pivotMatrix
  19453. if (this._postMultiplyPivotMatrix) {
  19454. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19455. }
  19456. // Local world
  19457. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19458. // Parent
  19459. if (this.parent && this.parent.getWorldMatrix) {
  19460. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19461. if (this._transformToBoneReferal) {
  19462. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19463. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19464. }
  19465. else {
  19466. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19467. }
  19468. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19469. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19470. this._worldMatrix.copyFrom(this._localWorld);
  19471. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19472. }
  19473. else {
  19474. if (this._transformToBoneReferal) {
  19475. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19476. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19477. }
  19478. else {
  19479. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19480. }
  19481. }
  19482. this._markSyncedWithParent();
  19483. }
  19484. else {
  19485. this._worldMatrix.copyFrom(this._localWorld);
  19486. }
  19487. // Normal matrix
  19488. if (!this.ignoreNonUniformScaling) {
  19489. if (this.scaling.isNonUniform) {
  19490. this._updateNonUniformScalingState(true);
  19491. }
  19492. else if (this.parent && this.parent._nonUniformScaling) {
  19493. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19494. }
  19495. else {
  19496. this._updateNonUniformScalingState(false);
  19497. }
  19498. }
  19499. else {
  19500. this._updateNonUniformScalingState(false);
  19501. }
  19502. this._afterComputeWorldMatrix();
  19503. // Absolute position
  19504. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19505. // Callbacks
  19506. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19507. if (!this._poseMatrix) {
  19508. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19509. }
  19510. // Cache the determinant
  19511. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19512. return this._worldMatrix;
  19513. };
  19514. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19515. };
  19516. /**
  19517. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19518. * @param func: callback function to add
  19519. *
  19520. * Returns the TransformNode.
  19521. */
  19522. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19523. this.onAfterWorldMatrixUpdateObservable.add(func);
  19524. return this;
  19525. };
  19526. /**
  19527. * Removes a registered callback function.
  19528. * Returns the TransformNode.
  19529. */
  19530. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19531. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19532. return this;
  19533. };
  19534. /**
  19535. * Clone the current transform node
  19536. * Returns the new transform node
  19537. * @param name Name of the new clone
  19538. * @param newParent New parent for the clone
  19539. * @param doNotCloneChildren Do not clone children hierarchy
  19540. */
  19541. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19542. var _this = this;
  19543. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19544. result.name = name;
  19545. result.id = name;
  19546. if (newParent) {
  19547. result.parent = newParent;
  19548. }
  19549. if (!doNotCloneChildren) {
  19550. // Children
  19551. var directDescendants = this.getDescendants(true);
  19552. for (var index = 0; index < directDescendants.length; index++) {
  19553. var child = directDescendants[index];
  19554. if (child.clone) {
  19555. child.clone(name + "." + child.name, result);
  19556. }
  19557. }
  19558. }
  19559. return result;
  19560. };
  19561. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19562. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19563. serializationObject.type = this.getClassName();
  19564. // Parent
  19565. if (this.parent) {
  19566. serializationObject.parentId = this.parent.id;
  19567. }
  19568. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19569. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19570. }
  19571. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19572. serializationObject.isEnabled = this.isEnabled();
  19573. // Parent
  19574. if (this.parent) {
  19575. serializationObject.parentId = this.parent.id;
  19576. }
  19577. return serializationObject;
  19578. };
  19579. // Statics
  19580. /**
  19581. * Returns a new TransformNode object parsed from the source provided.
  19582. * The parameter `parsedMesh` is the source.
  19583. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19584. */
  19585. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19586. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19587. if (BABYLON.Tags) {
  19588. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19589. }
  19590. if (parsedTransformNode.localMatrix) {
  19591. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19592. }
  19593. else if (parsedTransformNode.pivotMatrix) {
  19594. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19595. }
  19596. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19597. // Parent
  19598. if (parsedTransformNode.parentId) {
  19599. transformNode._waitingParentId = parsedTransformNode.parentId;
  19600. }
  19601. return transformNode;
  19602. };
  19603. /**
  19604. * Releases resources associated with this transform node.
  19605. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19606. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19607. */
  19608. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19609. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19610. // Animations
  19611. this.getScene().stopAnimation(this);
  19612. // Remove from scene
  19613. this.getScene().removeTransformNode(this);
  19614. this.onAfterWorldMatrixUpdateObservable.clear();
  19615. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19616. };
  19617. // Statics
  19618. TransformNode.BILLBOARDMODE_NONE = 0;
  19619. TransformNode.BILLBOARDMODE_X = 1;
  19620. TransformNode.BILLBOARDMODE_Y = 2;
  19621. TransformNode.BILLBOARDMODE_Z = 4;
  19622. TransformNode.BILLBOARDMODE_ALL = 7;
  19623. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19624. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19625. __decorate([
  19626. BABYLON.serializeAsVector3("position")
  19627. ], TransformNode.prototype, "_position", void 0);
  19628. __decorate([
  19629. BABYLON.serializeAsVector3("rotation")
  19630. ], TransformNode.prototype, "_rotation", void 0);
  19631. __decorate([
  19632. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19633. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19634. __decorate([
  19635. BABYLON.serializeAsVector3("scaling")
  19636. ], TransformNode.prototype, "_scaling", void 0);
  19637. __decorate([
  19638. BABYLON.serialize()
  19639. ], TransformNode.prototype, "billboardMode", void 0);
  19640. __decorate([
  19641. BABYLON.serialize()
  19642. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19643. __decorate([
  19644. BABYLON.serialize()
  19645. ], TransformNode.prototype, "infiniteDistance", void 0);
  19646. __decorate([
  19647. BABYLON.serialize()
  19648. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19649. return TransformNode;
  19650. }(BABYLON.Node));
  19651. BABYLON.TransformNode = TransformNode;
  19652. })(BABYLON || (BABYLON = {}));
  19653. //# sourceMappingURL=babylon.transformNode.js.map
  19654. var BABYLON;
  19655. (function (BABYLON) {
  19656. /**
  19657. * Class used to store all common mesh properties
  19658. */
  19659. var AbstractMesh = /** @class */ (function (_super) {
  19660. __extends(AbstractMesh, _super);
  19661. // Constructor
  19662. /**
  19663. * Creates a new AbstractMesh
  19664. * @param name defines the name of the mesh
  19665. * @param scene defines the hosting scene
  19666. */
  19667. function AbstractMesh(name, scene) {
  19668. if (scene === void 0) { scene = null; }
  19669. var _this = _super.call(this, name, scene, false) || this;
  19670. _this._facetNb = 0; // facet number
  19671. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19672. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19673. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19674. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19675. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19676. _this._subDiv = {
  19677. max: 1,
  19678. X: 1,
  19679. Y: 1,
  19680. Z: 1
  19681. };
  19682. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19683. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19684. /** Gets ot sets the culling strategy to use to find visible meshes */
  19685. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19686. // Events
  19687. /**
  19688. * An event triggered when this mesh collides with another one
  19689. */
  19690. _this.onCollideObservable = new BABYLON.Observable();
  19691. /**
  19692. * An event triggered when the collision's position changes
  19693. */
  19694. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19695. /**
  19696. * An event triggered when material is changed
  19697. */
  19698. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19699. // Properties
  19700. /**
  19701. * Gets or sets the orientation for POV movement & rotation
  19702. */
  19703. _this.definedFacingForward = true;
  19704. /**
  19705. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19706. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19707. * * 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.
  19708. * @see http://doc.babylonjs.com/features/occlusionquery
  19709. */
  19710. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19711. /**
  19712. * 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:
  19713. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19714. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19715. * * 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.
  19716. * @see http://doc.babylonjs.com/features/occlusionquery
  19717. */
  19718. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19719. /**
  19720. * 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.
  19721. * The default value is -1 which means don't break the query and wait till the result
  19722. * @see http://doc.babylonjs.com/features/occlusionquery
  19723. */
  19724. _this.occlusionRetryCount = -1;
  19725. /** @hidden */
  19726. _this._occlusionInternalRetryCounter = 0;
  19727. /** @hidden */
  19728. _this._isOccluded = false;
  19729. /** @hidden */
  19730. _this._isOcclusionQueryInProgress = false;
  19731. _this._visibility = 1.0;
  19732. /** Gets or sets the alpha index used to sort transparent meshes
  19733. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19734. */
  19735. _this.alphaIndex = Number.MAX_VALUE;
  19736. /**
  19737. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19738. */
  19739. _this.isVisible = true;
  19740. /**
  19741. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19742. */
  19743. _this.isPickable = true;
  19744. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19745. _this.showSubMeshesBoundingBox = false;
  19746. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19747. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19748. */
  19749. _this.isBlocker = false;
  19750. /**
  19751. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19752. */
  19753. _this.enablePointerMoveEvents = false;
  19754. /**
  19755. * Specifies the rendering group id for this mesh (0 by default)
  19756. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19757. */
  19758. _this.renderingGroupId = 0;
  19759. _this._receiveShadows = false;
  19760. /** Defines color to use when rendering outline */
  19761. _this.outlineColor = BABYLON.Color3.Red();
  19762. /** Define width to use when rendering outline */
  19763. _this.outlineWidth = 0.02;
  19764. /** Defines color to use when rendering overlay */
  19765. _this.overlayColor = BABYLON.Color3.Red();
  19766. /** Defines alpha to use when rendering overlay */
  19767. _this.overlayAlpha = 0.5;
  19768. _this._hasVertexAlpha = false;
  19769. _this._useVertexColors = true;
  19770. _this._computeBonesUsingShaders = true;
  19771. _this._numBoneInfluencers = 4;
  19772. _this._applyFog = true;
  19773. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19774. _this.useOctreeForRenderingSelection = true;
  19775. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19776. _this.useOctreeForPicking = true;
  19777. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19778. _this.useOctreeForCollisions = true;
  19779. _this._layerMask = 0x0FFFFFFF;
  19780. /**
  19781. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19782. */
  19783. _this.alwaysSelectAsActiveMesh = false;
  19784. /**
  19785. * Gets or sets the current action manager
  19786. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19787. */
  19788. _this.actionManager = null;
  19789. // Collisions
  19790. _this._checkCollisions = false;
  19791. _this._collisionMask = -1;
  19792. _this._collisionGroup = -1;
  19793. /**
  19794. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19795. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19796. */
  19797. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19798. /**
  19799. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19800. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19801. */
  19802. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19803. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19804. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19805. // Edges
  19806. /**
  19807. * Defines edge width used when edgesRenderer is enabled
  19808. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19809. */
  19810. _this.edgesWidth = 1;
  19811. /**
  19812. * Defines edge color used when edgesRenderer is enabled
  19813. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19814. */
  19815. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19816. // Cache
  19817. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19818. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19819. /** @hidden */
  19820. _this._renderId = 0;
  19821. /** @hidden */
  19822. _this._intersectionsInProgress = new Array();
  19823. /** @hidden */
  19824. _this._unIndexed = false;
  19825. /** @hidden */
  19826. _this._lightSources = new Array();
  19827. /**
  19828. * An event triggered when the mesh is rebuilt.
  19829. */
  19830. _this.onRebuildObservable = new BABYLON.Observable();
  19831. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19832. if (collidedMesh === void 0) { collidedMesh = null; }
  19833. //TODO move this to the collision coordinator!
  19834. if (_this.getScene().workerCollisions)
  19835. newPosition.multiplyInPlace(_this._collider._radius);
  19836. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19837. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19838. _this.position.addInPlace(_this._diffPositionForCollisions);
  19839. }
  19840. if (collidedMesh) {
  19841. _this.onCollideObservable.notifyObservers(collidedMesh);
  19842. }
  19843. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19844. };
  19845. _this.getScene().addMesh(_this);
  19846. _this._resyncLightSources();
  19847. return _this;
  19848. }
  19849. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19850. /**
  19851. * No billboard
  19852. */
  19853. get: function () {
  19854. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19860. /** Billboard on X axis */
  19861. get: function () {
  19862. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19868. /** Billboard on Y axis */
  19869. get: function () {
  19870. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19876. /** Billboard on Z axis */
  19877. get: function () {
  19878. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19884. /** Billboard on all axes */
  19885. get: function () {
  19886. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19892. /**
  19893. * Gets the number of facets in the mesh
  19894. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19895. */
  19896. get: function () {
  19897. return this._facetNb;
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19903. /**
  19904. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19905. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19906. */
  19907. get: function () {
  19908. return this._partitioningSubdivisions;
  19909. },
  19910. set: function (nb) {
  19911. this._partitioningSubdivisions = nb;
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19917. /**
  19918. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19919. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19920. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19921. */
  19922. get: function () {
  19923. return this._partitioningBBoxRatio;
  19924. },
  19925. set: function (ratio) {
  19926. this._partitioningBBoxRatio = ratio;
  19927. },
  19928. enumerable: true,
  19929. configurable: true
  19930. });
  19931. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19932. /**
  19933. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19934. * Works only for updatable meshes.
  19935. * Doesn't work with multi-materials
  19936. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19937. */
  19938. get: function () {
  19939. return this._facetDepthSort;
  19940. },
  19941. set: function (sort) {
  19942. this._facetDepthSort = sort;
  19943. },
  19944. enumerable: true,
  19945. configurable: true
  19946. });
  19947. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19948. /**
  19949. * The location (Vector3) where the facet depth sort must be computed from.
  19950. * By default, the active camera position.
  19951. * Used only when facet depth sort is enabled
  19952. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19953. */
  19954. get: function () {
  19955. return this._facetDepthSortFrom;
  19956. },
  19957. set: function (location) {
  19958. this._facetDepthSortFrom = location;
  19959. },
  19960. enumerable: true,
  19961. configurable: true
  19962. });
  19963. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19964. /**
  19965. * gets a boolean indicating if facetData is enabled
  19966. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19967. */
  19968. get: function () {
  19969. return this._facetDataEnabled;
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. /** @hidden */
  19975. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19976. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19977. return false;
  19978. }
  19979. this._markSubMeshesAsMiscDirty();
  19980. return true;
  19981. };
  19982. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19983. /** Set a function to call when this mesh collides with another one */
  19984. set: function (callback) {
  19985. if (this._onCollideObserver) {
  19986. this.onCollideObservable.remove(this._onCollideObserver);
  19987. }
  19988. this._onCollideObserver = this.onCollideObservable.add(callback);
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19994. /** Set a function to call when the collision's position changes */
  19995. set: function (callback) {
  19996. if (this._onCollisionPositionChangeObserver) {
  19997. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19998. }
  19999. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20005. /**
  20006. * 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
  20007. * @see http://doc.babylonjs.com/features/occlusionquery
  20008. */
  20009. get: function () {
  20010. return this._isOccluded;
  20011. },
  20012. set: function (value) {
  20013. this._isOccluded = value;
  20014. },
  20015. enumerable: true,
  20016. configurable: true
  20017. });
  20018. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20019. /**
  20020. * Flag to check the progress status of the query
  20021. * @see http://doc.babylonjs.com/features/occlusionquery
  20022. */
  20023. get: function () {
  20024. return this._isOcclusionQueryInProgress;
  20025. },
  20026. enumerable: true,
  20027. configurable: true
  20028. });
  20029. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20030. /**
  20031. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20032. */
  20033. get: function () {
  20034. return this._visibility;
  20035. },
  20036. /**
  20037. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20038. */
  20039. set: function (value) {
  20040. if (this._visibility === value) {
  20041. return;
  20042. }
  20043. this._visibility = value;
  20044. this._markSubMeshesAsMiscDirty();
  20045. },
  20046. enumerable: true,
  20047. configurable: true
  20048. });
  20049. Object.defineProperty(AbstractMesh.prototype, "material", {
  20050. /** Gets or sets current material */
  20051. get: function () {
  20052. return this._material;
  20053. },
  20054. set: function (value) {
  20055. if (this._material === value) {
  20056. return;
  20057. }
  20058. this._material = value;
  20059. if (this.onMaterialChangedObservable.hasObservers) {
  20060. this.onMaterialChangedObservable.notifyObservers(this);
  20061. }
  20062. if (!this.subMeshes) {
  20063. return;
  20064. }
  20065. this._unBindEffect();
  20066. },
  20067. enumerable: true,
  20068. configurable: true
  20069. });
  20070. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20071. /**
  20072. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20073. * @see http://doc.babylonjs.com/babylon101/shadows
  20074. */
  20075. get: function () {
  20076. return this._receiveShadows;
  20077. },
  20078. set: function (value) {
  20079. if (this._receiveShadows === value) {
  20080. return;
  20081. }
  20082. this._receiveShadows = value;
  20083. this._markSubMeshesAsLightDirty();
  20084. },
  20085. enumerable: true,
  20086. configurable: true
  20087. });
  20088. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20089. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20090. get: function () {
  20091. return this._hasVertexAlpha;
  20092. },
  20093. set: function (value) {
  20094. if (this._hasVertexAlpha === value) {
  20095. return;
  20096. }
  20097. this._hasVertexAlpha = value;
  20098. this._markSubMeshesAsAttributesDirty();
  20099. this._markSubMeshesAsMiscDirty();
  20100. },
  20101. enumerable: true,
  20102. configurable: true
  20103. });
  20104. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20105. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20106. get: function () {
  20107. return this._useVertexColors;
  20108. },
  20109. set: function (value) {
  20110. if (this._useVertexColors === value) {
  20111. return;
  20112. }
  20113. this._useVertexColors = value;
  20114. this._markSubMeshesAsAttributesDirty();
  20115. },
  20116. enumerable: true,
  20117. configurable: true
  20118. });
  20119. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20120. /**
  20121. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20122. */
  20123. get: function () {
  20124. return this._computeBonesUsingShaders;
  20125. },
  20126. set: function (value) {
  20127. if (this._computeBonesUsingShaders === value) {
  20128. return;
  20129. }
  20130. this._computeBonesUsingShaders = value;
  20131. this._markSubMeshesAsAttributesDirty();
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20137. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20138. get: function () {
  20139. return this._numBoneInfluencers;
  20140. },
  20141. set: function (value) {
  20142. if (this._numBoneInfluencers === value) {
  20143. return;
  20144. }
  20145. this._numBoneInfluencers = value;
  20146. this._markSubMeshesAsAttributesDirty();
  20147. },
  20148. enumerable: true,
  20149. configurable: true
  20150. });
  20151. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20152. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20153. get: function () {
  20154. return this._applyFog;
  20155. },
  20156. set: function (value) {
  20157. if (this._applyFog === value) {
  20158. return;
  20159. }
  20160. this._applyFog = value;
  20161. this._markSubMeshesAsMiscDirty();
  20162. },
  20163. enumerable: true,
  20164. configurable: true
  20165. });
  20166. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20167. /**
  20168. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20169. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20170. */
  20171. get: function () {
  20172. return this._layerMask;
  20173. },
  20174. set: function (value) {
  20175. if (value === this._layerMask) {
  20176. return;
  20177. }
  20178. this._layerMask = value;
  20179. this._resyncLightSources();
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20185. /**
  20186. * Gets or sets a collision mask used to mask collisions (default is -1).
  20187. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20188. */
  20189. get: function () {
  20190. return this._collisionMask;
  20191. },
  20192. set: function (mask) {
  20193. this._collisionMask = !isNaN(mask) ? mask : -1;
  20194. },
  20195. enumerable: true,
  20196. configurable: true
  20197. });
  20198. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20199. /**
  20200. * Gets or sets the current collision group mask (-1 by default).
  20201. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20202. */
  20203. get: function () {
  20204. return this._collisionGroup;
  20205. },
  20206. set: function (mask) {
  20207. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20208. },
  20209. enumerable: true,
  20210. configurable: true
  20211. });
  20212. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20213. /** @hidden */
  20214. get: function () {
  20215. return null;
  20216. },
  20217. enumerable: true,
  20218. configurable: true
  20219. });
  20220. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20221. get: function () {
  20222. return this._skeleton;
  20223. },
  20224. /**
  20225. * Gets or sets a skeleton to apply skining transformations
  20226. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20227. */
  20228. set: function (value) {
  20229. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20230. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20231. }
  20232. if (value && value.needInitialSkinMatrix) {
  20233. value._registerMeshWithPoseMatrix(this);
  20234. }
  20235. this._skeleton = value;
  20236. if (!this._skeleton) {
  20237. this._bonesTransformMatrices = null;
  20238. }
  20239. this._markSubMeshesAsAttributesDirty();
  20240. },
  20241. enumerable: true,
  20242. configurable: true
  20243. });
  20244. /**
  20245. * Returns the string "AbstractMesh"
  20246. * @returns "AbstractMesh"
  20247. */
  20248. AbstractMesh.prototype.getClassName = function () {
  20249. return "AbstractMesh";
  20250. };
  20251. /**
  20252. * Gets a string representation of the current mesh
  20253. * @param fullDetails defines a boolean indicating if full details must be included
  20254. * @returns a string representation of the current mesh
  20255. */
  20256. AbstractMesh.prototype.toString = function (fullDetails) {
  20257. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20258. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20259. if (this._skeleton) {
  20260. ret += ", skeleton: " + this._skeleton.name;
  20261. }
  20262. if (fullDetails) {
  20263. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20264. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20265. }
  20266. return ret;
  20267. };
  20268. /** @hidden */
  20269. AbstractMesh.prototype._rebuild = function () {
  20270. this.onRebuildObservable.notifyObservers(this);
  20271. if (this._occlusionQuery) {
  20272. this._occlusionQuery = null;
  20273. }
  20274. if (!this.subMeshes) {
  20275. return;
  20276. }
  20277. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20278. var subMesh = _a[_i];
  20279. subMesh._rebuild();
  20280. }
  20281. };
  20282. /** @hidden */
  20283. AbstractMesh.prototype._resyncLightSources = function () {
  20284. this._lightSources.length = 0;
  20285. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20286. var light = _a[_i];
  20287. if (!light.isEnabled()) {
  20288. continue;
  20289. }
  20290. if (light.canAffectMesh(this)) {
  20291. this._lightSources.push(light);
  20292. }
  20293. }
  20294. this._markSubMeshesAsLightDirty();
  20295. };
  20296. /** @hidden */
  20297. AbstractMesh.prototype._resyncLighSource = function (light) {
  20298. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20299. var index = this._lightSources.indexOf(light);
  20300. if (index === -1) {
  20301. if (!isIn) {
  20302. return;
  20303. }
  20304. this._lightSources.push(light);
  20305. }
  20306. else {
  20307. if (isIn) {
  20308. return;
  20309. }
  20310. this._lightSources.splice(index, 1);
  20311. }
  20312. this._markSubMeshesAsLightDirty();
  20313. };
  20314. /** @hidden */
  20315. AbstractMesh.prototype._unBindEffect = function () {
  20316. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20317. var subMesh = _a[_i];
  20318. subMesh.setEffect(null);
  20319. }
  20320. };
  20321. /** @hidden */
  20322. AbstractMesh.prototype._removeLightSource = function (light) {
  20323. var index = this._lightSources.indexOf(light);
  20324. if (index === -1) {
  20325. return;
  20326. }
  20327. this._lightSources.splice(index, 1);
  20328. this._markSubMeshesAsLightDirty();
  20329. };
  20330. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20331. if (!this.subMeshes) {
  20332. return;
  20333. }
  20334. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20335. var subMesh = _a[_i];
  20336. if (subMesh._materialDefines) {
  20337. func(subMesh._materialDefines);
  20338. }
  20339. }
  20340. };
  20341. /** @hidden */
  20342. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20343. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20344. };
  20345. /** @hidden */
  20346. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20347. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20348. };
  20349. /** @hidden */
  20350. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20351. if (!this.subMeshes) {
  20352. return;
  20353. }
  20354. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20355. var subMesh = _a[_i];
  20356. var material = subMesh.getMaterial();
  20357. if (material) {
  20358. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20359. }
  20360. }
  20361. };
  20362. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20363. /**
  20364. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20365. */
  20366. get: function () {
  20367. return this._scaling;
  20368. },
  20369. set: function (newScaling) {
  20370. this._scaling = newScaling;
  20371. if (this.physicsImpostor) {
  20372. this.physicsImpostor.forceUpdate();
  20373. }
  20374. },
  20375. enumerable: true,
  20376. configurable: true
  20377. });
  20378. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20379. // Methods
  20380. /**
  20381. * Returns true if the mesh is blocked. Implemented by child classes
  20382. */
  20383. get: function () {
  20384. return false;
  20385. },
  20386. enumerable: true,
  20387. configurable: true
  20388. });
  20389. /**
  20390. * Returns the mesh itself by default. Implemented by child classes
  20391. * @param camera defines the camera to use to pick the right LOD level
  20392. * @returns the currentAbstractMesh
  20393. */
  20394. AbstractMesh.prototype.getLOD = function (camera) {
  20395. return this;
  20396. };
  20397. /**
  20398. * Returns 0 by default. Implemented by child classes
  20399. * @returns an integer
  20400. */
  20401. AbstractMesh.prototype.getTotalVertices = function () {
  20402. return 0;
  20403. };
  20404. /**
  20405. * Returns null by default. Implemented by child classes
  20406. * @returns null
  20407. */
  20408. AbstractMesh.prototype.getIndices = function () {
  20409. return null;
  20410. };
  20411. /**
  20412. * Returns the array of the requested vertex data kind. Implemented by child classes
  20413. * @param kind defines the vertex data kind to use
  20414. * @returns null
  20415. */
  20416. AbstractMesh.prototype.getVerticesData = function (kind) {
  20417. return null;
  20418. };
  20419. /**
  20420. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20421. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20422. * Note that a new underlying VertexBuffer object is created each call.
  20423. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20424. * @param kind defines vertex data kind:
  20425. * * BABYLON.VertexBuffer.PositionKind
  20426. * * BABYLON.VertexBuffer.UVKind
  20427. * * BABYLON.VertexBuffer.UV2Kind
  20428. * * BABYLON.VertexBuffer.UV3Kind
  20429. * * BABYLON.VertexBuffer.UV4Kind
  20430. * * BABYLON.VertexBuffer.UV5Kind
  20431. * * BABYLON.VertexBuffer.UV6Kind
  20432. * * BABYLON.VertexBuffer.ColorKind
  20433. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20434. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20435. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20436. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20437. * @param data defines the data source
  20438. * @param updatable defines if the data must be flagged as updatable (or static)
  20439. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20440. * @returns the current mesh
  20441. */
  20442. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20443. return this;
  20444. };
  20445. /**
  20446. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20447. * If the mesh has no geometry, it is simply returned as it is.
  20448. * @param kind defines vertex data kind:
  20449. * * BABYLON.VertexBuffer.PositionKind
  20450. * * BABYLON.VertexBuffer.UVKind
  20451. * * BABYLON.VertexBuffer.UV2Kind
  20452. * * BABYLON.VertexBuffer.UV3Kind
  20453. * * BABYLON.VertexBuffer.UV4Kind
  20454. * * BABYLON.VertexBuffer.UV5Kind
  20455. * * BABYLON.VertexBuffer.UV6Kind
  20456. * * BABYLON.VertexBuffer.ColorKind
  20457. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20458. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20459. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20460. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20461. * @param data defines the data source
  20462. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20463. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20464. * @returns the current mesh
  20465. */
  20466. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20467. return this;
  20468. };
  20469. /**
  20470. * Sets the mesh indices,
  20471. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20472. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20473. * @param totalVertices Defines the total number of vertices
  20474. * @returns the current mesh
  20475. */
  20476. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20477. return this;
  20478. };
  20479. /**
  20480. * Gets a boolean indicating if specific vertex data is present
  20481. * @param kind defines the vertex data kind to use
  20482. * @returns true is data kind is present
  20483. */
  20484. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20485. return false;
  20486. };
  20487. /**
  20488. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20489. * @returns a BoundingInfo
  20490. */
  20491. AbstractMesh.prototype.getBoundingInfo = function () {
  20492. if (this._masterMesh) {
  20493. return this._masterMesh.getBoundingInfo();
  20494. }
  20495. if (!this._boundingInfo) {
  20496. // this._boundingInfo is being created here
  20497. this._updateBoundingInfo();
  20498. }
  20499. // cannot be null.
  20500. return this._boundingInfo;
  20501. };
  20502. /**
  20503. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20504. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20505. * @returns the current mesh
  20506. */
  20507. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20508. if (includeDescendants === void 0) { includeDescendants = true; }
  20509. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20510. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20511. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20512. if (maxDimension === 0) {
  20513. return this;
  20514. }
  20515. var scale = 1 / maxDimension;
  20516. this.scaling.scaleInPlace(scale);
  20517. return this;
  20518. };
  20519. /**
  20520. * Overwrite the current bounding info
  20521. * @param boundingInfo defines the new bounding info
  20522. * @returns the current mesh
  20523. */
  20524. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20525. this._boundingInfo = boundingInfo;
  20526. return this;
  20527. };
  20528. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20529. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20530. get: function () {
  20531. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20532. },
  20533. enumerable: true,
  20534. configurable: true
  20535. });
  20536. /** @hidden */
  20537. AbstractMesh.prototype._preActivate = function () {
  20538. };
  20539. /** @hidden */
  20540. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20541. };
  20542. /** @hidden */
  20543. AbstractMesh.prototype._activate = function (renderId) {
  20544. this._renderId = renderId;
  20545. };
  20546. /**
  20547. * Gets the current world matrix
  20548. * @returns a Matrix
  20549. */
  20550. AbstractMesh.prototype.getWorldMatrix = function () {
  20551. if (this._masterMesh) {
  20552. return this._masterMesh.getWorldMatrix();
  20553. }
  20554. return _super.prototype.getWorldMatrix.call(this);
  20555. };
  20556. /** @hidden */
  20557. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20558. if (this._masterMesh) {
  20559. return this._masterMesh._getWorldMatrixDeterminant();
  20560. }
  20561. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20562. };
  20563. // ================================== Point of View Movement =================================
  20564. /**
  20565. * Perform relative position change from the point of view of behind the front of the mesh.
  20566. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20567. * Supports definition of mesh facing forward or backward
  20568. * @param amountRight defines the distance on the right axis
  20569. * @param amountUp defines the distance on the up axis
  20570. * @param amountForward defines the distance on the forward axis
  20571. * @returns the current mesh
  20572. */
  20573. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20574. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20575. return this;
  20576. };
  20577. /**
  20578. * Calculate relative position change from the point of view of behind the front of the mesh.
  20579. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20580. * Supports definition of mesh facing forward or backward
  20581. * @param amountRight defines the distance on the right axis
  20582. * @param amountUp defines the distance on the up axis
  20583. * @param amountForward defines the distance on the forward axis
  20584. * @returns the new displacement vector
  20585. */
  20586. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20587. var rotMatrix = new BABYLON.Matrix();
  20588. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20589. rotQuaternion.toRotationMatrix(rotMatrix);
  20590. var translationDelta = BABYLON.Vector3.Zero();
  20591. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20592. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20593. return translationDelta;
  20594. };
  20595. // ================================== Point of View Rotation =================================
  20596. /**
  20597. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20598. * Supports definition of mesh facing forward or backward
  20599. * @param flipBack defines the flip
  20600. * @param twirlClockwise defines the twirl
  20601. * @param tiltRight defines the tilt
  20602. * @returns the current mesh
  20603. */
  20604. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20605. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20606. return this;
  20607. };
  20608. /**
  20609. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20610. * Supports definition of mesh facing forward or backward.
  20611. * @param flipBack defines the flip
  20612. * @param twirlClockwise defines the twirl
  20613. * @param tiltRight defines the tilt
  20614. * @returns the new rotation vector
  20615. */
  20616. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20617. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20618. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20619. };
  20620. /**
  20621. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20622. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20623. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20624. * @returns the new bounding vectors
  20625. */
  20626. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20627. if (includeDescendants === void 0) { includeDescendants = true; }
  20628. if (predicate === void 0) { predicate = null; }
  20629. // Ensures that all world matrix will be recomputed.
  20630. this.getScene().incrementRenderId();
  20631. this.computeWorldMatrix(true);
  20632. var min;
  20633. var max;
  20634. var boundingInfo = this.getBoundingInfo();
  20635. if (!this.subMeshes) {
  20636. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20637. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20638. }
  20639. else {
  20640. min = boundingInfo.boundingBox.minimumWorld;
  20641. max = boundingInfo.boundingBox.maximumWorld;
  20642. }
  20643. if (includeDescendants) {
  20644. var descendants = this.getDescendants(false);
  20645. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20646. var descendant = descendants_1[_i];
  20647. var childMesh = descendant;
  20648. childMesh.computeWorldMatrix(true);
  20649. // Filters meshes based on custom predicate function.
  20650. if (predicate && !predicate(childMesh)) {
  20651. continue;
  20652. }
  20653. //make sure we have the needed params to get mix and max
  20654. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20655. continue;
  20656. }
  20657. var childBoundingInfo = childMesh.getBoundingInfo();
  20658. var boundingBox = childBoundingInfo.boundingBox;
  20659. var minBox = boundingBox.minimumWorld;
  20660. var maxBox = boundingBox.maximumWorld;
  20661. BABYLON.Tools.CheckExtends(minBox, min, max);
  20662. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20663. }
  20664. }
  20665. return {
  20666. min: min,
  20667. max: max
  20668. };
  20669. };
  20670. /** @hidden */
  20671. AbstractMesh.prototype._updateBoundingInfo = function () {
  20672. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20673. this._boundingInfo.update(this.worldMatrixFromCache);
  20674. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20675. return this;
  20676. };
  20677. /** @hidden */
  20678. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20679. if (!this.subMeshes) {
  20680. return this;
  20681. }
  20682. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20683. var subMesh = this.subMeshes[subIndex];
  20684. if (!subMesh.IsGlobal) {
  20685. subMesh.updateBoundingInfo(matrix);
  20686. }
  20687. }
  20688. return this;
  20689. };
  20690. /** @hidden */
  20691. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20692. // Bounding info
  20693. this._updateBoundingInfo();
  20694. };
  20695. /**
  20696. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20697. * A mesh is in the frustum if its bounding box intersects the frustum
  20698. * @param frustumPlanes defines the frustum to test
  20699. * @returns true if the mesh is in the frustum planes
  20700. */
  20701. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20702. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20703. };
  20704. /**
  20705. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20706. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20707. * @param frustumPlanes defines the frustum to test
  20708. * @returns true if the mesh is completely in the frustum planes
  20709. */
  20710. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20711. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20712. };
  20713. /**
  20714. * True if the mesh intersects another mesh or a SolidParticle object
  20715. * @param mesh defines a target mesh or SolidParticle to test
  20716. * @param precise 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)
  20717. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20718. * @returns true if there is an intersection
  20719. */
  20720. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20721. if (precise === void 0) { precise = false; }
  20722. if (!this._boundingInfo || !mesh._boundingInfo) {
  20723. return false;
  20724. }
  20725. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20726. return true;
  20727. }
  20728. if (includeDescendants) {
  20729. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20730. var child = _a[_i];
  20731. if (child.intersectsMesh(mesh, precise, true)) {
  20732. return true;
  20733. }
  20734. }
  20735. }
  20736. return false;
  20737. };
  20738. /**
  20739. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20740. * @param point defines the point to test
  20741. * @returns true if there is an intersection
  20742. */
  20743. AbstractMesh.prototype.intersectsPoint = function (point) {
  20744. if (!this._boundingInfo) {
  20745. return false;
  20746. }
  20747. return this._boundingInfo.intersectsPoint(point);
  20748. };
  20749. /**
  20750. * Gets the position of the current mesh in camera space
  20751. * @param camera defines the camera to use
  20752. * @returns a position
  20753. */
  20754. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20755. if (camera === void 0) { camera = null; }
  20756. if (!camera) {
  20757. camera = this.getScene().activeCamera;
  20758. }
  20759. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20760. };
  20761. /**
  20762. * Returns the distance from the mesh to the active camera
  20763. * @param camera defines the camera to use
  20764. * @returns the distance
  20765. */
  20766. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20767. if (camera === void 0) { camera = null; }
  20768. if (!camera) {
  20769. camera = this.getScene().activeCamera;
  20770. }
  20771. return this.absolutePosition.subtract(camera.position).length();
  20772. };
  20773. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20774. // Collisions
  20775. /**
  20776. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20777. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20778. */
  20779. get: function () {
  20780. return this._checkCollisions;
  20781. },
  20782. set: function (collisionEnabled) {
  20783. this._checkCollisions = collisionEnabled;
  20784. if (this.getScene().workerCollisions) {
  20785. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20786. }
  20787. },
  20788. enumerable: true,
  20789. configurable: true
  20790. });
  20791. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20792. /**
  20793. * Gets Collider object used to compute collisions (not physics)
  20794. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20795. */
  20796. get: function () {
  20797. return this._collider;
  20798. },
  20799. enumerable: true,
  20800. configurable: true
  20801. });
  20802. /**
  20803. * Move the mesh using collision engine
  20804. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20805. * @param displacement defines the requested displacement vector
  20806. * @returns the current mesh
  20807. */
  20808. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20809. var globalPosition = this.getAbsolutePosition();
  20810. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20811. if (!this._collider) {
  20812. this._collider = new BABYLON.Collider();
  20813. }
  20814. this._collider._radius = this.ellipsoid;
  20815. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20816. return this;
  20817. };
  20818. // Collisions
  20819. /** @hidden */
  20820. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20821. this._generatePointsArray();
  20822. if (!this._positions) {
  20823. return this;
  20824. }
  20825. // Transformation
  20826. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20827. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20828. subMesh._lastColliderWorldVertices = [];
  20829. subMesh._trianglePlanes = [];
  20830. var start = subMesh.verticesStart;
  20831. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20832. for (var i = start; i < end; i++) {
  20833. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20834. }
  20835. }
  20836. // Collide
  20837. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20838. if (collider.collisionFound) {
  20839. collider.collidedMesh = this;
  20840. }
  20841. return this;
  20842. };
  20843. /** @hidden */
  20844. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20845. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20846. var len = subMeshes.length;
  20847. for (var index = 0; index < len; index++) {
  20848. var subMesh = subMeshes.data[index];
  20849. // Bounding test
  20850. if (len > 1 && !subMesh._checkCollision(collider))
  20851. continue;
  20852. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20853. }
  20854. return this;
  20855. };
  20856. /** @hidden */
  20857. AbstractMesh.prototype._checkCollision = function (collider) {
  20858. // Bounding box test
  20859. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20860. return this;
  20861. // Transformation matrix
  20862. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20863. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20864. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20865. return this;
  20866. };
  20867. // Picking
  20868. /** @hidden */
  20869. AbstractMesh.prototype._generatePointsArray = function () {
  20870. return false;
  20871. };
  20872. /**
  20873. * Checks if the passed Ray intersects with the mesh
  20874. * @param ray defines the ray to use
  20875. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20876. * @returns the picking info
  20877. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20878. */
  20879. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20880. var pickingInfo = new BABYLON.PickingInfo();
  20881. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20882. return pickingInfo;
  20883. }
  20884. if (!this._generatePointsArray()) {
  20885. return pickingInfo;
  20886. }
  20887. var intersectInfo = null;
  20888. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20889. var len = subMeshes.length;
  20890. for (var index = 0; index < len; index++) {
  20891. var subMesh = subMeshes.data[index];
  20892. // Bounding test
  20893. if (len > 1 && !subMesh.canIntersects(ray))
  20894. continue;
  20895. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20896. if (currentIntersectInfo) {
  20897. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20898. intersectInfo = currentIntersectInfo;
  20899. intersectInfo.subMeshId = index;
  20900. if (fastCheck) {
  20901. break;
  20902. }
  20903. }
  20904. }
  20905. }
  20906. if (intersectInfo) {
  20907. // Get picked point
  20908. var world = this.getWorldMatrix();
  20909. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20910. var direction = ray.direction.clone();
  20911. direction = direction.scale(intersectInfo.distance);
  20912. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20913. var pickedPoint = worldOrigin.add(worldDirection);
  20914. // Return result
  20915. pickingInfo.hit = true;
  20916. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20917. pickingInfo.pickedPoint = pickedPoint;
  20918. pickingInfo.pickedMesh = this;
  20919. pickingInfo.bu = intersectInfo.bu || 0;
  20920. pickingInfo.bv = intersectInfo.bv || 0;
  20921. pickingInfo.faceId = intersectInfo.faceId;
  20922. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20923. return pickingInfo;
  20924. }
  20925. return pickingInfo;
  20926. };
  20927. /**
  20928. * Clones the current mesh
  20929. * @param name defines the mesh name
  20930. * @param newParent defines the new mesh parent
  20931. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20932. * @returns the new mesh
  20933. */
  20934. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20935. return null;
  20936. };
  20937. /**
  20938. * Disposes all the submeshes of the current meshnp
  20939. * @returns the current mesh
  20940. */
  20941. AbstractMesh.prototype.releaseSubMeshes = function () {
  20942. if (this.subMeshes) {
  20943. while (this.subMeshes.length) {
  20944. this.subMeshes[0].dispose();
  20945. }
  20946. }
  20947. else {
  20948. this.subMeshes = new Array();
  20949. }
  20950. return this;
  20951. };
  20952. /**
  20953. * Releases resources associated with this abstract mesh.
  20954. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20955. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20956. */
  20957. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20958. var _this = this;
  20959. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20960. var index;
  20961. // Smart Array Retainers.
  20962. this.getScene().freeActiveMeshes();
  20963. this.getScene().freeRenderingGroups();
  20964. // Action manager
  20965. if (this.actionManager !== undefined && this.actionManager !== null) {
  20966. this.actionManager.dispose();
  20967. this.actionManager = null;
  20968. }
  20969. // Skeleton
  20970. this._skeleton = null;
  20971. // Intersections in progress
  20972. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20973. var other = this._intersectionsInProgress[index];
  20974. var pos = other._intersectionsInProgress.indexOf(this);
  20975. other._intersectionsInProgress.splice(pos, 1);
  20976. }
  20977. this._intersectionsInProgress = [];
  20978. // Lights
  20979. var lights = this.getScene().lights;
  20980. lights.forEach(function (light) {
  20981. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20982. if (meshIndex !== -1) {
  20983. light.includedOnlyMeshes.splice(meshIndex, 1);
  20984. }
  20985. meshIndex = light.excludedMeshes.indexOf(_this);
  20986. if (meshIndex !== -1) {
  20987. light.excludedMeshes.splice(meshIndex, 1);
  20988. }
  20989. // Shadow generators
  20990. var generator = light.getShadowGenerator();
  20991. if (generator) {
  20992. var shadowMap = generator.getShadowMap();
  20993. if (shadowMap && shadowMap.renderList) {
  20994. meshIndex = shadowMap.renderList.indexOf(_this);
  20995. if (meshIndex !== -1) {
  20996. shadowMap.renderList.splice(meshIndex, 1);
  20997. }
  20998. }
  20999. }
  21000. });
  21001. // SubMeshes
  21002. if (this.getClassName() !== "InstancedMesh") {
  21003. this.releaseSubMeshes();
  21004. }
  21005. // Query
  21006. var engine = this.getScene().getEngine();
  21007. if (this._occlusionQuery) {
  21008. this._isOcclusionQueryInProgress = false;
  21009. engine.deleteQuery(this._occlusionQuery);
  21010. this._occlusionQuery = null;
  21011. }
  21012. // Engine
  21013. engine.wipeCaches();
  21014. // Remove from scene
  21015. this.getScene().removeMesh(this);
  21016. if (disposeMaterialAndTextures) {
  21017. if (this.material) {
  21018. this.material.dispose(false, true);
  21019. }
  21020. }
  21021. if (!doNotRecurse) {
  21022. // Particles
  21023. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21024. if (this.getScene().particleSystems[index].emitter === this) {
  21025. this.getScene().particleSystems[index].dispose();
  21026. index--;
  21027. }
  21028. }
  21029. }
  21030. // facet data
  21031. if (this._facetDataEnabled) {
  21032. this.disableFacetData();
  21033. }
  21034. this.onAfterWorldMatrixUpdateObservable.clear();
  21035. this.onCollideObservable.clear();
  21036. this.onCollisionPositionChangeObservable.clear();
  21037. this.onRebuildObservable.clear();
  21038. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21039. };
  21040. /**
  21041. * Adds the passed mesh as a child to the current mesh
  21042. * @param mesh defines the child mesh
  21043. * @returns the current mesh
  21044. */
  21045. AbstractMesh.prototype.addChild = function (mesh) {
  21046. mesh.setParent(this);
  21047. return this;
  21048. };
  21049. /**
  21050. * Removes the passed mesh from the current mesh children list
  21051. * @param mesh defines the child mesh
  21052. * @returns the current mesh
  21053. */
  21054. AbstractMesh.prototype.removeChild = function (mesh) {
  21055. mesh.setParent(null);
  21056. return this;
  21057. };
  21058. // Facet data
  21059. /** @hidden */
  21060. AbstractMesh.prototype._initFacetData = function () {
  21061. if (!this._facetNormals) {
  21062. this._facetNormals = new Array();
  21063. }
  21064. if (!this._facetPositions) {
  21065. this._facetPositions = new Array();
  21066. }
  21067. if (!this._facetPartitioning) {
  21068. this._facetPartitioning = new Array();
  21069. }
  21070. this._facetNb = (this.getIndices().length / 3) | 0;
  21071. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21072. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21073. for (var f = 0; f < this._facetNb; f++) {
  21074. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21075. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21076. }
  21077. this._facetDataEnabled = true;
  21078. return this;
  21079. };
  21080. /**
  21081. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21082. * This method can be called within the render loop.
  21083. * 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
  21084. * @returns the current mesh
  21085. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21086. */
  21087. AbstractMesh.prototype.updateFacetData = function () {
  21088. if (!this._facetDataEnabled) {
  21089. this._initFacetData();
  21090. }
  21091. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21092. var indices = this.getIndices();
  21093. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21094. var bInfo = this.getBoundingInfo();
  21095. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21096. // init arrays, matrix and sort function on first call
  21097. this._facetDepthSortEnabled = true;
  21098. if (indices instanceof Uint16Array) {
  21099. this._depthSortedIndices = new Uint16Array(indices);
  21100. }
  21101. else if (indices instanceof Uint32Array) {
  21102. this._depthSortedIndices = new Uint32Array(indices);
  21103. }
  21104. else {
  21105. var needs32bits = false;
  21106. for (var i = 0; i < indices.length; i++) {
  21107. if (indices[i] > 65535) {
  21108. needs32bits = true;
  21109. break;
  21110. }
  21111. }
  21112. if (needs32bits) {
  21113. this._depthSortedIndices = new Uint32Array(indices);
  21114. }
  21115. else {
  21116. this._depthSortedIndices = new Uint16Array(indices);
  21117. }
  21118. }
  21119. this._facetDepthSortFunction = function (f1, f2) {
  21120. return (f2.sqDistance - f1.sqDistance);
  21121. };
  21122. if (!this._facetDepthSortFrom) {
  21123. var camera = this.getScene().activeCamera;
  21124. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21125. }
  21126. this._depthSortedFacets = [];
  21127. for (var f = 0; f < this._facetNb; f++) {
  21128. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21129. this._depthSortedFacets.push(depthSortedFacet);
  21130. }
  21131. this._invertedMatrix = BABYLON.Matrix.Identity();
  21132. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21133. }
  21134. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21135. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21136. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21137. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21138. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21139. this._subDiv.max = this._partitioningSubdivisions;
  21140. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21141. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21142. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21143. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21144. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21145. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21146. // set the parameters for ComputeNormals()
  21147. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21148. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21149. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21150. this._facetParameters.bInfo = bInfo;
  21151. this._facetParameters.bbSize = this._bbSize;
  21152. this._facetParameters.subDiv = this._subDiv;
  21153. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21154. this._facetParameters.depthSort = this._facetDepthSort;
  21155. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21156. this.computeWorldMatrix(true);
  21157. this._worldMatrix.invertToRef(this._invertedMatrix);
  21158. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21159. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21160. }
  21161. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21162. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21163. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21164. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21165. var l = (this._depthSortedIndices.length / 3) | 0;
  21166. for (var f = 0; f < l; f++) {
  21167. var sind = this._depthSortedFacets[f].ind;
  21168. this._depthSortedIndices[f * 3] = indices[sind];
  21169. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21170. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21171. }
  21172. this.updateIndices(this._depthSortedIndices);
  21173. }
  21174. return this;
  21175. };
  21176. /**
  21177. * Returns the facetLocalNormals array.
  21178. * The normals are expressed in the mesh local spac
  21179. * @returns an array of Vector3
  21180. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21181. */
  21182. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21183. if (!this._facetNormals) {
  21184. this.updateFacetData();
  21185. }
  21186. return this._facetNormals;
  21187. };
  21188. /**
  21189. * Returns the facetLocalPositions array.
  21190. * The facet positions are expressed in the mesh local space
  21191. * @returns an array of Vector3
  21192. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21193. */
  21194. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21195. if (!this._facetPositions) {
  21196. this.updateFacetData();
  21197. }
  21198. return this._facetPositions;
  21199. };
  21200. /**
  21201. * Returns the facetLocalPartioning array
  21202. * @returns an array of array of numbers
  21203. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21204. */
  21205. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21206. if (!this._facetPartitioning) {
  21207. this.updateFacetData();
  21208. }
  21209. return this._facetPartitioning;
  21210. };
  21211. /**
  21212. * Returns the i-th facet position in the world system.
  21213. * This method allocates a new Vector3 per call
  21214. * @param i defines the facet index
  21215. * @returns a new Vector3
  21216. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21217. */
  21218. AbstractMesh.prototype.getFacetPosition = function (i) {
  21219. var pos = BABYLON.Vector3.Zero();
  21220. this.getFacetPositionToRef(i, pos);
  21221. return pos;
  21222. };
  21223. /**
  21224. * Sets the reference Vector3 with the i-th facet position in the world system
  21225. * @param i defines the facet index
  21226. * @param ref defines the target vector
  21227. * @returns the current mesh
  21228. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21229. */
  21230. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21231. var localPos = (this.getFacetLocalPositions())[i];
  21232. var world = this.getWorldMatrix();
  21233. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21234. return this;
  21235. };
  21236. /**
  21237. * Returns the i-th facet normal in the world system.
  21238. * This method allocates a new Vector3 per call
  21239. * @param i defines the facet index
  21240. * @returns a new Vector3
  21241. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21242. */
  21243. AbstractMesh.prototype.getFacetNormal = function (i) {
  21244. var norm = BABYLON.Vector3.Zero();
  21245. this.getFacetNormalToRef(i, norm);
  21246. return norm;
  21247. };
  21248. /**
  21249. * Sets the reference Vector3 with the i-th facet normal in the world system
  21250. * @param i defines the facet index
  21251. * @param ref defines the target vector
  21252. * @returns the current mesh
  21253. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21254. */
  21255. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21256. var localNorm = (this.getFacetLocalNormals())[i];
  21257. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21258. return this;
  21259. };
  21260. /**
  21261. * 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)
  21262. * @param x defines x coordinate
  21263. * @param y defines y coordinate
  21264. * @param z defines z coordinate
  21265. * @returns the array of facet indexes
  21266. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21267. */
  21268. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21269. var bInfo = this.getBoundingInfo();
  21270. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21271. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21272. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21273. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21274. return null;
  21275. }
  21276. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21277. };
  21278. /**
  21279. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21280. * @param projected sets as the (x,y,z) world projection on the facet
  21281. * @param checkFace if 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
  21282. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21283. * @param x defines x coordinate
  21284. * @param y defines y coordinate
  21285. * @param z defines z coordinate
  21286. * @returns the face index if found (or null instead)
  21287. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21288. */
  21289. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21290. if (checkFace === void 0) { checkFace = false; }
  21291. if (facing === void 0) { facing = true; }
  21292. var world = this.getWorldMatrix();
  21293. var invMat = BABYLON.Tmp.Matrix[5];
  21294. world.invertToRef(invMat);
  21295. var invVect = BABYLON.Tmp.Vector3[8];
  21296. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21297. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21298. if (projected) {
  21299. // tranform the local computed projected vector to world coordinates
  21300. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21301. }
  21302. return closest;
  21303. };
  21304. /**
  21305. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21306. * @param projected sets as the (x,y,z) local projection on the facet
  21307. * @param checkFace if 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
  21308. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21309. * @param x defines x coordinate
  21310. * @param y defines y coordinate
  21311. * @param z defines z coordinate
  21312. * @returns the face index if found (or null instead)
  21313. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21314. */
  21315. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21316. if (checkFace === void 0) { checkFace = false; }
  21317. if (facing === void 0) { facing = true; }
  21318. var closest = null;
  21319. var tmpx = 0.0;
  21320. var tmpy = 0.0;
  21321. var tmpz = 0.0;
  21322. var d = 0.0; // tmp dot facet normal * facet position
  21323. var t0 = 0.0;
  21324. var projx = 0.0;
  21325. var projy = 0.0;
  21326. var projz = 0.0;
  21327. // Get all the facets in the same partitioning block than (x, y, z)
  21328. var facetPositions = this.getFacetLocalPositions();
  21329. var facetNormals = this.getFacetLocalNormals();
  21330. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21331. if (!facetsInBlock) {
  21332. return null;
  21333. }
  21334. // Get the closest facet to (x, y, z)
  21335. var shortest = Number.MAX_VALUE; // init distance vars
  21336. var tmpDistance = shortest;
  21337. var fib; // current facet in the block
  21338. var norm; // current facet normal
  21339. var p0; // current facet barycenter position
  21340. // loop on all the facets in the current partitioning block
  21341. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21342. fib = facetsInBlock[idx];
  21343. norm = facetNormals[fib];
  21344. p0 = facetPositions[fib];
  21345. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21346. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21347. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21348. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21349. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21350. projx = x + norm.x * t0;
  21351. projy = y + norm.y * t0;
  21352. projz = z + norm.z * t0;
  21353. tmpx = projx - x;
  21354. tmpy = projy - y;
  21355. tmpz = projz - z;
  21356. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21357. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21358. shortest = tmpDistance;
  21359. closest = fib;
  21360. if (projected) {
  21361. projected.x = projx;
  21362. projected.y = projy;
  21363. projected.z = projz;
  21364. }
  21365. }
  21366. }
  21367. }
  21368. return closest;
  21369. };
  21370. /**
  21371. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21372. * @returns the parameters
  21373. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21374. */
  21375. AbstractMesh.prototype.getFacetDataParameters = function () {
  21376. return this._facetParameters;
  21377. };
  21378. /**
  21379. * Disables the feature FacetData and frees the related memory
  21380. * @returns the current mesh
  21381. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21382. */
  21383. AbstractMesh.prototype.disableFacetData = function () {
  21384. if (this._facetDataEnabled) {
  21385. this._facetDataEnabled = false;
  21386. this._facetPositions = new Array();
  21387. this._facetNormals = new Array();
  21388. this._facetPartitioning = new Array();
  21389. this._facetParameters = null;
  21390. this._depthSortedIndices = new Uint32Array(0);
  21391. }
  21392. return this;
  21393. };
  21394. /**
  21395. * Updates the AbstractMesh indices array
  21396. * @param indices defines the data source
  21397. * @returns the current mesh
  21398. */
  21399. AbstractMesh.prototype.updateIndices = function (indices) {
  21400. return this;
  21401. };
  21402. /**
  21403. * Creates new normals data for the mesh
  21404. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21405. * @returns the current mesh
  21406. */
  21407. AbstractMesh.prototype.createNormals = function (updatable) {
  21408. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21409. var indices = this.getIndices();
  21410. var normals;
  21411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21412. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21413. }
  21414. else {
  21415. normals = [];
  21416. }
  21417. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21418. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21419. return this;
  21420. };
  21421. /**
  21422. * Align the mesh with a normal
  21423. * @param normal defines the normal to use
  21424. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21425. * @returns the current mesh
  21426. */
  21427. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21428. if (!upDirection) {
  21429. upDirection = BABYLON.Axis.Y;
  21430. }
  21431. var axisX = BABYLON.Tmp.Vector3[0];
  21432. var axisZ = BABYLON.Tmp.Vector3[1];
  21433. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21434. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21435. if (this.rotationQuaternion) {
  21436. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21437. }
  21438. else {
  21439. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21440. }
  21441. return this;
  21442. };
  21443. /** @hidden */
  21444. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21445. this._isOccluded = false;
  21446. };
  21447. /** No occlusion */
  21448. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21449. /** Occlusion set to optimisitic */
  21450. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21451. /** Occlusion set to strict */
  21452. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21453. /** Use an accurante occlusion algorithm */
  21454. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21455. /** Use a conservative occlusion algorithm */
  21456. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21457. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21458. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21459. /** Culling strategy with bounding sphere only and then frustum culling */
  21460. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21461. return AbstractMesh;
  21462. }(BABYLON.TransformNode));
  21463. BABYLON.AbstractMesh = AbstractMesh;
  21464. })(BABYLON || (BABYLON = {}));
  21465. //# sourceMappingURL=babylon.abstractMesh.js.map
  21466. var BABYLON;
  21467. (function (BABYLON) {
  21468. /**
  21469. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21470. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21471. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  21472. */
  21473. var Light = /** @class */ (function (_super) {
  21474. __extends(Light, _super);
  21475. /**
  21476. * Creates a Light object in the scene.
  21477. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21478. * @param name The firendly name of the light
  21479. * @param scene The scene the light belongs too
  21480. */
  21481. function Light(name, scene) {
  21482. var _this = _super.call(this, name, scene) || this;
  21483. /**
  21484. * Diffuse gives the basic color to an object.
  21485. */
  21486. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21487. /**
  21488. * Specular produces a highlight color on an object.
  21489. * Note: This is note affecting PBR materials.
  21490. */
  21491. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21492. /**
  21493. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21494. * falling off base on range or angle.
  21495. * This can be set to any values in Light.FALLOFF_x.
  21496. *
  21497. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21498. * other types of materials.
  21499. */
  21500. _this.falloffType = Light.FALLOFF_DEFAULT;
  21501. /**
  21502. * Strength of the light.
  21503. * Note: By default it is define in the framework own unit.
  21504. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21505. */
  21506. _this.intensity = 1.0;
  21507. _this._range = Number.MAX_VALUE;
  21508. _this._inverseSquaredRange = 0;
  21509. /**
  21510. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21511. * of light.
  21512. */
  21513. _this._photometricScale = 1.0;
  21514. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21515. _this._radius = 0.00001;
  21516. /**
  21517. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21518. * exceeding the number allowed of the materials.
  21519. */
  21520. _this.renderPriority = 0;
  21521. _this._shadowEnabled = true;
  21522. _this._excludeWithLayerMask = 0;
  21523. _this._includeOnlyWithLayerMask = 0;
  21524. _this._lightmapMode = 0;
  21525. /**
  21526. * @hidden Internal use only.
  21527. */
  21528. _this._excludedMeshesIds = new Array();
  21529. /**
  21530. * @hidden Internal use only.
  21531. */
  21532. _this._includedOnlyMeshesIds = new Array();
  21533. _this.getScene().addLight(_this);
  21534. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21535. _this._buildUniformLayout();
  21536. _this.includedOnlyMeshes = new Array();
  21537. _this.excludedMeshes = new Array();
  21538. _this._resyncMeshes();
  21539. return _this;
  21540. }
  21541. Object.defineProperty(Light.prototype, "range", {
  21542. /**
  21543. * Defines how far from the source the light is impacting in scene units.
  21544. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21545. */
  21546. get: function () {
  21547. return this._range;
  21548. },
  21549. /**
  21550. * Defines how far from the source the light is impacting in scene units.
  21551. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21552. */
  21553. set: function (value) {
  21554. this._range = value;
  21555. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21556. },
  21557. enumerable: true,
  21558. configurable: true
  21559. });
  21560. Object.defineProperty(Light.prototype, "intensityMode", {
  21561. /**
  21562. * Gets the photometric scale used to interpret the intensity.
  21563. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21564. */
  21565. get: function () {
  21566. return this._intensityMode;
  21567. },
  21568. /**
  21569. * Sets the photometric scale used to interpret the intensity.
  21570. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21571. */
  21572. set: function (value) {
  21573. this._intensityMode = value;
  21574. this._computePhotometricScale();
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. ;
  21580. ;
  21581. Object.defineProperty(Light.prototype, "radius", {
  21582. /**
  21583. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21584. */
  21585. get: function () {
  21586. return this._radius;
  21587. },
  21588. /**
  21589. * sets the light radius used by PBR Materials to simulate soft area lights.
  21590. */
  21591. set: function (value) {
  21592. this._radius = value;
  21593. this._computePhotometricScale();
  21594. },
  21595. enumerable: true,
  21596. configurable: true
  21597. });
  21598. ;
  21599. ;
  21600. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21601. /**
  21602. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21603. * the current shadow generator.
  21604. */
  21605. get: function () {
  21606. return this._shadowEnabled;
  21607. },
  21608. /**
  21609. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21610. * the current shadow generator.
  21611. */
  21612. set: function (value) {
  21613. if (this._shadowEnabled === value) {
  21614. return;
  21615. }
  21616. this._shadowEnabled = value;
  21617. this._markMeshesAsLightDirty();
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21623. /**
  21624. * Gets the only meshes impacted by this light.
  21625. */
  21626. get: function () {
  21627. return this._includedOnlyMeshes;
  21628. },
  21629. /**
  21630. * Sets the only meshes impacted by this light.
  21631. */
  21632. set: function (value) {
  21633. this._includedOnlyMeshes = value;
  21634. this._hookArrayForIncludedOnly(value);
  21635. },
  21636. enumerable: true,
  21637. configurable: true
  21638. });
  21639. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21640. /**
  21641. * Gets the meshes not impacted by this light.
  21642. */
  21643. get: function () {
  21644. return this._excludedMeshes;
  21645. },
  21646. /**
  21647. * Sets the meshes not impacted by this light.
  21648. */
  21649. set: function (value) {
  21650. this._excludedMeshes = value;
  21651. this._hookArrayForExcluded(value);
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21657. /**
  21658. * Gets the layer id use to find what meshes are not impacted by the light.
  21659. * Inactive if 0
  21660. */
  21661. get: function () {
  21662. return this._excludeWithLayerMask;
  21663. },
  21664. /**
  21665. * Sets the layer id use to find what meshes are not impacted by the light.
  21666. * Inactive if 0
  21667. */
  21668. set: function (value) {
  21669. this._excludeWithLayerMask = value;
  21670. this._resyncMeshes();
  21671. },
  21672. enumerable: true,
  21673. configurable: true
  21674. });
  21675. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21676. /**
  21677. * Gets the layer id use to find what meshes are impacted by the light.
  21678. * Inactive if 0
  21679. */
  21680. get: function () {
  21681. return this._includeOnlyWithLayerMask;
  21682. },
  21683. /**
  21684. * Sets the layer id use to find what meshes are impacted by the light.
  21685. * Inactive if 0
  21686. */
  21687. set: function (value) {
  21688. this._includeOnlyWithLayerMask = value;
  21689. this._resyncMeshes();
  21690. },
  21691. enumerable: true,
  21692. configurable: true
  21693. });
  21694. Object.defineProperty(Light.prototype, "lightmapMode", {
  21695. /**
  21696. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21697. */
  21698. get: function () {
  21699. return this._lightmapMode;
  21700. },
  21701. /**
  21702. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21703. */
  21704. set: function (value) {
  21705. if (this._lightmapMode === value) {
  21706. return;
  21707. }
  21708. this._lightmapMode = value;
  21709. this._markMeshesAsLightDirty();
  21710. },
  21711. enumerable: true,
  21712. configurable: true
  21713. });
  21714. /**
  21715. * Returns the string "Light".
  21716. * @returns the class name
  21717. */
  21718. Light.prototype.getClassName = function () {
  21719. return "Light";
  21720. };
  21721. /**
  21722. * Converts the light information to a readable string for debug purpose.
  21723. * @param fullDetails Supports for multiple levels of logging within scene loading
  21724. * @returns the human readable light info
  21725. */
  21726. Light.prototype.toString = function (fullDetails) {
  21727. var ret = "Name: " + this.name;
  21728. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21729. if (this.animations) {
  21730. for (var i = 0; i < this.animations.length; i++) {
  21731. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21732. }
  21733. }
  21734. if (fullDetails) {
  21735. }
  21736. return ret;
  21737. };
  21738. /** @hidden */
  21739. Light.prototype._syncParentEnabledState = function () {
  21740. _super.prototype._syncParentEnabledState.call(this);
  21741. this._resyncMeshes();
  21742. };
  21743. /**
  21744. * Set the enabled state of this node.
  21745. * @param value - the new enabled state
  21746. */
  21747. Light.prototype.setEnabled = function (value) {
  21748. _super.prototype.setEnabled.call(this, value);
  21749. this._resyncMeshes();
  21750. };
  21751. /**
  21752. * Returns the Light associated shadow generator if any.
  21753. * @return the associated shadow generator.
  21754. */
  21755. Light.prototype.getShadowGenerator = function () {
  21756. return this._shadowGenerator;
  21757. };
  21758. /**
  21759. * Returns a Vector3, the absolute light position in the World.
  21760. * @returns the world space position of the light
  21761. */
  21762. Light.prototype.getAbsolutePosition = function () {
  21763. return BABYLON.Vector3.Zero();
  21764. };
  21765. /**
  21766. * Specifies if the light will affect the passed mesh.
  21767. * @param mesh The mesh to test against the light
  21768. * @return true the mesh is affected otherwise, false.
  21769. */
  21770. Light.prototype.canAffectMesh = function (mesh) {
  21771. if (!mesh) {
  21772. return true;
  21773. }
  21774. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21775. return false;
  21776. }
  21777. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21778. return false;
  21779. }
  21780. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21781. return false;
  21782. }
  21783. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21784. return false;
  21785. }
  21786. return true;
  21787. };
  21788. /**
  21789. * Sort function to order lights for rendering.
  21790. * @param a First Light object to compare to second.
  21791. * @param b Second Light object to compare first.
  21792. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21793. */
  21794. Light.CompareLightsPriority = function (a, b) {
  21795. //shadow-casting lights have priority over non-shadow-casting lights
  21796. //the renderPrioirty is a secondary sort criterion
  21797. if (a.shadowEnabled !== b.shadowEnabled) {
  21798. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21799. }
  21800. return b.renderPriority - a.renderPriority;
  21801. };
  21802. /**
  21803. * Releases resources associated with this node.
  21804. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21805. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21806. */
  21807. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21808. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21809. if (this._shadowGenerator) {
  21810. this._shadowGenerator.dispose();
  21811. this._shadowGenerator = null;
  21812. }
  21813. // Animations
  21814. this.getScene().stopAnimation(this);
  21815. // Remove from meshes
  21816. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21817. var mesh = _a[_i];
  21818. mesh._removeLightSource(this);
  21819. }
  21820. this._uniformBuffer.dispose();
  21821. // Remove from scene
  21822. this.getScene().removeLight(this);
  21823. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21824. };
  21825. /**
  21826. * Returns the light type ID (integer).
  21827. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21828. */
  21829. Light.prototype.getTypeID = function () {
  21830. return 0;
  21831. };
  21832. /**
  21833. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21834. * @returns the scaled intensity in intensity mode unit
  21835. */
  21836. Light.prototype.getScaledIntensity = function () {
  21837. return this._photometricScale * this.intensity;
  21838. };
  21839. /**
  21840. * Returns a new Light object, named "name", from the current one.
  21841. * @param name The name of the cloned light
  21842. * @returns the new created light
  21843. */
  21844. Light.prototype.clone = function (name) {
  21845. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21846. if (!constructor) {
  21847. return null;
  21848. }
  21849. return BABYLON.SerializationHelper.Clone(constructor, this);
  21850. };
  21851. /**
  21852. * Serializes the current light into a Serialization object.
  21853. * @returns the serialized object.
  21854. */
  21855. Light.prototype.serialize = function () {
  21856. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21857. // Type
  21858. serializationObject.type = this.getTypeID();
  21859. // Parent
  21860. if (this.parent) {
  21861. serializationObject.parentId = this.parent.id;
  21862. }
  21863. // Inclusion / exclusions
  21864. if (this.excludedMeshes.length > 0) {
  21865. serializationObject.excludedMeshesIds = [];
  21866. this.excludedMeshes.forEach(function (mesh) {
  21867. serializationObject.excludedMeshesIds.push(mesh.id);
  21868. });
  21869. }
  21870. if (this.includedOnlyMeshes.length > 0) {
  21871. serializationObject.includedOnlyMeshesIds = [];
  21872. this.includedOnlyMeshes.forEach(function (mesh) {
  21873. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21874. });
  21875. }
  21876. // Animations
  21877. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21878. serializationObject.ranges = this.serializeAnimationRanges();
  21879. return serializationObject;
  21880. };
  21881. /**
  21882. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21883. * This new light is named "name" and added to the passed scene.
  21884. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21885. * @param name The friendly name of the light
  21886. * @param scene The scene the new light will belong to
  21887. * @returns the constructor function
  21888. */
  21889. Light.GetConstructorFromName = function (type, name, scene) {
  21890. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21891. if (constructorFunc) {
  21892. return constructorFunc;
  21893. }
  21894. // Default to no light for none present once.
  21895. return null;
  21896. };
  21897. /**
  21898. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21899. * @param parsedLight The JSON representation of the light
  21900. * @param scene The scene to create the parsed light in
  21901. * @returns the created light after parsing
  21902. */
  21903. Light.Parse = function (parsedLight, scene) {
  21904. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21905. if (!constructor) {
  21906. return null;
  21907. }
  21908. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21909. // Inclusion / exclusions
  21910. if (parsedLight.excludedMeshesIds) {
  21911. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21912. }
  21913. if (parsedLight.includedOnlyMeshesIds) {
  21914. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21915. }
  21916. // Parent
  21917. if (parsedLight.parentId) {
  21918. light._waitingParentId = parsedLight.parentId;
  21919. }
  21920. // Animations
  21921. if (parsedLight.animations) {
  21922. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21923. var parsedAnimation = parsedLight.animations[animationIndex];
  21924. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21925. }
  21926. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21927. }
  21928. if (parsedLight.autoAnimate) {
  21929. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21930. }
  21931. return light;
  21932. };
  21933. Light.prototype._hookArrayForExcluded = function (array) {
  21934. var _this = this;
  21935. var oldPush = array.push;
  21936. array.push = function () {
  21937. var items = [];
  21938. for (var _i = 0; _i < arguments.length; _i++) {
  21939. items[_i] = arguments[_i];
  21940. }
  21941. var result = oldPush.apply(array, items);
  21942. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21943. var item = items_1[_a];
  21944. item._resyncLighSource(_this);
  21945. }
  21946. return result;
  21947. };
  21948. var oldSplice = array.splice;
  21949. array.splice = function (index, deleteCount) {
  21950. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21951. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21952. var item = deleted_1[_i];
  21953. item._resyncLighSource(_this);
  21954. }
  21955. return deleted;
  21956. };
  21957. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21958. var item = array_1[_i];
  21959. item._resyncLighSource(this);
  21960. }
  21961. };
  21962. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21963. var _this = this;
  21964. var oldPush = array.push;
  21965. array.push = function () {
  21966. var items = [];
  21967. for (var _i = 0; _i < arguments.length; _i++) {
  21968. items[_i] = arguments[_i];
  21969. }
  21970. var result = oldPush.apply(array, items);
  21971. _this._resyncMeshes();
  21972. return result;
  21973. };
  21974. var oldSplice = array.splice;
  21975. array.splice = function (index, deleteCount) {
  21976. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21977. _this._resyncMeshes();
  21978. return deleted;
  21979. };
  21980. this._resyncMeshes();
  21981. };
  21982. Light.prototype._resyncMeshes = function () {
  21983. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21984. var mesh = _a[_i];
  21985. mesh._resyncLighSource(this);
  21986. }
  21987. };
  21988. /**
  21989. * Forces the meshes to update their light related information in their rendering used effects
  21990. * @hidden Internal Use Only
  21991. */
  21992. Light.prototype._markMeshesAsLightDirty = function () {
  21993. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21994. var mesh = _a[_i];
  21995. if (mesh._lightSources.indexOf(this) !== -1) {
  21996. mesh._markSubMeshesAsLightDirty();
  21997. }
  21998. }
  21999. };
  22000. /**
  22001. * Recomputes the cached photometric scale if needed.
  22002. */
  22003. Light.prototype._computePhotometricScale = function () {
  22004. this._photometricScale = this._getPhotometricScale();
  22005. this.getScene().resetCachedMaterial();
  22006. };
  22007. /**
  22008. * Returns the Photometric Scale according to the light type and intensity mode.
  22009. */
  22010. Light.prototype._getPhotometricScale = function () {
  22011. var photometricScale = 0.0;
  22012. var lightTypeID = this.getTypeID();
  22013. //get photometric mode
  22014. var photometricMode = this.intensityMode;
  22015. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22016. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22017. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22018. }
  22019. else {
  22020. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22021. }
  22022. }
  22023. //compute photometric scale
  22024. switch (lightTypeID) {
  22025. case Light.LIGHTTYPEID_POINTLIGHT:
  22026. case Light.LIGHTTYPEID_SPOTLIGHT:
  22027. switch (photometricMode) {
  22028. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22029. photometricScale = 1.0 / (4.0 * Math.PI);
  22030. break;
  22031. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22032. photometricScale = 1.0;
  22033. break;
  22034. case Light.INTENSITYMODE_LUMINANCE:
  22035. photometricScale = this.radius * this.radius;
  22036. break;
  22037. }
  22038. break;
  22039. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22040. switch (photometricMode) {
  22041. case Light.INTENSITYMODE_ILLUMINANCE:
  22042. photometricScale = 1.0;
  22043. break;
  22044. case Light.INTENSITYMODE_LUMINANCE:
  22045. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22046. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22047. var apexAngleRadians = this.radius;
  22048. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22049. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22050. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22051. photometricScale = solidAngle;
  22052. break;
  22053. }
  22054. break;
  22055. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22056. // No fall off in hemisperic light.
  22057. photometricScale = 1.0;
  22058. break;
  22059. }
  22060. return photometricScale;
  22061. };
  22062. /**
  22063. * Reorder the light in the scene according to their defined priority.
  22064. * @hidden Internal Use Only
  22065. */
  22066. Light.prototype._reorderLightsInScene = function () {
  22067. var scene = this.getScene();
  22068. if (this._renderPriority != 0) {
  22069. scene.requireLightSorting = true;
  22070. }
  22071. this.getScene().sortLightsByPriority();
  22072. };
  22073. /**
  22074. * Falloff Default: light is falling off following the material specification:
  22075. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22076. */
  22077. Light.FALLOFF_DEFAULT = 0;
  22078. /**
  22079. * Falloff Physical: light is falling off following the inverse squared distance law.
  22080. */
  22081. Light.FALLOFF_PHYSICAL = 1;
  22082. /**
  22083. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22084. * to enhance interoperability with other engines.
  22085. */
  22086. Light.FALLOFF_GLTF = 2;
  22087. /**
  22088. * Falloff Standard: light is falling off like in the standard material
  22089. * to enhance interoperability with other materials.
  22090. */
  22091. Light.FALLOFF_STANDARD = 3;
  22092. //lightmapMode Consts
  22093. /**
  22094. * If every light affecting the material is in this lightmapMode,
  22095. * material.lightmapTexture adds or multiplies
  22096. * (depends on material.useLightmapAsShadowmap)
  22097. * after every other light calculations.
  22098. */
  22099. Light.LIGHTMAP_DEFAULT = 0;
  22100. /**
  22101. * material.lightmapTexture as only diffuse lighting from this light
  22102. * adds only specular lighting from this light
  22103. * adds dynamic shadows
  22104. */
  22105. Light.LIGHTMAP_SPECULAR = 1;
  22106. /**
  22107. * material.lightmapTexture as only lighting
  22108. * no light calculation from this light
  22109. * only adds dynamic shadows from this light
  22110. */
  22111. Light.LIGHTMAP_SHADOWSONLY = 2;
  22112. // Intensity Mode Consts
  22113. /**
  22114. * Each light type uses the default quantity according to its type:
  22115. * point/spot lights use luminous intensity
  22116. * directional lights use illuminance
  22117. */
  22118. Light.INTENSITYMODE_AUTOMATIC = 0;
  22119. /**
  22120. * lumen (lm)
  22121. */
  22122. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22123. /**
  22124. * candela (lm/sr)
  22125. */
  22126. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22127. /**
  22128. * lux (lm/m^2)
  22129. */
  22130. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22131. /**
  22132. * nit (cd/m^2)
  22133. */
  22134. Light.INTENSITYMODE_LUMINANCE = 4;
  22135. // Light types ids const.
  22136. /**
  22137. * Light type const id of the point light.
  22138. */
  22139. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22140. /**
  22141. * Light type const id of the directional light.
  22142. */
  22143. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22144. /**
  22145. * Light type const id of the spot light.
  22146. */
  22147. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22148. /**
  22149. * Light type const id of the hemispheric light.
  22150. */
  22151. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22152. __decorate([
  22153. BABYLON.serializeAsColor3()
  22154. ], Light.prototype, "diffuse", void 0);
  22155. __decorate([
  22156. BABYLON.serializeAsColor3()
  22157. ], Light.prototype, "specular", void 0);
  22158. __decorate([
  22159. BABYLON.serialize()
  22160. ], Light.prototype, "falloffType", void 0);
  22161. __decorate([
  22162. BABYLON.serialize()
  22163. ], Light.prototype, "intensity", void 0);
  22164. __decorate([
  22165. BABYLON.serialize()
  22166. ], Light.prototype, "range", null);
  22167. __decorate([
  22168. BABYLON.serialize()
  22169. ], Light.prototype, "intensityMode", null);
  22170. __decorate([
  22171. BABYLON.serialize()
  22172. ], Light.prototype, "radius", null);
  22173. __decorate([
  22174. BABYLON.serialize()
  22175. ], Light.prototype, "_renderPriority", void 0);
  22176. __decorate([
  22177. BABYLON.expandToProperty("_reorderLightsInScene")
  22178. ], Light.prototype, "renderPriority", void 0);
  22179. __decorate([
  22180. BABYLON.serialize("shadowEnabled")
  22181. ], Light.prototype, "_shadowEnabled", void 0);
  22182. __decorate([
  22183. BABYLON.serialize("excludeWithLayerMask")
  22184. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22185. __decorate([
  22186. BABYLON.serialize("includeOnlyWithLayerMask")
  22187. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22188. __decorate([
  22189. BABYLON.serialize("lightmapMode")
  22190. ], Light.prototype, "_lightmapMode", void 0);
  22191. return Light;
  22192. }(BABYLON.Node));
  22193. BABYLON.Light = Light;
  22194. })(BABYLON || (BABYLON = {}));
  22195. //# sourceMappingURL=babylon.light.js.map
  22196. var BABYLON;
  22197. (function (BABYLON) {
  22198. /**
  22199. * This is the base class of all the camera used in the application.
  22200. * @see http://doc.babylonjs.com/features/cameras
  22201. */
  22202. var Camera = /** @class */ (function (_super) {
  22203. __extends(Camera, _super);
  22204. /**
  22205. * Instantiates a new camera object.
  22206. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22207. * @see http://doc.babylonjs.com/features/cameras
  22208. * @param name Defines the name of the camera in the scene
  22209. * @param position Defines the position of the camera
  22210. * @param scene Defines the scene the camera belongs too
  22211. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22212. */
  22213. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22214. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22215. var _this = _super.call(this, name, scene) || this;
  22216. /**
  22217. * The vector the camera should consider as up.
  22218. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22219. */
  22220. _this.upVector = BABYLON.Vector3.Up();
  22221. /**
  22222. * Define the current limit on the left side for an orthographic camera
  22223. * In scene unit
  22224. */
  22225. _this.orthoLeft = null;
  22226. /**
  22227. * Define the current limit on the right side for an orthographic camera
  22228. * In scene unit
  22229. */
  22230. _this.orthoRight = null;
  22231. /**
  22232. * Define the current limit on the bottom side for an orthographic camera
  22233. * In scene unit
  22234. */
  22235. _this.orthoBottom = null;
  22236. /**
  22237. * Define the current limit on the top side for an orthographic camera
  22238. * In scene unit
  22239. */
  22240. _this.orthoTop = null;
  22241. /**
  22242. * Field Of View is set in Radians. (default is 0.8)
  22243. */
  22244. _this.fov = 0.8;
  22245. /**
  22246. * Define the minimum distance the camera can see from.
  22247. * This is important to note that the depth buffer are not infinite and the closer it starts
  22248. * the more your scene might encounter depth fighting issue.
  22249. */
  22250. _this.minZ = 1;
  22251. /**
  22252. * Define the maximum distance the camera can see to.
  22253. * This is important to note that the depth buffer are not infinite and the further it end
  22254. * the more your scene might encounter depth fighting issue.
  22255. */
  22256. _this.maxZ = 10000.0;
  22257. /**
  22258. * Define the default inertia of the camera.
  22259. * This helps giving a smooth feeling to the camera movement.
  22260. */
  22261. _this.inertia = 0.9;
  22262. /**
  22263. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22264. */
  22265. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22266. /**
  22267. * Define wether the camera is intermediate.
  22268. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22269. */
  22270. _this.isIntermediate = false;
  22271. /**
  22272. * Define the viewport of the camera.
  22273. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22274. */
  22275. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22276. /**
  22277. * Restricts the camera to viewing objects with the same layerMask.
  22278. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22279. */
  22280. _this.layerMask = 0x0FFFFFFF;
  22281. /**
  22282. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22283. */
  22284. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22285. /**
  22286. * Rig mode of the camera.
  22287. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22288. * This is normally controlled byt the camera themselves as internal use.
  22289. */
  22290. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22291. /**
  22292. * Defines the list of custom render target the camera should render to.
  22293. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22294. * else in the scene.
  22295. */
  22296. _this.customRenderTargets = new Array();
  22297. /**
  22298. * Observable triggered when the camera view matrix has changed.
  22299. */
  22300. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22301. /**
  22302. * Observable triggered when the camera Projection matrix has changed.
  22303. */
  22304. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22305. /**
  22306. * Observable triggered when the inputs have been processed.
  22307. */
  22308. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22309. /**
  22310. * Observable triggered when reset has been called and applied to the camera.
  22311. */
  22312. _this.onRestoreStateObservable = new BABYLON.Observable();
  22313. /** @hidden */
  22314. _this._rigCameras = new Array();
  22315. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22316. /** @hidden */
  22317. _this._skipRendering = false;
  22318. /** @hidden */
  22319. _this._projectionMatrix = new BABYLON.Matrix();
  22320. /** @hidden */
  22321. _this._postProcesses = new Array();
  22322. /** @hidden */
  22323. _this._activeMeshes = new BABYLON.SmartArray(256);
  22324. _this._globalPosition = BABYLON.Vector3.Zero();
  22325. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22326. _this._doNotComputeProjectionMatrix = false;
  22327. _this._transformMatrix = BABYLON.Matrix.Zero();
  22328. _this._refreshFrustumPlanes = true;
  22329. _this.getScene().addCamera(_this);
  22330. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22331. _this.getScene().activeCamera = _this;
  22332. }
  22333. _this.position = position;
  22334. return _this;
  22335. }
  22336. /**
  22337. * Store current camera state (fov, position, etc..)
  22338. * @returns the camera
  22339. */
  22340. Camera.prototype.storeState = function () {
  22341. this._stateStored = true;
  22342. this._storedFov = this.fov;
  22343. return this;
  22344. };
  22345. /**
  22346. * Restores the camera state values if it has been stored. You must call storeState() first
  22347. */
  22348. Camera.prototype._restoreStateValues = function () {
  22349. if (!this._stateStored) {
  22350. return false;
  22351. }
  22352. this.fov = this._storedFov;
  22353. return true;
  22354. };
  22355. /**
  22356. * Restored camera state. You must call storeState() first.
  22357. * @returns true if restored and false otherwise
  22358. */
  22359. Camera.prototype.restoreState = function () {
  22360. if (this._restoreStateValues()) {
  22361. this.onRestoreStateObservable.notifyObservers(this);
  22362. return true;
  22363. }
  22364. return false;
  22365. };
  22366. /**
  22367. * Gets the class name of the camera.
  22368. * @returns the class name
  22369. */
  22370. Camera.prototype.getClassName = function () {
  22371. return "Camera";
  22372. };
  22373. /**
  22374. * Gets a string representation of the camera usefull for debug purpose.
  22375. * @param fullDetails Defines that a more verboe level of logging is required
  22376. * @returns the string representation
  22377. */
  22378. Camera.prototype.toString = function (fullDetails) {
  22379. var ret = "Name: " + this.name;
  22380. ret += ", type: " + this.getClassName();
  22381. if (this.animations) {
  22382. for (var i = 0; i < this.animations.length; i++) {
  22383. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22384. }
  22385. }
  22386. if (fullDetails) {
  22387. }
  22388. return ret;
  22389. };
  22390. Object.defineProperty(Camera.prototype, "globalPosition", {
  22391. /**
  22392. * Gets the current world space position of the camera.
  22393. */
  22394. get: function () {
  22395. return this._globalPosition;
  22396. },
  22397. enumerable: true,
  22398. configurable: true
  22399. });
  22400. /**
  22401. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22402. * @returns the active meshe list
  22403. */
  22404. Camera.prototype.getActiveMeshes = function () {
  22405. return this._activeMeshes;
  22406. };
  22407. /**
  22408. * Check wether a mesh is part of the current active mesh list of the camera
  22409. * @param mesh Defines the mesh to check
  22410. * @returns true if active, false otherwise
  22411. */
  22412. Camera.prototype.isActiveMesh = function (mesh) {
  22413. return (this._activeMeshes.indexOf(mesh) !== -1);
  22414. };
  22415. /**
  22416. * Is this camera ready to be used/rendered
  22417. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22418. * @return true if the camera is ready
  22419. */
  22420. Camera.prototype.isReady = function (completeCheck) {
  22421. if (completeCheck === void 0) { completeCheck = false; }
  22422. if (completeCheck) {
  22423. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22424. var pp = _a[_i];
  22425. if (pp && !pp.isReady()) {
  22426. return false;
  22427. }
  22428. }
  22429. }
  22430. return _super.prototype.isReady.call(this, completeCheck);
  22431. };
  22432. /** @hidden */
  22433. Camera.prototype._initCache = function () {
  22434. _super.prototype._initCache.call(this);
  22435. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22436. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22437. this._cache.mode = undefined;
  22438. this._cache.minZ = undefined;
  22439. this._cache.maxZ = undefined;
  22440. this._cache.fov = undefined;
  22441. this._cache.fovMode = undefined;
  22442. this._cache.aspectRatio = undefined;
  22443. this._cache.orthoLeft = undefined;
  22444. this._cache.orthoRight = undefined;
  22445. this._cache.orthoBottom = undefined;
  22446. this._cache.orthoTop = undefined;
  22447. this._cache.renderWidth = undefined;
  22448. this._cache.renderHeight = undefined;
  22449. };
  22450. /** @hidden */
  22451. Camera.prototype._updateCache = function (ignoreParentClass) {
  22452. if (!ignoreParentClass) {
  22453. _super.prototype._updateCache.call(this);
  22454. }
  22455. this._cache.position.copyFrom(this.position);
  22456. this._cache.upVector.copyFrom(this.upVector);
  22457. };
  22458. /** @hidden */
  22459. Camera.prototype._isSynchronized = function () {
  22460. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22461. };
  22462. /** @hidden */
  22463. Camera.prototype._isSynchronizedViewMatrix = function () {
  22464. if (!_super.prototype._isSynchronized.call(this))
  22465. return false;
  22466. return this._cache.position.equals(this.position)
  22467. && this._cache.upVector.equals(this.upVector)
  22468. && this.isSynchronizedWithParent();
  22469. };
  22470. /** @hidden */
  22471. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22472. var check = this._cache.mode === this.mode
  22473. && this._cache.minZ === this.minZ
  22474. && this._cache.maxZ === this.maxZ;
  22475. if (!check) {
  22476. return false;
  22477. }
  22478. var engine = this.getEngine();
  22479. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22480. check = this._cache.fov === this.fov
  22481. && this._cache.fovMode === this.fovMode
  22482. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22483. }
  22484. else {
  22485. check = this._cache.orthoLeft === this.orthoLeft
  22486. && this._cache.orthoRight === this.orthoRight
  22487. && this._cache.orthoBottom === this.orthoBottom
  22488. && this._cache.orthoTop === this.orthoTop
  22489. && this._cache.renderWidth === engine.getRenderWidth()
  22490. && this._cache.renderHeight === engine.getRenderHeight();
  22491. }
  22492. return check;
  22493. };
  22494. /**
  22495. * Attach the input controls to a specific dom element to get the input from.
  22496. * @param element Defines the element the controls should be listened from
  22497. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22498. */
  22499. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22500. };
  22501. /**
  22502. * Detach the current controls from the specified dom element.
  22503. * @param element Defines the element to stop listening the inputs from
  22504. */
  22505. Camera.prototype.detachControl = function (element) {
  22506. };
  22507. /**
  22508. * Update the camera state according to the different inputs gathered during the frame.
  22509. */
  22510. Camera.prototype.update = function () {
  22511. this._checkInputs();
  22512. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22513. this._updateRigCameras();
  22514. }
  22515. };
  22516. /** @hidden */
  22517. Camera.prototype._checkInputs = function () {
  22518. this.onAfterCheckInputsObservable.notifyObservers(this);
  22519. };
  22520. Object.defineProperty(Camera.prototype, "rigCameras", {
  22521. /** @hidden */
  22522. get: function () {
  22523. return this._rigCameras;
  22524. },
  22525. enumerable: true,
  22526. configurable: true
  22527. });
  22528. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22529. get: function () {
  22530. return this._rigPostProcess;
  22531. },
  22532. enumerable: true,
  22533. configurable: true
  22534. });
  22535. /**
  22536. * Internal, gets the first post proces.
  22537. * @returns the first post process to be run on this camera.
  22538. */
  22539. Camera.prototype._getFirstPostProcess = function () {
  22540. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22541. if (this._postProcesses[ppIndex] !== null) {
  22542. return this._postProcesses[ppIndex];
  22543. }
  22544. }
  22545. return null;
  22546. };
  22547. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22548. // invalidate framebuffer
  22549. var firstPostProcess = this._getFirstPostProcess();
  22550. if (firstPostProcess) {
  22551. firstPostProcess.markTextureDirty();
  22552. }
  22553. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22554. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22555. var cam = this._rigCameras[i];
  22556. var rigPostProcess = cam._rigPostProcess;
  22557. // for VR rig, there does not have to be a post process
  22558. if (rigPostProcess) {
  22559. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22560. if (isPass) {
  22561. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22562. cam.isIntermediate = this._postProcesses.length === 0;
  22563. }
  22564. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22565. rigPostProcess.markTextureDirty();
  22566. }
  22567. else {
  22568. cam._postProcesses = this._postProcesses.slice(0);
  22569. }
  22570. }
  22571. };
  22572. /**
  22573. * Attach a post process to the camera.
  22574. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22575. * @param postProcess The post process to attach to the camera
  22576. * @param insertAt The position of the post process in case several of them are in use in the scene
  22577. * @returns the position the post process has been inserted at
  22578. */
  22579. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22580. if (insertAt === void 0) { insertAt = null; }
  22581. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22582. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22583. return 0;
  22584. }
  22585. if (insertAt == null || insertAt < 0) {
  22586. this._postProcesses.push(postProcess);
  22587. }
  22588. else if (this._postProcesses[insertAt] === null) {
  22589. this._postProcesses[insertAt] = postProcess;
  22590. }
  22591. else {
  22592. this._postProcesses.splice(insertAt, 0, postProcess);
  22593. }
  22594. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22595. return this._postProcesses.indexOf(postProcess);
  22596. };
  22597. /**
  22598. * Detach a post process to the camera.
  22599. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22600. * @param postProcess The post process to detach from the camera
  22601. */
  22602. Camera.prototype.detachPostProcess = function (postProcess) {
  22603. var idx = this._postProcesses.indexOf(postProcess);
  22604. if (idx !== -1) {
  22605. this._postProcesses[idx] = null;
  22606. }
  22607. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22608. };
  22609. /**
  22610. * Gets the current world matrix of the camera
  22611. */
  22612. Camera.prototype.getWorldMatrix = function () {
  22613. if (this._isSynchronizedViewMatrix()) {
  22614. return this._worldMatrix;
  22615. }
  22616. // Getting the the view matrix will also compute the world matrix.
  22617. this.getViewMatrix();
  22618. return this._worldMatrix;
  22619. };
  22620. /** @hidden */
  22621. Camera.prototype._getViewMatrix = function () {
  22622. return BABYLON.Matrix.Identity();
  22623. };
  22624. /**
  22625. * Gets the current view matrix of the camera.
  22626. * @param force forces the camera to recompute the matrix without looking at the cached state
  22627. * @returns the view matrix
  22628. */
  22629. Camera.prototype.getViewMatrix = function (force) {
  22630. if (!force && this._isSynchronizedViewMatrix()) {
  22631. return this._computedViewMatrix;
  22632. }
  22633. this.updateCache();
  22634. this._computedViewMatrix = this._getViewMatrix();
  22635. this._currentRenderId = this.getScene().getRenderId();
  22636. this._childRenderId = this._currentRenderId;
  22637. this._refreshFrustumPlanes = true;
  22638. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22639. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22640. }
  22641. this.onViewMatrixChangedObservable.notifyObservers(this);
  22642. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22643. return this._computedViewMatrix;
  22644. };
  22645. /**
  22646. * Freeze the projection matrix.
  22647. * It will prevent the cache check of the camera projection compute and can speed up perf
  22648. * if no parameter of the camera are meant to change
  22649. * @param projection Defines manually a projection if necessary
  22650. */
  22651. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22652. this._doNotComputeProjectionMatrix = true;
  22653. if (projection !== undefined) {
  22654. this._projectionMatrix = projection;
  22655. }
  22656. };
  22657. ;
  22658. /**
  22659. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22660. */
  22661. Camera.prototype.unfreezeProjectionMatrix = function () {
  22662. this._doNotComputeProjectionMatrix = false;
  22663. };
  22664. ;
  22665. /**
  22666. * Gets the current projection matrix of the camera.
  22667. * @param force forces the camera to recompute the matrix without looking at the cached state
  22668. * @returns the projection matrix
  22669. */
  22670. Camera.prototype.getProjectionMatrix = function (force) {
  22671. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22672. return this._projectionMatrix;
  22673. }
  22674. // Cache
  22675. this._cache.mode = this.mode;
  22676. this._cache.minZ = this.minZ;
  22677. this._cache.maxZ = this.maxZ;
  22678. // Matrix
  22679. this._refreshFrustumPlanes = true;
  22680. var engine = this.getEngine();
  22681. var scene = this.getScene();
  22682. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22683. this._cache.fov = this.fov;
  22684. this._cache.fovMode = this.fovMode;
  22685. this._cache.aspectRatio = engine.getAspectRatio(this);
  22686. if (this.minZ <= 0) {
  22687. this.minZ = 0.1;
  22688. }
  22689. if (scene.useRightHandedSystem) {
  22690. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22691. }
  22692. else {
  22693. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22694. }
  22695. }
  22696. else {
  22697. var halfWidth = engine.getRenderWidth() / 2.0;
  22698. var halfHeight = engine.getRenderHeight() / 2.0;
  22699. if (scene.useRightHandedSystem) {
  22700. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22701. }
  22702. else {
  22703. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22704. }
  22705. this._cache.orthoLeft = this.orthoLeft;
  22706. this._cache.orthoRight = this.orthoRight;
  22707. this._cache.orthoBottom = this.orthoBottom;
  22708. this._cache.orthoTop = this.orthoTop;
  22709. this._cache.renderWidth = engine.getRenderWidth();
  22710. this._cache.renderHeight = engine.getRenderHeight();
  22711. }
  22712. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22713. return this._projectionMatrix;
  22714. };
  22715. /**
  22716. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22717. * @returns a Matrix
  22718. */
  22719. Camera.prototype.getTransformationMatrix = function () {
  22720. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22721. return this._transformMatrix;
  22722. };
  22723. Camera.prototype._updateFrustumPlanes = function () {
  22724. if (!this._refreshFrustumPlanes) {
  22725. return;
  22726. }
  22727. this.getTransformationMatrix();
  22728. if (!this._frustumPlanes) {
  22729. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22730. }
  22731. else {
  22732. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22733. }
  22734. this._refreshFrustumPlanes = false;
  22735. };
  22736. /**
  22737. * Checks if a cullable object (mesh...) is in the camera frustum
  22738. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  22739. * @param target The object to check
  22740. * @returns true if the object is in frustum otherwise false
  22741. */
  22742. Camera.prototype.isInFrustum = function (target) {
  22743. this._updateFrustumPlanes();
  22744. return target.isInFrustum(this._frustumPlanes);
  22745. };
  22746. /**
  22747. * Checks if a cullable object (mesh...) is in the camera frustum
  22748. * Unlike isInFrustum this cheks the full bounding box
  22749. * @param target The object to check
  22750. * @returns true if the object is in frustum otherwise false
  22751. */
  22752. Camera.prototype.isCompletelyInFrustum = function (target) {
  22753. this._updateFrustumPlanes();
  22754. return target.isCompletelyInFrustum(this._frustumPlanes);
  22755. };
  22756. /**
  22757. * Gets a ray in the forward direction from the camera.
  22758. * @param length Defines the length of the ray to create
  22759. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  22760. * @param origin Defines the start point of the ray which defaults to the camera position
  22761. * @returns the forward ray
  22762. */
  22763. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22764. if (length === void 0) { length = 100; }
  22765. if (!transform) {
  22766. transform = this.getWorldMatrix();
  22767. }
  22768. if (!origin) {
  22769. origin = this.position;
  22770. }
  22771. var forward = new BABYLON.Vector3(0, 0, 1);
  22772. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22773. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22774. return new BABYLON.Ray(origin, direction, length);
  22775. };
  22776. /**
  22777. * Releases resources associated with this node.
  22778. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22779. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22780. */
  22781. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22782. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22783. // Observables
  22784. this.onViewMatrixChangedObservable.clear();
  22785. this.onProjectionMatrixChangedObservable.clear();
  22786. this.onAfterCheckInputsObservable.clear();
  22787. this.onRestoreStateObservable.clear();
  22788. // Inputs
  22789. if (this.inputs) {
  22790. this.inputs.clear();
  22791. }
  22792. // Animations
  22793. this.getScene().stopAnimation(this);
  22794. // Remove from scene
  22795. this.getScene().removeCamera(this);
  22796. while (this._rigCameras.length > 0) {
  22797. var camera = this._rigCameras.pop();
  22798. if (camera) {
  22799. camera.dispose();
  22800. }
  22801. }
  22802. // Postprocesses
  22803. if (this._rigPostProcess) {
  22804. this._rigPostProcess.dispose(this);
  22805. this._rigPostProcess = null;
  22806. this._postProcesses = [];
  22807. }
  22808. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22809. this._rigPostProcess = null;
  22810. this._postProcesses = [];
  22811. }
  22812. else {
  22813. var i = this._postProcesses.length;
  22814. while (--i >= 0) {
  22815. var postProcess = this._postProcesses[i];
  22816. if (postProcess) {
  22817. postProcess.dispose(this);
  22818. }
  22819. }
  22820. }
  22821. // Render targets
  22822. var i = this.customRenderTargets.length;
  22823. while (--i >= 0) {
  22824. this.customRenderTargets[i].dispose();
  22825. }
  22826. this.customRenderTargets = [];
  22827. // Active Meshes
  22828. this._activeMeshes.dispose();
  22829. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22830. };
  22831. Object.defineProperty(Camera.prototype, "leftCamera", {
  22832. /**
  22833. * Gets the left camera of a rig setup in case of Rigged Camera
  22834. */
  22835. get: function () {
  22836. if (this._rigCameras.length < 1) {
  22837. return null;
  22838. }
  22839. return this._rigCameras[0];
  22840. },
  22841. enumerable: true,
  22842. configurable: true
  22843. });
  22844. Object.defineProperty(Camera.prototype, "rightCamera", {
  22845. /**
  22846. * Gets the right camera of a rig setup in case of Rigged Camera
  22847. */
  22848. get: function () {
  22849. if (this._rigCameras.length < 2) {
  22850. return null;
  22851. }
  22852. return this._rigCameras[1];
  22853. },
  22854. enumerable: true,
  22855. configurable: true
  22856. });
  22857. /**
  22858. * Gets the left camera target of a rig setup in case of Rigged Camera
  22859. * @returns the target position
  22860. */
  22861. Camera.prototype.getLeftTarget = function () {
  22862. if (this._rigCameras.length < 1) {
  22863. return null;
  22864. }
  22865. return this._rigCameras[0].getTarget();
  22866. };
  22867. /**
  22868. * Gets the right camera target of a rig setup in case of Rigged Camera
  22869. * @returns the target position
  22870. */
  22871. Camera.prototype.getRightTarget = function () {
  22872. if (this._rigCameras.length < 2) {
  22873. return null;
  22874. }
  22875. return this._rigCameras[1].getTarget();
  22876. };
  22877. /**
  22878. * @hidden
  22879. */
  22880. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22881. if (this.cameraRigMode === mode) {
  22882. return;
  22883. }
  22884. while (this._rigCameras.length > 0) {
  22885. var camera = this._rigCameras.pop();
  22886. if (camera) {
  22887. camera.dispose();
  22888. }
  22889. }
  22890. this.cameraRigMode = mode;
  22891. this._cameraRigParams = {};
  22892. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22893. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22894. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22895. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22896. // create the rig cameras, unless none
  22897. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22898. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22899. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22900. if (leftCamera && rightCamera) {
  22901. this._rigCameras.push(leftCamera);
  22902. this._rigCameras.push(rightCamera);
  22903. }
  22904. }
  22905. switch (this.cameraRigMode) {
  22906. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22907. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22908. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22909. break;
  22910. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22911. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22912. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22913. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22914. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22915. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22916. break;
  22917. case Camera.RIG_MODE_VR:
  22918. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22919. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22920. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22921. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22922. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22923. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22924. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22925. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22926. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22927. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22928. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22929. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22930. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22931. if (metrics.compensateDistortion) {
  22932. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22933. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22934. }
  22935. break;
  22936. case Camera.RIG_MODE_WEBVR:
  22937. if (rigParams.vrDisplay) {
  22938. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22939. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22940. //Left eye
  22941. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22942. this._rigCameras[0].setCameraRigParameter("left", true);
  22943. //leaving this for future reference
  22944. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22945. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22946. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22947. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22948. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22949. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22950. this._rigCameras[0].parent = this;
  22951. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22952. //Right eye
  22953. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22954. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22955. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22956. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22957. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22958. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22959. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22960. this._rigCameras[1].parent = this;
  22961. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22962. if (Camera.UseAlternateWebVRRendering) {
  22963. this._rigCameras[1]._skipRendering = true;
  22964. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22965. }
  22966. }
  22967. break;
  22968. }
  22969. this._cascadePostProcessesToRigCams();
  22970. this.update();
  22971. };
  22972. Camera.prototype._getVRProjectionMatrix = function () {
  22973. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22974. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22975. return this._projectionMatrix;
  22976. };
  22977. Camera.prototype._updateCameraRotationMatrix = function () {
  22978. //Here for WebVR
  22979. };
  22980. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22981. //Here for WebVR
  22982. };
  22983. /**
  22984. * This function MUST be overwritten by the different WebVR cameras available.
  22985. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22986. */
  22987. Camera.prototype._getWebVRProjectionMatrix = function () {
  22988. return BABYLON.Matrix.Identity();
  22989. };
  22990. /**
  22991. * This function MUST be overwritten by the different WebVR cameras available.
  22992. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22993. */
  22994. Camera.prototype._getWebVRViewMatrix = function () {
  22995. return BABYLON.Matrix.Identity();
  22996. };
  22997. /** @hidden */
  22998. Camera.prototype.setCameraRigParameter = function (name, value) {
  22999. if (!this._cameraRigParams) {
  23000. this._cameraRigParams = {};
  23001. }
  23002. this._cameraRigParams[name] = value;
  23003. //provisionnally:
  23004. if (name === "interaxialDistance") {
  23005. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23006. }
  23007. };
  23008. /**
  23009. * needs to be overridden by children so sub has required properties to be copied
  23010. * @hidden
  23011. */
  23012. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23013. return null;
  23014. };
  23015. /**
  23016. * May need to be overridden by children
  23017. * @hidden
  23018. */
  23019. Camera.prototype._updateRigCameras = function () {
  23020. for (var i = 0; i < this._rigCameras.length; i++) {
  23021. this._rigCameras[i].minZ = this.minZ;
  23022. this._rigCameras[i].maxZ = this.maxZ;
  23023. this._rigCameras[i].fov = this.fov;
  23024. }
  23025. // only update viewport when ANAGLYPH
  23026. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23027. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23028. }
  23029. };
  23030. /** @hidden */
  23031. Camera.prototype._setupInputs = function () {
  23032. };
  23033. /**
  23034. * Serialiaze the camera setup to a json represention
  23035. * @returns the JSON representation
  23036. */
  23037. Camera.prototype.serialize = function () {
  23038. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23039. // Type
  23040. serializationObject.type = this.getClassName();
  23041. // Parent
  23042. if (this.parent) {
  23043. serializationObject.parentId = this.parent.id;
  23044. }
  23045. if (this.inputs) {
  23046. this.inputs.serialize(serializationObject);
  23047. }
  23048. // Animations
  23049. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23050. serializationObject.ranges = this.serializeAnimationRanges();
  23051. return serializationObject;
  23052. };
  23053. /**
  23054. * Clones the current camera.
  23055. * @param name The cloned camera name
  23056. * @returns the cloned camera
  23057. */
  23058. Camera.prototype.clone = function (name) {
  23059. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23060. };
  23061. /**
  23062. * Gets the direction of the camera relative to a given local axis.
  23063. * @param localAxis Defines the reference axis to provide a relative direction.
  23064. * @return the direction
  23065. */
  23066. Camera.prototype.getDirection = function (localAxis) {
  23067. var result = BABYLON.Vector3.Zero();
  23068. this.getDirectionToRef(localAxis, result);
  23069. return result;
  23070. };
  23071. /**
  23072. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23073. * @param localAxis Defines the reference axis to provide a relative direction.
  23074. * @param result Defines the vector to store the result in
  23075. */
  23076. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23077. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23078. };
  23079. /**
  23080. * Gets a camera constructor for a given camera type
  23081. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23082. * @param name The name of the camera the result will be able to instantiate
  23083. * @param scene The scene the result will construct the camera in
  23084. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23085. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23086. * @returns a factory method to construc the camera
  23087. */
  23088. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23089. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23090. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23091. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23092. interaxial_distance: interaxial_distance,
  23093. isStereoscopicSideBySide: isStereoscopicSideBySide
  23094. });
  23095. if (constructorFunc) {
  23096. return constructorFunc;
  23097. }
  23098. // Default to universal camera
  23099. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23100. };
  23101. /**
  23102. * Compute the world matrix of the camera.
  23103. * @returns the camera workd matrix
  23104. */
  23105. Camera.prototype.computeWorldMatrix = function () {
  23106. return this.getWorldMatrix();
  23107. };
  23108. /**
  23109. * Parse a JSON and creates the camera from the parsed information
  23110. * @param parsedCamera The JSON to parse
  23111. * @param scene The scene to instantiate the camera in
  23112. * @returns the newly constructed camera
  23113. */
  23114. Camera.Parse = function (parsedCamera, scene) {
  23115. var type = parsedCamera.type;
  23116. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23117. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23118. // Parent
  23119. if (parsedCamera.parentId) {
  23120. camera._waitingParentId = parsedCamera.parentId;
  23121. }
  23122. //If camera has an input manager, let it parse inputs settings
  23123. if (camera.inputs) {
  23124. camera.inputs.parse(parsedCamera);
  23125. camera._setupInputs();
  23126. }
  23127. if (camera.setPosition) { // need to force position
  23128. camera.position.copyFromFloats(0, 0, 0);
  23129. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23130. }
  23131. // Target
  23132. if (parsedCamera.target) {
  23133. if (camera.setTarget) {
  23134. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23135. }
  23136. }
  23137. // Apply 3d rig, when found
  23138. if (parsedCamera.cameraRigMode) {
  23139. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23140. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23141. }
  23142. // Animations
  23143. if (parsedCamera.animations) {
  23144. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23145. var parsedAnimation = parsedCamera.animations[animationIndex];
  23146. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23147. }
  23148. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23149. }
  23150. if (parsedCamera.autoAnimate) {
  23151. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23152. }
  23153. return camera;
  23154. };
  23155. /**
  23156. * This is the default projection mode used by the cameras.
  23157. * It helps recreating a feeling of perspective and better appreciate depth.
  23158. * This is the best way to simulate real life cameras.
  23159. */
  23160. Camera.PERSPECTIVE_CAMERA = 0;
  23161. /**
  23162. * This helps creating camera with an orthographic mode.
  23163. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23164. */
  23165. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23166. /**
  23167. * This is the default FOV mode for perspective cameras.
  23168. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23169. */
  23170. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23171. /**
  23172. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23173. */
  23174. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23175. /**
  23176. * This specifies ther is no need for a camera rig.
  23177. * Basically only one eye is rendered corresponding to the camera.
  23178. */
  23179. Camera.RIG_MODE_NONE = 0;
  23180. /**
  23181. * Simulates a camera Rig with one blue eye and one red eye.
  23182. * This can be use with 3d blue and red glasses.
  23183. */
  23184. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23185. /**
  23186. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23187. */
  23188. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23189. /**
  23190. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23191. */
  23192. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23193. /**
  23194. * Defines that both eyes of the camera will be rendered over under each other.
  23195. */
  23196. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23197. /**
  23198. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23199. */
  23200. Camera.RIG_MODE_VR = 20;
  23201. /**
  23202. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23203. */
  23204. Camera.RIG_MODE_WEBVR = 21;
  23205. /**
  23206. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23207. */
  23208. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23209. /**
  23210. * @hidden
  23211. * Might be removed once multiview will be a thing
  23212. */
  23213. Camera.UseAlternateWebVRRendering = false;
  23214. __decorate([
  23215. BABYLON.serializeAsVector3()
  23216. ], Camera.prototype, "position", void 0);
  23217. __decorate([
  23218. BABYLON.serializeAsVector3()
  23219. ], Camera.prototype, "upVector", void 0);
  23220. __decorate([
  23221. BABYLON.serialize()
  23222. ], Camera.prototype, "orthoLeft", void 0);
  23223. __decorate([
  23224. BABYLON.serialize()
  23225. ], Camera.prototype, "orthoRight", void 0);
  23226. __decorate([
  23227. BABYLON.serialize()
  23228. ], Camera.prototype, "orthoBottom", void 0);
  23229. __decorate([
  23230. BABYLON.serialize()
  23231. ], Camera.prototype, "orthoTop", void 0);
  23232. __decorate([
  23233. BABYLON.serialize()
  23234. ], Camera.prototype, "fov", void 0);
  23235. __decorate([
  23236. BABYLON.serialize()
  23237. ], Camera.prototype, "minZ", void 0);
  23238. __decorate([
  23239. BABYLON.serialize()
  23240. ], Camera.prototype, "maxZ", void 0);
  23241. __decorate([
  23242. BABYLON.serialize()
  23243. ], Camera.prototype, "inertia", void 0);
  23244. __decorate([
  23245. BABYLON.serialize()
  23246. ], Camera.prototype, "mode", void 0);
  23247. __decorate([
  23248. BABYLON.serialize()
  23249. ], Camera.prototype, "layerMask", void 0);
  23250. __decorate([
  23251. BABYLON.serialize()
  23252. ], Camera.prototype, "fovMode", void 0);
  23253. __decorate([
  23254. BABYLON.serialize()
  23255. ], Camera.prototype, "cameraRigMode", void 0);
  23256. __decorate([
  23257. BABYLON.serialize()
  23258. ], Camera.prototype, "interaxialDistance", void 0);
  23259. __decorate([
  23260. BABYLON.serialize()
  23261. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23262. return Camera;
  23263. }(BABYLON.Node));
  23264. BABYLON.Camera = Camera;
  23265. })(BABYLON || (BABYLON = {}));
  23266. //# sourceMappingURL=babylon.camera.js.map
  23267. var BABYLON;
  23268. (function (BABYLON) {
  23269. var RenderingManager = /** @class */ (function () {
  23270. function RenderingManager(scene) {
  23271. /**
  23272. * @hidden
  23273. */
  23274. this._useSceneAutoClearSetup = false;
  23275. this._renderingGroups = new Array();
  23276. this._autoClearDepthStencil = {};
  23277. this._customOpaqueSortCompareFn = {};
  23278. this._customAlphaTestSortCompareFn = {};
  23279. this._customTransparentSortCompareFn = {};
  23280. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23281. this._scene = scene;
  23282. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23283. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23284. }
  23285. }
  23286. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23287. if (depth === void 0) { depth = true; }
  23288. if (stencil === void 0) { stencil = true; }
  23289. if (this._depthStencilBufferAlreadyCleaned) {
  23290. return;
  23291. }
  23292. this._scene.getEngine().clear(null, false, depth, stencil);
  23293. this._depthStencilBufferAlreadyCleaned = true;
  23294. };
  23295. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23296. // Update the observable context (not null as it only goes away on dispose)
  23297. var info = this._renderingGroupInfo;
  23298. info.scene = this._scene;
  23299. info.camera = this._scene.activeCamera;
  23300. // Dispatch sprites
  23301. if (this._scene.spriteManagers && renderSprites) {
  23302. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23303. var manager = this._scene.spriteManagers[index];
  23304. this.dispatchSprites(manager);
  23305. }
  23306. }
  23307. // Render
  23308. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23309. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23310. var renderingGroup = this._renderingGroups[index];
  23311. if (!renderingGroup)
  23312. continue;
  23313. var renderingGroupMask = Math.pow(2, index);
  23314. info.renderingGroupId = index;
  23315. // Before Observable
  23316. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23317. // Clear depth/stencil if needed
  23318. if (RenderingManager.AUTOCLEAR) {
  23319. var autoClear = this._useSceneAutoClearSetup ?
  23320. this._scene.getAutoClearDepthStencilSetup(index) :
  23321. this._autoClearDepthStencil[index];
  23322. if (autoClear && autoClear.autoClear) {
  23323. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23324. }
  23325. }
  23326. // Render
  23327. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23328. var step = _a[_i];
  23329. step.action(index);
  23330. }
  23331. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23332. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23333. var step = _c[_b];
  23334. step.action(index);
  23335. }
  23336. // After Observable
  23337. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23338. }
  23339. };
  23340. RenderingManager.prototype.reset = function () {
  23341. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23342. var renderingGroup = this._renderingGroups[index];
  23343. if (renderingGroup) {
  23344. renderingGroup.prepare();
  23345. }
  23346. }
  23347. };
  23348. RenderingManager.prototype.dispose = function () {
  23349. this.freeRenderingGroups();
  23350. this._renderingGroups.length = 0;
  23351. this._renderingGroupInfo = null;
  23352. };
  23353. /**
  23354. * Clear the info related to rendering groups preventing retention points during dispose.
  23355. */
  23356. RenderingManager.prototype.freeRenderingGroups = function () {
  23357. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23358. var renderingGroup = this._renderingGroups[index];
  23359. if (renderingGroup) {
  23360. renderingGroup.dispose();
  23361. }
  23362. }
  23363. };
  23364. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23365. if (this._renderingGroups[renderingGroupId] === undefined) {
  23366. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23367. }
  23368. };
  23369. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23370. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23371. this._prepareRenderingGroup(renderingGroupId);
  23372. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23373. };
  23374. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23375. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23376. this._prepareRenderingGroup(renderingGroupId);
  23377. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23378. };
  23379. /**
  23380. * @param subMesh The submesh to dispatch
  23381. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23382. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23383. */
  23384. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23385. if (mesh === undefined) {
  23386. mesh = subMesh.getMesh();
  23387. }
  23388. var renderingGroupId = mesh.renderingGroupId || 0;
  23389. this._prepareRenderingGroup(renderingGroupId);
  23390. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23391. };
  23392. /**
  23393. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23394. * This allowed control for front to back rendering or reversly depending of the special needs.
  23395. *
  23396. * @param renderingGroupId The rendering group id corresponding to its index
  23397. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23398. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23399. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23400. */
  23401. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23402. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23403. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23404. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23405. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23406. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23407. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23408. if (this._renderingGroups[renderingGroupId]) {
  23409. var group = this._renderingGroups[renderingGroupId];
  23410. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23411. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23412. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23413. }
  23414. };
  23415. /**
  23416. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23417. *
  23418. * @param renderingGroupId The rendering group id corresponding to its index
  23419. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23420. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23421. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23422. */
  23423. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23424. if (depth === void 0) { depth = true; }
  23425. if (stencil === void 0) { stencil = true; }
  23426. this._autoClearDepthStencil[renderingGroupId] = {
  23427. autoClear: autoClearDepthStencil,
  23428. depth: depth,
  23429. stencil: stencil
  23430. };
  23431. };
  23432. /**
  23433. * Gets the current auto clear configuration for one rendering group of the rendering
  23434. * manager.
  23435. * @param index the rendering group index to get the information for
  23436. * @returns The auto clear setup for the requested rendering group
  23437. */
  23438. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23439. return this._autoClearDepthStencil[index];
  23440. };
  23441. /**
  23442. * The max id used for rendering groups (not included)
  23443. */
  23444. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23445. /**
  23446. * The min id used for rendering groups (included)
  23447. */
  23448. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23449. /**
  23450. * Used to globally prevent autoclearing scenes.
  23451. */
  23452. RenderingManager.AUTOCLEAR = true;
  23453. return RenderingManager;
  23454. }());
  23455. BABYLON.RenderingManager = RenderingManager;
  23456. })(BABYLON || (BABYLON = {}));
  23457. //# sourceMappingURL=babylon.renderingManager.js.map
  23458. var BABYLON;
  23459. (function (BABYLON) {
  23460. var RenderingGroup = /** @class */ (function () {
  23461. /**
  23462. * Creates a new rendering group.
  23463. * @param index The rendering group index
  23464. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23465. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23466. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23467. */
  23468. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23469. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23470. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23471. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23472. this.index = index;
  23473. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23474. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23475. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23476. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23477. this._particleSystems = new BABYLON.SmartArray(256);
  23478. this._spriteManagers = new BABYLON.SmartArray(256);
  23479. this._edgesRenderers = new BABYLON.SmartArray(16);
  23480. this._scene = scene;
  23481. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23482. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23483. this.transparentSortCompareFn = transparentSortCompareFn;
  23484. }
  23485. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23486. /**
  23487. * Set the opaque sort comparison function.
  23488. * If null the sub meshes will be render in the order they were created
  23489. */
  23490. set: function (value) {
  23491. this._opaqueSortCompareFn = value;
  23492. if (value) {
  23493. this._renderOpaque = this.renderOpaqueSorted;
  23494. }
  23495. else {
  23496. this._renderOpaque = RenderingGroup.renderUnsorted;
  23497. }
  23498. },
  23499. enumerable: true,
  23500. configurable: true
  23501. });
  23502. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23503. /**
  23504. * Set the alpha test sort comparison function.
  23505. * If null the sub meshes will be render in the order they were created
  23506. */
  23507. set: function (value) {
  23508. this._alphaTestSortCompareFn = value;
  23509. if (value) {
  23510. this._renderAlphaTest = this.renderAlphaTestSorted;
  23511. }
  23512. else {
  23513. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23514. }
  23515. },
  23516. enumerable: true,
  23517. configurable: true
  23518. });
  23519. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23520. /**
  23521. * Set the transparent sort comparison function.
  23522. * If null the sub meshes will be render in the order they were created
  23523. */
  23524. set: function (value) {
  23525. if (value) {
  23526. this._transparentSortCompareFn = value;
  23527. }
  23528. else {
  23529. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23530. }
  23531. this._renderTransparent = this.renderTransparentSorted;
  23532. },
  23533. enumerable: true,
  23534. configurable: true
  23535. });
  23536. /**
  23537. * Render all the sub meshes contained in the group.
  23538. * @param customRenderFunction Used to override the default render behaviour of the group.
  23539. * @returns true if rendered some submeshes.
  23540. */
  23541. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23542. if (customRenderFunction) {
  23543. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23544. return;
  23545. }
  23546. var engine = this._scene.getEngine();
  23547. // Depth only
  23548. if (this._depthOnlySubMeshes.length !== 0) {
  23549. engine.setColorWrite(false);
  23550. this._renderAlphaTest(this._depthOnlySubMeshes);
  23551. engine.setColorWrite(true);
  23552. }
  23553. // Opaque
  23554. if (this._opaqueSubMeshes.length !== 0) {
  23555. this._renderOpaque(this._opaqueSubMeshes);
  23556. }
  23557. // Alpha test
  23558. if (this._alphaTestSubMeshes.length !== 0) {
  23559. this._renderAlphaTest(this._alphaTestSubMeshes);
  23560. }
  23561. var stencilState = engine.getStencilBuffer();
  23562. engine.setStencilBuffer(false);
  23563. // Sprites
  23564. if (renderSprites) {
  23565. this._renderSprites();
  23566. }
  23567. // Particles
  23568. if (renderParticles) {
  23569. this._renderParticles(activeMeshes);
  23570. }
  23571. if (this.onBeforeTransparentRendering) {
  23572. this.onBeforeTransparentRendering();
  23573. }
  23574. // Transparent
  23575. if (this._transparentSubMeshes.length !== 0) {
  23576. this._renderTransparent(this._transparentSubMeshes);
  23577. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23578. }
  23579. // Set back stencil to false in case it changes before the edge renderer.
  23580. engine.setStencilBuffer(false);
  23581. // Edges
  23582. if (this._edgesRenderers.length) {
  23583. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23584. this._edgesRenderers.data[edgesRendererIndex].render();
  23585. }
  23586. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23587. }
  23588. // Restore Stencil state.
  23589. engine.setStencilBuffer(stencilState);
  23590. };
  23591. /**
  23592. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23593. * @param subMeshes The submeshes to render
  23594. */
  23595. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23596. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23597. };
  23598. /**
  23599. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23600. * @param subMeshes The submeshes to render
  23601. */
  23602. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23603. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23604. };
  23605. /**
  23606. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23607. * @param subMeshes The submeshes to render
  23608. */
  23609. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23610. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23611. };
  23612. /**
  23613. * Renders the submeshes in a specified order.
  23614. * @param subMeshes The submeshes to sort before render
  23615. * @param sortCompareFn The comparison function use to sort
  23616. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23617. * @param transparent Specifies to activate blending if true
  23618. */
  23619. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23620. var subIndex = 0;
  23621. var subMesh;
  23622. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23623. for (; subIndex < subMeshes.length; subIndex++) {
  23624. subMesh = subMeshes.data[subIndex];
  23625. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23626. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23627. }
  23628. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23629. if (sortCompareFn) {
  23630. sortedArray.sort(sortCompareFn);
  23631. }
  23632. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23633. subMesh = sortedArray[subIndex];
  23634. if (transparent) {
  23635. var material = subMesh.getMaterial();
  23636. if (material && material.needDepthPrePass) {
  23637. var engine = material.getScene().getEngine();
  23638. engine.setColorWrite(false);
  23639. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23640. subMesh.render(false);
  23641. engine.setColorWrite(true);
  23642. }
  23643. }
  23644. subMesh.render(transparent);
  23645. }
  23646. };
  23647. /**
  23648. * Renders the submeshes in the order they were dispatched (no sort applied).
  23649. * @param subMeshes The submeshes to render
  23650. */
  23651. RenderingGroup.renderUnsorted = function (subMeshes) {
  23652. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23653. var submesh = subMeshes.data[subIndex];
  23654. submesh.render(false);
  23655. }
  23656. };
  23657. /**
  23658. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23659. * are rendered back to front if in the same alpha index.
  23660. *
  23661. * @param a The first submesh
  23662. * @param b The second submesh
  23663. * @returns The result of the comparison
  23664. */
  23665. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23666. // Alpha index first
  23667. if (a._alphaIndex > b._alphaIndex) {
  23668. return 1;
  23669. }
  23670. if (a._alphaIndex < b._alphaIndex) {
  23671. return -1;
  23672. }
  23673. // Then distance to camera
  23674. return RenderingGroup.backToFrontSortCompare(a, b);
  23675. };
  23676. /**
  23677. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23678. * are rendered back to front.
  23679. *
  23680. * @param a The first submesh
  23681. * @param b The second submesh
  23682. * @returns The result of the comparison
  23683. */
  23684. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23685. // Then distance to camera
  23686. if (a._distanceToCamera < b._distanceToCamera) {
  23687. return 1;
  23688. }
  23689. if (a._distanceToCamera > b._distanceToCamera) {
  23690. return -1;
  23691. }
  23692. return 0;
  23693. };
  23694. /**
  23695. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23696. * are rendered front to back (prevent overdraw).
  23697. *
  23698. * @param a The first submesh
  23699. * @param b The second submesh
  23700. * @returns The result of the comparison
  23701. */
  23702. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23703. // Then distance to camera
  23704. if (a._distanceToCamera < b._distanceToCamera) {
  23705. return -1;
  23706. }
  23707. if (a._distanceToCamera > b._distanceToCamera) {
  23708. return 1;
  23709. }
  23710. return 0;
  23711. };
  23712. /**
  23713. * Resets the different lists of submeshes to prepare a new frame.
  23714. */
  23715. RenderingGroup.prototype.prepare = function () {
  23716. this._opaqueSubMeshes.reset();
  23717. this._transparentSubMeshes.reset();
  23718. this._alphaTestSubMeshes.reset();
  23719. this._depthOnlySubMeshes.reset();
  23720. this._particleSystems.reset();
  23721. this._spriteManagers.reset();
  23722. this._edgesRenderers.reset();
  23723. };
  23724. RenderingGroup.prototype.dispose = function () {
  23725. this._opaqueSubMeshes.dispose();
  23726. this._transparentSubMeshes.dispose();
  23727. this._alphaTestSubMeshes.dispose();
  23728. this._depthOnlySubMeshes.dispose();
  23729. this._particleSystems.dispose();
  23730. this._spriteManagers.dispose();
  23731. this._edgesRenderers.dispose();
  23732. };
  23733. /**
  23734. * Inserts the submesh in its correct queue depending on its material.
  23735. * @param subMesh The submesh to dispatch
  23736. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23737. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23738. */
  23739. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23740. // Get mesh and materials if not provided
  23741. if (mesh === undefined) {
  23742. mesh = subMesh.getMesh();
  23743. }
  23744. if (material === undefined) {
  23745. material = subMesh.getMaterial();
  23746. }
  23747. if (material === null || material === undefined) {
  23748. return;
  23749. }
  23750. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23751. this._transparentSubMeshes.push(subMesh);
  23752. }
  23753. else if (material.needAlphaTesting()) { // Alpha test
  23754. if (material.needDepthPrePass) {
  23755. this._depthOnlySubMeshes.push(subMesh);
  23756. }
  23757. this._alphaTestSubMeshes.push(subMesh);
  23758. }
  23759. else {
  23760. if (material.needDepthPrePass) {
  23761. this._depthOnlySubMeshes.push(subMesh);
  23762. }
  23763. this._opaqueSubMeshes.push(subMesh); // Opaque
  23764. }
  23765. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23766. this._edgesRenderers.push(mesh._edgesRenderer);
  23767. }
  23768. };
  23769. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23770. this._spriteManagers.push(spriteManager);
  23771. };
  23772. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23773. this._particleSystems.push(particleSystem);
  23774. };
  23775. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23776. if (this._particleSystems.length === 0) {
  23777. return;
  23778. }
  23779. // Particles
  23780. var activeCamera = this._scene.activeCamera;
  23781. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23782. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23783. var particleSystem = this._particleSystems.data[particleIndex];
  23784. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23785. continue;
  23786. }
  23787. var emitter = particleSystem.emitter;
  23788. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23789. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23790. }
  23791. }
  23792. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23793. };
  23794. RenderingGroup.prototype._renderSprites = function () {
  23795. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23796. return;
  23797. }
  23798. // Sprites
  23799. var activeCamera = this._scene.activeCamera;
  23800. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23801. for (var id = 0; id < this._spriteManagers.length; id++) {
  23802. var spriteManager = this._spriteManagers.data[id];
  23803. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23804. spriteManager.render();
  23805. }
  23806. }
  23807. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23808. };
  23809. return RenderingGroup;
  23810. }());
  23811. BABYLON.RenderingGroup = RenderingGroup;
  23812. })(BABYLON || (BABYLON = {}));
  23813. //# sourceMappingURL=babylon.renderingGroup.js.map
  23814. var BABYLON;
  23815. (function (BABYLON) {
  23816. /**
  23817. * Groups all the scene component constants in one place to ease maintenance.
  23818. * @hidden
  23819. */
  23820. var SceneComponentConstants = /** @class */ (function () {
  23821. function SceneComponentConstants() {
  23822. }
  23823. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23824. SceneComponentConstants.NAME_LAYER = "Layer";
  23825. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23826. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23827. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23828. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23829. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23830. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23831. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23832. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23833. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23834. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23835. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23836. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23837. SceneComponentConstants.NAME_OCTREE = "Octree";
  23838. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23839. SceneComponentConstants.NAME_AUDIO = "Audio";
  23840. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23841. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23842. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23843. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23844. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23845. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23846. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23847. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23848. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23849. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23850. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23851. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23852. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23853. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23854. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23855. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23856. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23857. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23858. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23859. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23860. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23861. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23862. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23863. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23864. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23865. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23866. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23867. return SceneComponentConstants;
  23868. }());
  23869. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23870. /**
  23871. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23872. * @hidden
  23873. */
  23874. var Stage = /** @class */ (function (_super) {
  23875. __extends(Stage, _super);
  23876. /**
  23877. * Hide ctor from the rest of the world.
  23878. * @param items The items to add.
  23879. */
  23880. function Stage(items) {
  23881. return _super.apply(this, items) || this;
  23882. }
  23883. /**
  23884. * Creates a new Stage.
  23885. * @returns A new instance of a Stage
  23886. */
  23887. Stage.Create = function () {
  23888. return Object.create(Stage.prototype);
  23889. };
  23890. /**
  23891. * Registers a step in an ordered way in the targeted stage.
  23892. * @param index Defines the position to register the step in
  23893. * @param component Defines the component attached to the step
  23894. * @param action Defines the action to launch during the step
  23895. */
  23896. Stage.prototype.registerStep = function (index, component, action) {
  23897. var i = 0;
  23898. var maxIndex = Number.MAX_VALUE;
  23899. for (; i < this.length && i < maxIndex; i++) {
  23900. var step = this[i];
  23901. maxIndex = step.index;
  23902. }
  23903. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23904. };
  23905. /**
  23906. * Clears all the steps from the stage.
  23907. */
  23908. Stage.prototype.clear = function () {
  23909. this.length = 0;
  23910. };
  23911. return Stage;
  23912. }(Array));
  23913. BABYLON.Stage = Stage;
  23914. })(BABYLON || (BABYLON = {}));
  23915. //# sourceMappingURL=babylon.sceneComponent.js.map
  23916. var BABYLON;
  23917. (function (BABYLON) {
  23918. /**
  23919. * Base class of the scene acting as a container for the different elements composing a scene.
  23920. * This class is dynamically extended by the different components of the scene increasing
  23921. * flexibility and reducing coupling
  23922. */
  23923. var AbstractScene = /** @class */ (function () {
  23924. function AbstractScene() {
  23925. /**
  23926. * Gets the list of root nodes (ie. nodes with no parent)
  23927. */
  23928. this.rootNodes = new Array();
  23929. /** All of the cameras added to this scene
  23930. * @see http://doc.babylonjs.com/babylon101/cameras
  23931. */
  23932. this.cameras = new Array();
  23933. /**
  23934. * All of the lights added to this scene
  23935. * @see http://doc.babylonjs.com/babylon101/lights
  23936. */
  23937. this.lights = new Array();
  23938. /**
  23939. * All of the (abstract) meshes added to this scene
  23940. */
  23941. this.meshes = new Array();
  23942. /**
  23943. * The list of skeletons added to the scene
  23944. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23945. */
  23946. this.skeletons = new Array();
  23947. /**
  23948. * All of the particle systems added to this scene
  23949. * @see http://doc.babylonjs.com/babylon101/particles
  23950. */
  23951. this.particleSystems = new Array();
  23952. /**
  23953. * Gets a list of Animations associated with the scene
  23954. */
  23955. this.animations = [];
  23956. /**
  23957. * All of the animation groups added to this scene
  23958. * @see http://doc.babylonjs.com/how_to/group
  23959. */
  23960. this.animationGroups = new Array();
  23961. /**
  23962. * All of the multi-materials added to this scene
  23963. * @see http://doc.babylonjs.com/how_to/multi_materials
  23964. */
  23965. this.multiMaterials = new Array();
  23966. /**
  23967. * All of the materials added to this scene
  23968. * @see http://doc.babylonjs.com/babylon101/materials
  23969. */
  23970. this.materials = new Array();
  23971. /**
  23972. * The list of morph target managers added to the scene
  23973. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23974. */
  23975. this.morphTargetManagers = new Array();
  23976. /**
  23977. * The list of geometries used in the scene.
  23978. */
  23979. this.geometries = new Array();
  23980. /**
  23981. * All of the tranform nodes added to this scene
  23982. * @see http://doc.babylonjs.com/how_to/transformnode
  23983. */
  23984. this.transformNodes = new Array();
  23985. /**
  23986. * ActionManagers available on the scene.
  23987. */
  23988. this.actionManagers = new Array();
  23989. /**
  23990. * Textures to keep.
  23991. */
  23992. this.textures = new Array();
  23993. }
  23994. /**
  23995. * Adds a parser in the list of available ones
  23996. * @param name Defines the name of the parser
  23997. * @param parser Defines the parser to add
  23998. */
  23999. AbstractScene.AddParser = function (name, parser) {
  24000. this._BabylonFileParsers[name] = parser;
  24001. };
  24002. /**
  24003. * Gets a general parser from the list of avaialble ones
  24004. * @param name Defines the name of the parser
  24005. * @returns the requested parser or null
  24006. */
  24007. AbstractScene.GetParser = function (name) {
  24008. if (this._BabylonFileParsers[name]) {
  24009. return this._BabylonFileParsers[name];
  24010. }
  24011. return null;
  24012. };
  24013. /**
  24014. * Adds n individual parser in the list of available ones
  24015. * @param name Defines the name of the parser
  24016. * @param parser Defines the parser to add
  24017. */
  24018. AbstractScene.AddIndividualParser = function (name, parser) {
  24019. this._IndividualBabylonFileParsers[name] = parser;
  24020. };
  24021. /**
  24022. * Gets an individual parser from the list of avaialble ones
  24023. * @param name Defines the name of the parser
  24024. * @returns the requested parser or null
  24025. */
  24026. AbstractScene.GetIndividualParser = function (name) {
  24027. if (this._IndividualBabylonFileParsers[name]) {
  24028. return this._IndividualBabylonFileParsers[name];
  24029. }
  24030. return null;
  24031. };
  24032. /**
  24033. * Parser json data and populate both a scene and its associated container object
  24034. * @param jsonData Defines the data to parse
  24035. * @param scene Defines the scene to parse the data for
  24036. * @param container Defines the container attached to the parsing sequence
  24037. * @param rootUrl Defines the root url of the data
  24038. */
  24039. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24040. for (var parserName in this._BabylonFileParsers) {
  24041. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24042. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24043. }
  24044. }
  24045. };
  24046. /**
  24047. * Stores the list of available parsers in the application.
  24048. */
  24049. AbstractScene._BabylonFileParsers = {};
  24050. /**
  24051. * Stores the list of available individual parsers in the application.
  24052. */
  24053. AbstractScene._IndividualBabylonFileParsers = {};
  24054. return AbstractScene;
  24055. }());
  24056. BABYLON.AbstractScene = AbstractScene;
  24057. })(BABYLON || (BABYLON = {}));
  24058. //# sourceMappingURL=babylon.abstractScene.js.map
  24059. var BABYLON;
  24060. (function (BABYLON) {
  24061. /** @hidden */
  24062. var ClickInfo = /** @class */ (function () {
  24063. function ClickInfo() {
  24064. this._singleClick = false;
  24065. this._doubleClick = false;
  24066. this._hasSwiped = false;
  24067. this._ignore = false;
  24068. }
  24069. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24070. get: function () {
  24071. return this._singleClick;
  24072. },
  24073. set: function (b) {
  24074. this._singleClick = b;
  24075. },
  24076. enumerable: true,
  24077. configurable: true
  24078. });
  24079. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24080. get: function () {
  24081. return this._doubleClick;
  24082. },
  24083. set: function (b) {
  24084. this._doubleClick = b;
  24085. },
  24086. enumerable: true,
  24087. configurable: true
  24088. });
  24089. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24090. get: function () {
  24091. return this._hasSwiped;
  24092. },
  24093. set: function (b) {
  24094. this._hasSwiped = b;
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24100. get: function () {
  24101. return this._ignore;
  24102. },
  24103. set: function (b) {
  24104. this._ignore = b;
  24105. },
  24106. enumerable: true,
  24107. configurable: true
  24108. });
  24109. return ClickInfo;
  24110. }());
  24111. /**
  24112. * This class is used by the onRenderingGroupObservable
  24113. */
  24114. var RenderingGroupInfo = /** @class */ (function () {
  24115. function RenderingGroupInfo() {
  24116. }
  24117. return RenderingGroupInfo;
  24118. }());
  24119. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24120. /**
  24121. * Represents a scene to be rendered by the engine.
  24122. * @see http://doc.babylonjs.com/features/scene
  24123. */
  24124. var Scene = /** @class */ (function (_super) {
  24125. __extends(Scene, _super);
  24126. /**
  24127. * Creates a new Scene
  24128. * @param engine defines the engine to use to render this scene
  24129. */
  24130. function Scene(engine) {
  24131. var _this = _super.call(this) || this;
  24132. // Members
  24133. /**
  24134. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24135. */
  24136. _this.autoClear = true;
  24137. /**
  24138. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24139. */
  24140. _this.autoClearDepthAndStencil = true;
  24141. /**
  24142. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24143. */
  24144. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24145. /**
  24146. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24147. */
  24148. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24149. _this._forceWireframe = false;
  24150. _this._forcePointsCloud = false;
  24151. /**
  24152. * Gets or sets a boolean indicating if animations are enabled
  24153. */
  24154. _this.animationsEnabled = true;
  24155. _this._animationPropertiesOverride = null;
  24156. /**
  24157. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24158. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24159. */
  24160. _this.useConstantAnimationDeltaTime = false;
  24161. /**
  24162. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24163. * Please note that it requires to run a ray cast through the scene on every frame
  24164. */
  24165. _this.constantlyUpdateMeshUnderPointer = false;
  24166. /**
  24167. * Defines the HTML cursor to use when hovering over interactive elements
  24168. */
  24169. _this.hoverCursor = "pointer";
  24170. /**
  24171. * Defines the HTML default cursor to use (empty by default)
  24172. */
  24173. _this.defaultCursor = "";
  24174. /**
  24175. * This is used to call preventDefault() on pointer down
  24176. * in order to block unwanted artifacts like system double clicks
  24177. */
  24178. _this.preventDefaultOnPointerDown = true;
  24179. // Metadata
  24180. /**
  24181. * Gets or sets user defined metadata
  24182. */
  24183. _this.metadata = null;
  24184. /**
  24185. * Use this array to add regular expressions used to disable offline support for specific urls
  24186. */
  24187. _this.disableOfflineSupportExceptionRules = new Array();
  24188. /**
  24189. * An event triggered when the scene is disposed.
  24190. */
  24191. _this.onDisposeObservable = new BABYLON.Observable();
  24192. _this._onDisposeObserver = null;
  24193. /**
  24194. * An event triggered before rendering the scene (right after animations and physics)
  24195. */
  24196. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24197. _this._onBeforeRenderObserver = null;
  24198. /**
  24199. * An event triggered after rendering the scene
  24200. */
  24201. _this.onAfterRenderObservable = new BABYLON.Observable();
  24202. _this._onAfterRenderObserver = null;
  24203. /**
  24204. * An event triggered before animating the scene
  24205. */
  24206. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24207. /**
  24208. * An event triggered after animations processing
  24209. */
  24210. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24211. /**
  24212. * An event triggered before draw calls are ready to be sent
  24213. */
  24214. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24215. /**
  24216. * An event triggered after draw calls have been sent
  24217. */
  24218. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24219. /**
  24220. * An event triggered when the scene is ready
  24221. */
  24222. _this.onReadyObservable = new BABYLON.Observable();
  24223. /**
  24224. * An event triggered before rendering a camera
  24225. */
  24226. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24227. _this._onBeforeCameraRenderObserver = null;
  24228. /**
  24229. * An event triggered after rendering a camera
  24230. */
  24231. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24232. _this._onAfterCameraRenderObserver = null;
  24233. /**
  24234. * An event triggered when active meshes evaluation is about to start
  24235. */
  24236. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24237. /**
  24238. * An event triggered when active meshes evaluation is done
  24239. */
  24240. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24241. /**
  24242. * An event triggered when particles rendering is about to start
  24243. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24244. */
  24245. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24246. /**
  24247. * An event triggered when particles rendering is done
  24248. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24249. */
  24250. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24251. /**
  24252. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24253. */
  24254. _this.onDataLoadedObservable = new BABYLON.Observable();
  24255. /**
  24256. * An event triggered when a camera is created
  24257. */
  24258. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24259. /**
  24260. * An event triggered when a camera is removed
  24261. */
  24262. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24263. /**
  24264. * An event triggered when a light is created
  24265. */
  24266. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24267. /**
  24268. * An event triggered when a light is removed
  24269. */
  24270. _this.onLightRemovedObservable = new BABYLON.Observable();
  24271. /**
  24272. * An event triggered when a geometry is created
  24273. */
  24274. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24275. /**
  24276. * An event triggered when a geometry is removed
  24277. */
  24278. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24279. /**
  24280. * An event triggered when a transform node is created
  24281. */
  24282. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24283. /**
  24284. * An event triggered when a transform node is removed
  24285. */
  24286. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24287. /**
  24288. * An event triggered when a mesh is created
  24289. */
  24290. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24291. /**
  24292. * An event triggered when a mesh is removed
  24293. */
  24294. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24295. /**
  24296. * An event triggered when render targets are about to be rendered
  24297. * Can happen multiple times per frame.
  24298. */
  24299. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24300. /**
  24301. * An event triggered when render targets were rendered.
  24302. * Can happen multiple times per frame.
  24303. */
  24304. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24305. /**
  24306. * An event triggered before calculating deterministic simulation step
  24307. */
  24308. _this.onBeforeStepObservable = new BABYLON.Observable();
  24309. /**
  24310. * An event triggered after calculating deterministic simulation step
  24311. */
  24312. _this.onAfterStepObservable = new BABYLON.Observable();
  24313. /**
  24314. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24315. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24316. * 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)
  24317. */
  24318. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24319. /**
  24320. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24321. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24322. * 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)
  24323. */
  24324. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24325. /**
  24326. * This Observable will when a mesh has been imported into the scene.
  24327. */
  24328. _this.onMeshImportedObservable = new BABYLON.Observable();
  24329. // Animations
  24330. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24331. /**
  24332. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  24333. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24334. */
  24335. _this.onPrePointerObservable = new BABYLON.Observable();
  24336. /**
  24337. * Observable event triggered each time an input event is received from the rendering canvas
  24338. */
  24339. _this.onPointerObservable = new BABYLON.Observable();
  24340. _this._meshPickProceed = false;
  24341. _this._currentPickResult = null;
  24342. _this._previousPickResult = null;
  24343. _this._totalPointersPressed = 0;
  24344. _this._doubleClickOccured = false;
  24345. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24346. _this.cameraToUseForPointers = null;
  24347. _this._pointerX = 0;
  24348. _this._pointerY = 0;
  24349. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24350. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24351. _this._startingPointerTime = 0;
  24352. _this._previousStartingPointerTime = 0;
  24353. _this._pointerCaptures = {};
  24354. // Deterministic lockstep
  24355. _this._timeAccumulator = 0;
  24356. _this._currentStepId = 0;
  24357. _this._currentInternalStep = 0;
  24358. // Keyboard
  24359. /**
  24360. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24361. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24362. */
  24363. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24364. /**
  24365. * Observable event triggered each time an keyboard event is received from the hosting window
  24366. */
  24367. _this.onKeyboardObservable = new BABYLON.Observable();
  24368. // Coordinates system
  24369. _this._useRightHandedSystem = false;
  24370. // Fog
  24371. _this._fogEnabled = true;
  24372. _this._fogMode = Scene.FOGMODE_NONE;
  24373. /**
  24374. * Gets or sets the fog color to use
  24375. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24376. */
  24377. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24378. /**
  24379. * Gets or sets the fog density to use
  24380. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24381. */
  24382. _this.fogDensity = 0.1;
  24383. /**
  24384. * Gets or sets the fog start distance to use
  24385. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24386. */
  24387. _this.fogStart = 0;
  24388. /**
  24389. * Gets or sets the fog end distance to use
  24390. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24391. */
  24392. _this.fogEnd = 1000.0;
  24393. // Lights
  24394. _this._shadowsEnabled = true;
  24395. _this._lightsEnabled = true;
  24396. /** All of the active cameras added to this scene. */
  24397. _this.activeCameras = new Array();
  24398. // Textures
  24399. _this._texturesEnabled = true;
  24400. // Particles
  24401. /**
  24402. * Gets or sets a boolean indicating if particles are enabled on this scene
  24403. */
  24404. _this.particlesEnabled = true;
  24405. // Sprites
  24406. /**
  24407. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24408. */
  24409. _this.spritesEnabled = true;
  24410. // Skeletons
  24411. _this._skeletonsEnabled = true;
  24412. // Lens flares
  24413. /**
  24414. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24415. */
  24416. _this.lensFlaresEnabled = true;
  24417. // Collisions
  24418. /**
  24419. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24420. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24421. */
  24422. _this.collisionsEnabled = true;
  24423. /**
  24424. * Defines the gravity applied to this scene (used only for collisions)
  24425. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24426. */
  24427. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24428. // Postprocesses
  24429. /**
  24430. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24431. */
  24432. _this.postProcessesEnabled = true;
  24433. /**
  24434. * The list of postprocesses added to the scene
  24435. */
  24436. _this.postProcesses = new Array();
  24437. // Customs render targets
  24438. /**
  24439. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24440. */
  24441. _this.renderTargetsEnabled = true;
  24442. /**
  24443. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24444. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24445. */
  24446. _this.dumpNextRenderTargets = false;
  24447. /**
  24448. * The list of user defined render targets added to the scene
  24449. */
  24450. _this.customRenderTargets = new Array();
  24451. /**
  24452. * Gets the list of meshes imported to the scene through SceneLoader
  24453. */
  24454. _this.importedMeshesFiles = new Array();
  24455. // Probes
  24456. /**
  24457. * Gets or sets a boolean indicating if probes are enabled on this scene
  24458. */
  24459. _this.probesEnabled = true;
  24460. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24461. // Procedural textures
  24462. /**
  24463. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24464. */
  24465. _this.proceduralTexturesEnabled = true;
  24466. // Performance counters
  24467. _this._totalVertices = new BABYLON.PerfCounter();
  24468. /** @hidden */
  24469. _this._activeIndices = new BABYLON.PerfCounter();
  24470. /** @hidden */
  24471. _this._activeParticles = new BABYLON.PerfCounter();
  24472. /** @hidden */
  24473. _this._activeBones = new BABYLON.PerfCounter();
  24474. _this._animationTime = 0;
  24475. /**
  24476. * Gets or sets a general scale for animation speed
  24477. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24478. */
  24479. _this.animationTimeScale = 1;
  24480. _this._renderId = 0;
  24481. _this._frameId = 0;
  24482. _this._executeWhenReadyTimeoutId = -1;
  24483. _this._intermediateRendering = false;
  24484. _this._viewUpdateFlag = -1;
  24485. _this._projectionUpdateFlag = -1;
  24486. _this._alternateViewUpdateFlag = -1;
  24487. _this._alternateProjectionUpdateFlag = -1;
  24488. /** @hidden */
  24489. _this._toBeDisposed = new Array(256);
  24490. _this._activeRequests = new Array();
  24491. _this._pendingData = new Array();
  24492. _this._isDisposed = false;
  24493. /**
  24494. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24495. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24496. */
  24497. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24498. _this._activeMeshes = new BABYLON.SmartArray(256);
  24499. _this._processedMaterials = new BABYLON.SmartArray(256);
  24500. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24501. /** @hidden */
  24502. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24503. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24504. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24505. /** @hidden */
  24506. _this._activeAnimatables = new Array();
  24507. _this._transformMatrix = BABYLON.Matrix.Zero();
  24508. _this._useAlternateCameraConfiguration = false;
  24509. _this._alternateRendering = false;
  24510. /**
  24511. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24512. * This is useful if there are more lights that the maximum simulteanous authorized
  24513. */
  24514. _this.requireLightSorting = false;
  24515. /**
  24516. * @hidden
  24517. * Backing store of defined scene components.
  24518. */
  24519. _this._components = [];
  24520. /**
  24521. * @hidden
  24522. * Backing store of defined scene components.
  24523. */
  24524. _this._serializableComponents = [];
  24525. /**
  24526. * List of components to register on the next registration step.
  24527. */
  24528. _this._transientComponents = [];
  24529. /**
  24530. * @hidden
  24531. * Defines the actions happening before camera updates.
  24532. */
  24533. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24534. /**
  24535. * @hidden
  24536. * Defines the actions happening before clear the canvas.
  24537. */
  24538. _this._beforeClearStage = BABYLON.Stage.Create();
  24539. /**
  24540. * @hidden
  24541. * Defines the actions when collecting render targets for the frame.
  24542. */
  24543. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24544. /**
  24545. * @hidden
  24546. * Defines the actions happening for one camera in the frame.
  24547. */
  24548. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24549. /**
  24550. * @hidden
  24551. * Defines the actions happening during the per mesh ready checks.
  24552. */
  24553. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24554. /**
  24555. * @hidden
  24556. * Defines the actions happening before evaluate active mesh checks.
  24557. */
  24558. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24559. /**
  24560. * @hidden
  24561. * Defines the actions happening during the evaluate sub mesh checks.
  24562. */
  24563. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24564. /**
  24565. * @hidden
  24566. * Defines the actions happening during the active mesh stage.
  24567. */
  24568. _this._activeMeshStage = BABYLON.Stage.Create();
  24569. /**
  24570. * @hidden
  24571. * Defines the actions happening during the per camera render target step.
  24572. */
  24573. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24574. /**
  24575. * @hidden
  24576. * Defines the actions happening just before the active camera is drawing.
  24577. */
  24578. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24579. /**
  24580. * @hidden
  24581. * Defines the actions happening just before a rendering group is drawing.
  24582. */
  24583. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24584. /**
  24585. * @hidden
  24586. * Defines the actions happening just before a mesh is drawing.
  24587. */
  24588. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24589. /**
  24590. * @hidden
  24591. * Defines the actions happening just after a mesh has been drawn.
  24592. */
  24593. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24594. /**
  24595. * @hidden
  24596. * Defines the actions happening just after a rendering group has been drawn.
  24597. */
  24598. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24599. /**
  24600. * @hidden
  24601. * Defines the actions happening just after the active camera has been drawn.
  24602. */
  24603. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24604. /**
  24605. * @hidden
  24606. * Defines the actions happening just after rendering all cameras and computing intersections.
  24607. */
  24608. _this._afterRenderStage = BABYLON.Stage.Create();
  24609. /**
  24610. * @hidden
  24611. * Defines the actions happening when a pointer move event happens.
  24612. */
  24613. _this._pointerMoveStage = BABYLON.Stage.Create();
  24614. /**
  24615. * @hidden
  24616. * Defines the actions happening when a pointer down event happens.
  24617. */
  24618. _this._pointerDownStage = BABYLON.Stage.Create();
  24619. /**
  24620. * @hidden
  24621. * Defines the actions happening when a pointer up event happens.
  24622. */
  24623. _this._pointerUpStage = BABYLON.Stage.Create();
  24624. _this._defaultMeshCandidates = {
  24625. data: [],
  24626. length: 0
  24627. };
  24628. _this._defaultSubMeshCandidates = {
  24629. data: [],
  24630. length: 0
  24631. };
  24632. _this._activeMeshesFrozen = false;
  24633. /** @hidden */
  24634. _this._allowPostProcessClearColor = true;
  24635. /**
  24636. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24637. */
  24638. _this.getDeterministicFrameTime = function () {
  24639. return 1000.0 / 60.0; // frame time in ms
  24640. };
  24641. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24642. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24643. _this.blockMaterialDirtyMechanism = false;
  24644. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24645. _this._engine.scenes.push(_this);
  24646. _this._uid = null;
  24647. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24648. if (BABYLON.PostProcessManager) {
  24649. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24650. }
  24651. if (BABYLON.Tools.IsWindowObjectExist()) {
  24652. _this.attachControl();
  24653. }
  24654. //collision coordinator initialization. For now legacy per default.
  24655. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24656. // Uniform Buffer
  24657. _this._createUbo();
  24658. // Default Image processing definition
  24659. if (BABYLON.ImageProcessingConfiguration) {
  24660. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24661. }
  24662. _this.setDefaultCandidateProviders();
  24663. return _this;
  24664. }
  24665. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24666. /**
  24667. * Texture used in all pbr material as the reflection texture.
  24668. * As in the majority of the scene they are the same (exception for multi room and so on),
  24669. * this is easier to reference from here than from all the materials.
  24670. */
  24671. get: function () {
  24672. return this._environmentTexture;
  24673. },
  24674. /**
  24675. * Texture used in all pbr material as the reflection texture.
  24676. * As in the majority of the scene they are the same (exception for multi room and so on),
  24677. * this is easier to set here than in all the materials.
  24678. */
  24679. set: function (value) {
  24680. if (this._environmentTexture === value) {
  24681. return;
  24682. }
  24683. this._environmentTexture = value;
  24684. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24685. },
  24686. enumerable: true,
  24687. configurable: true
  24688. });
  24689. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24690. /**
  24691. * Default image processing configuration used either in the rendering
  24692. * Forward main pass or through the imageProcessingPostProcess if present.
  24693. * As in the majority of the scene they are the same (exception for multi camera),
  24694. * this is easier to reference from here than from all the materials and post process.
  24695. *
  24696. * No setter as we it is a shared configuration, you can set the values instead.
  24697. */
  24698. get: function () {
  24699. return this._imageProcessingConfiguration;
  24700. },
  24701. enumerable: true,
  24702. configurable: true
  24703. });
  24704. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24705. get: function () {
  24706. return this._forceWireframe;
  24707. },
  24708. /**
  24709. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24710. */
  24711. set: function (value) {
  24712. if (this._forceWireframe === value) {
  24713. return;
  24714. }
  24715. this._forceWireframe = value;
  24716. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24717. },
  24718. enumerable: true,
  24719. configurable: true
  24720. });
  24721. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24722. get: function () {
  24723. return this._forcePointsCloud;
  24724. },
  24725. /**
  24726. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24727. */
  24728. set: function (value) {
  24729. if (this._forcePointsCloud === value) {
  24730. return;
  24731. }
  24732. this._forcePointsCloud = value;
  24733. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24739. /**
  24740. * Gets or sets the animation properties override
  24741. */
  24742. get: function () {
  24743. return this._animationPropertiesOverride;
  24744. },
  24745. set: function (value) {
  24746. this._animationPropertiesOverride = value;
  24747. },
  24748. enumerable: true,
  24749. configurable: true
  24750. });
  24751. Object.defineProperty(Scene.prototype, "onDispose", {
  24752. /** Sets a function to be executed when this scene is disposed. */
  24753. set: function (callback) {
  24754. if (this._onDisposeObserver) {
  24755. this.onDisposeObservable.remove(this._onDisposeObserver);
  24756. }
  24757. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24758. },
  24759. enumerable: true,
  24760. configurable: true
  24761. });
  24762. Object.defineProperty(Scene.prototype, "beforeRender", {
  24763. /** Sets a function to be executed before rendering this scene */
  24764. set: function (callback) {
  24765. if (this._onBeforeRenderObserver) {
  24766. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24767. }
  24768. if (callback) {
  24769. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24770. }
  24771. },
  24772. enumerable: true,
  24773. configurable: true
  24774. });
  24775. Object.defineProperty(Scene.prototype, "afterRender", {
  24776. /** Sets a function to be executed after rendering this scene */
  24777. set: function (callback) {
  24778. if (this._onAfterRenderObserver) {
  24779. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24780. }
  24781. if (callback) {
  24782. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24783. }
  24784. },
  24785. enumerable: true,
  24786. configurable: true
  24787. });
  24788. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24789. /** Sets a function to be executed before rendering a camera*/
  24790. set: function (callback) {
  24791. if (this._onBeforeCameraRenderObserver) {
  24792. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24793. }
  24794. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24800. /** Sets a function to be executed after rendering a camera*/
  24801. set: function (callback) {
  24802. if (this._onAfterCameraRenderObserver) {
  24803. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24804. }
  24805. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24811. /**
  24812. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24813. */
  24814. get: function () {
  24815. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24821. get: function () {
  24822. return this._useRightHandedSystem;
  24823. },
  24824. /**
  24825. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24826. */
  24827. set: function (value) {
  24828. if (this._useRightHandedSystem === value) {
  24829. return;
  24830. }
  24831. this._useRightHandedSystem = value;
  24832. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24833. },
  24834. enumerable: true,
  24835. configurable: true
  24836. });
  24837. /**
  24838. * Sets the step Id used by deterministic lock step
  24839. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24840. * @param newStepId defines the step Id
  24841. */
  24842. Scene.prototype.setStepId = function (newStepId) {
  24843. this._currentStepId = newStepId;
  24844. };
  24845. ;
  24846. /**
  24847. * Gets the step Id used by deterministic lock step
  24848. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24849. * @returns the step Id
  24850. */
  24851. Scene.prototype.getStepId = function () {
  24852. return this._currentStepId;
  24853. };
  24854. ;
  24855. /**
  24856. * Gets the internal step used by deterministic lock step
  24857. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24858. * @returns the internal step
  24859. */
  24860. Scene.prototype.getInternalStep = function () {
  24861. return this._currentInternalStep;
  24862. };
  24863. ;
  24864. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24865. get: function () {
  24866. return this._fogEnabled;
  24867. },
  24868. /**
  24869. * Gets or sets a boolean indicating if fog is enabled on this scene
  24870. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24871. */
  24872. set: function (value) {
  24873. if (this._fogEnabled === value) {
  24874. return;
  24875. }
  24876. this._fogEnabled = value;
  24877. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24878. },
  24879. enumerable: true,
  24880. configurable: true
  24881. });
  24882. Object.defineProperty(Scene.prototype, "fogMode", {
  24883. get: function () {
  24884. return this._fogMode;
  24885. },
  24886. /**
  24887. * Gets or sets the fog mode to use
  24888. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24889. */
  24890. set: function (value) {
  24891. if (this._fogMode === value) {
  24892. return;
  24893. }
  24894. this._fogMode = value;
  24895. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24896. },
  24897. enumerable: true,
  24898. configurable: true
  24899. });
  24900. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24901. get: function () {
  24902. return this._shadowsEnabled;
  24903. },
  24904. /**
  24905. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24906. */
  24907. set: function (value) {
  24908. if (this._shadowsEnabled === value) {
  24909. return;
  24910. }
  24911. this._shadowsEnabled = value;
  24912. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24913. },
  24914. enumerable: true,
  24915. configurable: true
  24916. });
  24917. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24918. get: function () {
  24919. return this._lightsEnabled;
  24920. },
  24921. /**
  24922. * Gets or sets a boolean indicating if lights are enabled on this scene
  24923. */
  24924. set: function (value) {
  24925. if (this._lightsEnabled === value) {
  24926. return;
  24927. }
  24928. this._lightsEnabled = value;
  24929. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24935. /** The default material used on meshes when no material is affected */
  24936. get: function () {
  24937. if (!this._defaultMaterial) {
  24938. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24939. }
  24940. return this._defaultMaterial;
  24941. },
  24942. /** The default material used on meshes when no material is affected */
  24943. set: function (value) {
  24944. this._defaultMaterial = value;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24950. get: function () {
  24951. return this._texturesEnabled;
  24952. },
  24953. /**
  24954. * Gets or sets a boolean indicating if textures are enabled on this scene
  24955. */
  24956. set: function (value) {
  24957. if (this._texturesEnabled === value) {
  24958. return;
  24959. }
  24960. this._texturesEnabled = value;
  24961. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24962. },
  24963. enumerable: true,
  24964. configurable: true
  24965. });
  24966. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24967. get: function () {
  24968. return this._skeletonsEnabled;
  24969. },
  24970. /**
  24971. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24972. */
  24973. set: function (value) {
  24974. if (this._skeletonsEnabled === value) {
  24975. return;
  24976. }
  24977. this._skeletonsEnabled = value;
  24978. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24979. },
  24980. enumerable: true,
  24981. configurable: true
  24982. });
  24983. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24984. /** @hidden */
  24985. get: function () {
  24986. return this._alternateRendering;
  24987. },
  24988. enumerable: true,
  24989. configurable: true
  24990. });
  24991. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24992. /**
  24993. * Gets the list of frustum planes (built from the active camera)
  24994. */
  24995. get: function () {
  24996. return this._frustumPlanes;
  24997. },
  24998. enumerable: true,
  24999. configurable: true
  25000. });
  25001. /**
  25002. * Registers the transient components if needed.
  25003. */
  25004. Scene.prototype._registerTransientComponents = function () {
  25005. // Register components that have been associated lately to the scene.
  25006. if (this._transientComponents.length > 0) {
  25007. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25008. var component = _a[_i];
  25009. component.register();
  25010. }
  25011. this._transientComponents = [];
  25012. }
  25013. };
  25014. /**
  25015. * @hidden
  25016. * Add a component to the scene.
  25017. * Note that the ccomponent could be registered on th next frame if this is called after
  25018. * the register component stage.
  25019. * @param component Defines the component to add to the scene
  25020. */
  25021. Scene.prototype._addComponent = function (component) {
  25022. this._components.push(component);
  25023. this._transientComponents.push(component);
  25024. var serializableComponent = component;
  25025. if (serializableComponent.addFromContainer) {
  25026. this._serializableComponents.push(serializableComponent);
  25027. }
  25028. };
  25029. /**
  25030. * @hidden
  25031. * Gets a component from the scene.
  25032. * @param name defines the name of the component to retrieve
  25033. * @returns the component or null if not present
  25034. */
  25035. Scene.prototype._getComponent = function (name) {
  25036. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25037. var component = _a[_i];
  25038. if (component.name === name) {
  25039. return component;
  25040. }
  25041. }
  25042. return null;
  25043. };
  25044. /**
  25045. * @hidden
  25046. */
  25047. Scene.prototype._getDefaultMeshCandidates = function () {
  25048. this._defaultMeshCandidates.data = this.meshes;
  25049. this._defaultMeshCandidates.length = this.meshes.length;
  25050. return this._defaultMeshCandidates;
  25051. };
  25052. /**
  25053. * @hidden
  25054. */
  25055. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25056. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25057. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25058. return this._defaultSubMeshCandidates;
  25059. };
  25060. /**
  25061. * Sets the default candidate providers for the scene.
  25062. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25063. * and getCollidingSubMeshCandidates to their default function
  25064. */
  25065. Scene.prototype.setDefaultCandidateProviders = function () {
  25066. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25067. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25068. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25069. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25070. };
  25071. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25072. /**
  25073. * Gets a boolean indicating if collisions are processed on a web worker
  25074. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25075. */
  25076. get: function () {
  25077. return this._workerCollisions;
  25078. },
  25079. set: function (enabled) {
  25080. if (!BABYLON.CollisionCoordinatorLegacy) {
  25081. return;
  25082. }
  25083. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25084. this._workerCollisions = enabled;
  25085. if (this.collisionCoordinator) {
  25086. this.collisionCoordinator.destroy();
  25087. }
  25088. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25089. this.collisionCoordinator.init(this);
  25090. },
  25091. enumerable: true,
  25092. configurable: true
  25093. });
  25094. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25095. /**
  25096. * Gets the mesh that is currently under the pointer
  25097. */
  25098. get: function () {
  25099. return this._pointerOverMesh;
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. Object.defineProperty(Scene.prototype, "pointerX", {
  25105. /**
  25106. * Gets the current on-screen X position of the pointer
  25107. */
  25108. get: function () {
  25109. return this._pointerX;
  25110. },
  25111. enumerable: true,
  25112. configurable: true
  25113. });
  25114. Object.defineProperty(Scene.prototype, "pointerY", {
  25115. /**
  25116. * Gets the current on-screen Y position of the pointer
  25117. */
  25118. get: function () {
  25119. return this._pointerY;
  25120. },
  25121. enumerable: true,
  25122. configurable: true
  25123. });
  25124. /**
  25125. * Gets the cached material (ie. the latest rendered one)
  25126. * @returns the cached material
  25127. */
  25128. Scene.prototype.getCachedMaterial = function () {
  25129. return this._cachedMaterial;
  25130. };
  25131. /**
  25132. * Gets the cached effect (ie. the latest rendered one)
  25133. * @returns the cached effect
  25134. */
  25135. Scene.prototype.getCachedEffect = function () {
  25136. return this._cachedEffect;
  25137. };
  25138. /**
  25139. * Gets the cached visibility state (ie. the latest rendered one)
  25140. * @returns the cached visibility state
  25141. */
  25142. Scene.prototype.getCachedVisibility = function () {
  25143. return this._cachedVisibility;
  25144. };
  25145. /**
  25146. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25147. * @param material defines the current material
  25148. * @param effect defines the current effect
  25149. * @param visibility defines the current visibility state
  25150. * @returns true if one parameter is not cached
  25151. */
  25152. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25153. if (visibility === void 0) { visibility = 1; }
  25154. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25155. };
  25156. /**
  25157. * Gets the engine associated with the scene
  25158. * @returns an Engine
  25159. */
  25160. Scene.prototype.getEngine = function () {
  25161. return this._engine;
  25162. };
  25163. /**
  25164. * Gets the total number of vertices rendered per frame
  25165. * @returns the total number of vertices rendered per frame
  25166. */
  25167. Scene.prototype.getTotalVertices = function () {
  25168. return this._totalVertices.current;
  25169. };
  25170. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25171. /**
  25172. * Gets the performance counter for total vertices
  25173. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25174. */
  25175. get: function () {
  25176. return this._totalVertices;
  25177. },
  25178. enumerable: true,
  25179. configurable: true
  25180. });
  25181. /**
  25182. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25183. * @returns the total number of active indices rendered per frame
  25184. */
  25185. Scene.prototype.getActiveIndices = function () {
  25186. return this._activeIndices.current;
  25187. };
  25188. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25189. /**
  25190. * Gets the performance counter for active indices
  25191. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25192. */
  25193. get: function () {
  25194. return this._activeIndices;
  25195. },
  25196. enumerable: true,
  25197. configurable: true
  25198. });
  25199. /**
  25200. * Gets the total number of active particles rendered per frame
  25201. * @returns the total number of active particles rendered per frame
  25202. */
  25203. Scene.prototype.getActiveParticles = function () {
  25204. return this._activeParticles.current;
  25205. };
  25206. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25207. /**
  25208. * Gets the performance counter for active particles
  25209. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25210. */
  25211. get: function () {
  25212. return this._activeParticles;
  25213. },
  25214. enumerable: true,
  25215. configurable: true
  25216. });
  25217. /**
  25218. * Gets the total number of active bones rendered per frame
  25219. * @returns the total number of active bones rendered per frame
  25220. */
  25221. Scene.prototype.getActiveBones = function () {
  25222. return this._activeBones.current;
  25223. };
  25224. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25225. /**
  25226. * Gets the performance counter for active bones
  25227. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25228. */
  25229. get: function () {
  25230. return this._activeBones;
  25231. },
  25232. enumerable: true,
  25233. configurable: true
  25234. });
  25235. /** @hidden */
  25236. Scene.prototype.getInterFramePerfCounter = function () {
  25237. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25238. return 0;
  25239. };
  25240. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25241. /** @hidden */
  25242. get: function () {
  25243. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25244. return null;
  25245. },
  25246. enumerable: true,
  25247. configurable: true
  25248. });
  25249. /** @hidden */
  25250. Scene.prototype.getLastFrameDuration = function () {
  25251. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25252. return 0;
  25253. };
  25254. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25255. /** @hidden */
  25256. get: function () {
  25257. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25258. return null;
  25259. },
  25260. enumerable: true,
  25261. configurable: true
  25262. });
  25263. /** @hidden */
  25264. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25265. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25266. return 0;
  25267. };
  25268. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25269. /** @hidden */
  25270. get: function () {
  25271. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25272. return null;
  25273. },
  25274. enumerable: true,
  25275. configurable: true
  25276. });
  25277. /**
  25278. * Gets the array of active meshes
  25279. * @returns an array of AbstractMesh
  25280. */
  25281. Scene.prototype.getActiveMeshes = function () {
  25282. return this._activeMeshes;
  25283. };
  25284. /** @hidden */
  25285. Scene.prototype.getRenderTargetsDuration = function () {
  25286. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25287. return 0;
  25288. };
  25289. /** @hidden */
  25290. Scene.prototype.getRenderDuration = function () {
  25291. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25292. return 0;
  25293. };
  25294. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25295. /** @hidden */
  25296. get: function () {
  25297. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25298. return null;
  25299. },
  25300. enumerable: true,
  25301. configurable: true
  25302. });
  25303. /** @hidden */
  25304. Scene.prototype.getParticlesDuration = function () {
  25305. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25306. return 0;
  25307. };
  25308. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25309. /** @hidden */
  25310. get: function () {
  25311. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25312. return null;
  25313. },
  25314. enumerable: true,
  25315. configurable: true
  25316. });
  25317. /** @hidden */
  25318. Scene.prototype.getSpritesDuration = function () {
  25319. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25320. return 0;
  25321. };
  25322. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25323. /** @hidden */
  25324. get: function () {
  25325. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25326. return null;
  25327. },
  25328. enumerable: true,
  25329. configurable: true
  25330. });
  25331. /**
  25332. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25333. * @returns a number
  25334. */
  25335. Scene.prototype.getAnimationRatio = function () {
  25336. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25337. };
  25338. /**
  25339. * Gets an unique Id for the current render phase
  25340. * @returns a number
  25341. */
  25342. Scene.prototype.getRenderId = function () {
  25343. return this._renderId;
  25344. };
  25345. /**
  25346. * Gets an unique Id for the current frame
  25347. * @returns a number
  25348. */
  25349. Scene.prototype.getFrameId = function () {
  25350. return this._frameId;
  25351. };
  25352. /** Call this function if you want to manually increment the render Id*/
  25353. Scene.prototype.incrementRenderId = function () {
  25354. this._renderId++;
  25355. };
  25356. Scene.prototype._updatePointerPosition = function (evt) {
  25357. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25358. if (!canvasRect) {
  25359. return;
  25360. }
  25361. this._pointerX = evt.clientX - canvasRect.left;
  25362. this._pointerY = evt.clientY - canvasRect.top;
  25363. this._unTranslatedPointerX = this._pointerX;
  25364. this._unTranslatedPointerY = this._pointerY;
  25365. };
  25366. Scene.prototype._createUbo = function () {
  25367. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25368. this._sceneUbo.addUniform("viewProjection", 16);
  25369. this._sceneUbo.addUniform("view", 16);
  25370. };
  25371. Scene.prototype._createAlternateUbo = function () {
  25372. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25373. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25374. this._alternateSceneUbo.addUniform("view", 16);
  25375. };
  25376. // Pointers handling
  25377. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25378. if (pointerInfo.pickInfo) {
  25379. if (!pointerInfo.pickInfo.ray) {
  25380. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25381. }
  25382. }
  25383. };
  25384. /**
  25385. * Use this method to simulate a pointer move on a mesh
  25386. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25387. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25388. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25389. * @returns the current scene
  25390. */
  25391. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25392. var evt = new PointerEvent("pointermove", pointerEventInit);
  25393. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25394. return this;
  25395. }
  25396. return this._processPointerMove(pickResult, evt);
  25397. };
  25398. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25399. var canvas = this._engine.getRenderingCanvas();
  25400. if (!canvas) {
  25401. return this;
  25402. }
  25403. // Restore pointer
  25404. canvas.style.cursor = this.defaultCursor;
  25405. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25406. if (isMeshPicked) {
  25407. this.setPointerOverMesh(pickResult.pickedMesh);
  25408. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25409. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25410. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25411. }
  25412. else {
  25413. canvas.style.cursor = this.hoverCursor;
  25414. }
  25415. }
  25416. }
  25417. else {
  25418. this.setPointerOverMesh(null);
  25419. }
  25420. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25421. var step = _a[_i];
  25422. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25423. }
  25424. if (pickResult) {
  25425. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25426. if (this.onPointerMove) {
  25427. this.onPointerMove(evt, pickResult, type);
  25428. }
  25429. if (this.onPointerObservable.hasObservers()) {
  25430. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25431. this._setRayOnPointerInfo(pi);
  25432. this.onPointerObservable.notifyObservers(pi, type);
  25433. }
  25434. }
  25435. return this;
  25436. };
  25437. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25438. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25439. if (pickResult) {
  25440. pi.ray = pickResult.ray;
  25441. }
  25442. this.onPrePointerObservable.notifyObservers(pi, type);
  25443. if (pi.skipOnPointerObservable) {
  25444. return true;
  25445. }
  25446. else {
  25447. return false;
  25448. }
  25449. };
  25450. /**
  25451. * Use this method to simulate a pointer down on a mesh
  25452. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25453. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25454. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25455. * @returns the current scene
  25456. */
  25457. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25458. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25459. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25460. return this;
  25461. }
  25462. return this._processPointerDown(pickResult, evt);
  25463. };
  25464. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25465. var _this = this;
  25466. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25467. this._pickedDownMesh = pickResult.pickedMesh;
  25468. var actionManager = pickResult.pickedMesh.actionManager;
  25469. if (actionManager) {
  25470. if (actionManager.hasPickTriggers) {
  25471. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25472. switch (evt.button) {
  25473. case 0:
  25474. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25475. break;
  25476. case 1:
  25477. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25478. break;
  25479. case 2:
  25480. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25481. break;
  25482. }
  25483. }
  25484. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25485. window.setTimeout(function () {
  25486. 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);
  25487. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25488. if (_this._totalPointersPressed !== 0 &&
  25489. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25490. !_this._isPointerSwiping()) {
  25491. _this._startingPointerTime = 0;
  25492. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25493. }
  25494. }
  25495. }, Scene.LongPressDelay);
  25496. }
  25497. }
  25498. }
  25499. else {
  25500. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25501. var step = _a[_i];
  25502. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25503. }
  25504. }
  25505. if (pickResult) {
  25506. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25507. if (this.onPointerDown) {
  25508. this.onPointerDown(evt, pickResult, type);
  25509. }
  25510. if (this.onPointerObservable.hasObservers()) {
  25511. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25512. this._setRayOnPointerInfo(pi);
  25513. this.onPointerObservable.notifyObservers(pi, type);
  25514. }
  25515. }
  25516. return this;
  25517. };
  25518. /**
  25519. * Use this method to simulate a pointer up on a mesh
  25520. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25521. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25522. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25523. * @returns the current scene
  25524. */
  25525. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25526. var evt = new PointerEvent("pointerup", pointerEventInit);
  25527. var clickInfo = new ClickInfo();
  25528. clickInfo.singleClick = true;
  25529. clickInfo.ignore = true;
  25530. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25531. return this;
  25532. }
  25533. return this._processPointerUp(pickResult, evt, clickInfo);
  25534. };
  25535. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25536. if (pickResult && pickResult && pickResult.pickedMesh) {
  25537. this._pickedUpMesh = pickResult.pickedMesh;
  25538. if (this._pickedDownMesh === this._pickedUpMesh) {
  25539. if (this.onPointerPick) {
  25540. this.onPointerPick(evt, pickResult);
  25541. }
  25542. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25543. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25544. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25545. this._setRayOnPointerInfo(pi);
  25546. this.onPointerObservable.notifyObservers(pi, type_1);
  25547. }
  25548. }
  25549. if (pickResult.pickedMesh.actionManager) {
  25550. if (clickInfo.ignore) {
  25551. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25552. }
  25553. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25554. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25555. }
  25556. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25557. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25558. }
  25559. }
  25560. }
  25561. else {
  25562. if (!clickInfo.ignore) {
  25563. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25564. var step = _a[_i];
  25565. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25566. }
  25567. }
  25568. }
  25569. if (this._pickedDownMesh &&
  25570. this._pickedDownMesh.actionManager &&
  25571. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25572. this._pickedDownMesh !== this._pickedUpMesh) {
  25573. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25574. }
  25575. var type = BABYLON.PointerEventTypes.POINTERUP;
  25576. if (this.onPointerObservable.hasObservers()) {
  25577. if (!clickInfo.ignore) {
  25578. if (!clickInfo.hasSwiped) {
  25579. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25580. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25581. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25582. this._setRayOnPointerInfo(pi);
  25583. this.onPointerObservable.notifyObservers(pi, type_2);
  25584. }
  25585. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25586. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25587. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25588. this._setRayOnPointerInfo(pi);
  25589. this.onPointerObservable.notifyObservers(pi, type_3);
  25590. }
  25591. }
  25592. }
  25593. else {
  25594. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25595. this._setRayOnPointerInfo(pi);
  25596. this.onPointerObservable.notifyObservers(pi, type);
  25597. }
  25598. }
  25599. if (this.onPointerUp) {
  25600. this.onPointerUp(evt, pickResult, type);
  25601. }
  25602. return this;
  25603. };
  25604. /**
  25605. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25606. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25607. * @returns true if the pointer was captured
  25608. */
  25609. Scene.prototype.isPointerCaptured = function (pointerId) {
  25610. if (pointerId === void 0) { pointerId = 0; }
  25611. return this._pointerCaptures[pointerId];
  25612. };
  25613. /** @hidden */
  25614. Scene.prototype._isPointerSwiping = function () {
  25615. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25616. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25617. };
  25618. /**
  25619. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25620. * @param attachUp defines if you want to attach events to pointerup
  25621. * @param attachDown defines if you want to attach events to pointerdown
  25622. * @param attachMove defines if you want to attach events to pointermove
  25623. */
  25624. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25625. var _this = this;
  25626. if (attachUp === void 0) { attachUp = true; }
  25627. if (attachDown === void 0) { attachDown = true; }
  25628. if (attachMove === void 0) { attachMove = true; }
  25629. this._initActionManager = function (act, clickInfo) {
  25630. if (!_this._meshPickProceed) {
  25631. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25632. _this._currentPickResult = pickResult;
  25633. if (pickResult) {
  25634. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25635. }
  25636. _this._meshPickProceed = true;
  25637. }
  25638. return act;
  25639. };
  25640. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25641. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25642. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25643. btn !== _this._previousButtonPressed) {
  25644. _this._doubleClickOccured = false;
  25645. clickInfo.singleClick = true;
  25646. clickInfo.ignore = false;
  25647. cb(clickInfo, _this._currentPickResult);
  25648. }
  25649. };
  25650. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25651. var clickInfo = new ClickInfo();
  25652. _this._currentPickResult = null;
  25653. var act = null;
  25654. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25655. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25656. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25657. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25658. act = _this._initActionManager(act, clickInfo);
  25659. if (act)
  25660. checkPicking = act.hasPickTriggers;
  25661. }
  25662. if (checkPicking) {
  25663. var btn = evt.button;
  25664. clickInfo.hasSwiped = _this._isPointerSwiping();
  25665. if (!clickInfo.hasSwiped) {
  25666. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25667. if (!checkSingleClickImmediately) {
  25668. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25669. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25670. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25671. act = _this._initActionManager(act, clickInfo);
  25672. if (act)
  25673. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25674. }
  25675. }
  25676. if (checkSingleClickImmediately) {
  25677. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25678. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25679. btn !== _this._previousButtonPressed) {
  25680. clickInfo.singleClick = true;
  25681. cb(clickInfo, _this._currentPickResult);
  25682. }
  25683. }
  25684. // at least one double click is required to be check and exclusive double click is enabled
  25685. else {
  25686. // wait that no double click has been raised during the double click delay
  25687. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25688. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25689. }
  25690. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25691. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25692. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25693. act = _this._initActionManager(act, clickInfo);
  25694. if (act)
  25695. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25696. }
  25697. if (checkDoubleClick) {
  25698. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25699. if (btn === _this._previousButtonPressed &&
  25700. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25701. !_this._doubleClickOccured) {
  25702. // pointer has not moved for 2 clicks, it's a double click
  25703. if (!clickInfo.hasSwiped &&
  25704. !_this._isPointerSwiping()) {
  25705. _this._previousStartingPointerTime = 0;
  25706. _this._doubleClickOccured = true;
  25707. clickInfo.doubleClick = true;
  25708. clickInfo.ignore = false;
  25709. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25710. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25711. }
  25712. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25713. cb(clickInfo, _this._currentPickResult);
  25714. }
  25715. // if the two successive clicks are too far, it's just two simple clicks
  25716. else {
  25717. _this._doubleClickOccured = false;
  25718. _this._previousStartingPointerTime = _this._startingPointerTime;
  25719. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25720. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25721. _this._previousButtonPressed = btn;
  25722. if (Scene.ExclusiveDoubleClickMode) {
  25723. if (_this._previousDelayedSimpleClickTimeout) {
  25724. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25725. }
  25726. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25727. cb(clickInfo, _this._previousPickResult);
  25728. }
  25729. else {
  25730. cb(clickInfo, _this._currentPickResult);
  25731. }
  25732. }
  25733. }
  25734. // just the first click of the double has been raised
  25735. else {
  25736. _this._doubleClickOccured = false;
  25737. _this._previousStartingPointerTime = _this._startingPointerTime;
  25738. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25739. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25740. _this._previousButtonPressed = btn;
  25741. }
  25742. }
  25743. }
  25744. }
  25745. clickInfo.ignore = true;
  25746. cb(clickInfo, _this._currentPickResult);
  25747. };
  25748. this._onPointerMove = function (evt) {
  25749. _this._updatePointerPosition(evt);
  25750. // PreObservable support
  25751. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25752. return;
  25753. }
  25754. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25755. return;
  25756. }
  25757. if (!_this.pointerMovePredicate) {
  25758. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25759. }
  25760. // Meshes
  25761. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25762. _this._processPointerMove(pickResult, evt);
  25763. };
  25764. this._onPointerDown = function (evt) {
  25765. _this._totalPointersPressed++;
  25766. _this._pickedDownMesh = null;
  25767. _this._meshPickProceed = false;
  25768. _this._updatePointerPosition(evt);
  25769. if (_this.preventDefaultOnPointerDown && canvas) {
  25770. evt.preventDefault();
  25771. canvas.focus();
  25772. }
  25773. // PreObservable support
  25774. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25775. return;
  25776. }
  25777. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25778. return;
  25779. }
  25780. _this._pointerCaptures[evt.pointerId] = true;
  25781. _this._startingPointerPosition.x = _this._pointerX;
  25782. _this._startingPointerPosition.y = _this._pointerY;
  25783. _this._startingPointerTime = Date.now();
  25784. if (!_this.pointerDownPredicate) {
  25785. _this.pointerDownPredicate = function (mesh) {
  25786. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25787. };
  25788. }
  25789. // Meshes
  25790. _this._pickedDownMesh = null;
  25791. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25792. _this._processPointerDown(pickResult, evt);
  25793. };
  25794. this._onPointerUp = function (evt) {
  25795. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25796. return; // So we need to test it the pointer down was pressed before.
  25797. }
  25798. _this._totalPointersPressed--;
  25799. _this._pickedUpMesh = null;
  25800. _this._meshPickProceed = false;
  25801. _this._updatePointerPosition(evt);
  25802. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25803. // PreObservable support
  25804. if (_this.onPrePointerObservable.hasObservers()) {
  25805. if (!clickInfo.ignore) {
  25806. if (!clickInfo.hasSwiped) {
  25807. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25808. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25809. return;
  25810. }
  25811. }
  25812. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25813. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25814. return;
  25815. }
  25816. }
  25817. }
  25818. }
  25819. else {
  25820. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25821. return;
  25822. }
  25823. }
  25824. }
  25825. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25826. return;
  25827. }
  25828. _this._pointerCaptures[evt.pointerId] = false;
  25829. if (!_this.pointerUpPredicate) {
  25830. _this.pointerUpPredicate = function (mesh) {
  25831. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25832. };
  25833. }
  25834. // Meshes
  25835. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25836. _this._initActionManager(null, clickInfo);
  25837. }
  25838. if (!pickResult) {
  25839. pickResult = _this._currentPickResult;
  25840. }
  25841. _this._processPointerUp(pickResult, evt, clickInfo);
  25842. _this._previousPickResult = _this._currentPickResult;
  25843. });
  25844. };
  25845. this._onKeyDown = function (evt) {
  25846. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25847. if (_this.onPreKeyboardObservable.hasObservers()) {
  25848. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25849. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25850. if (pi.skipOnPointerObservable) {
  25851. return;
  25852. }
  25853. }
  25854. if (_this.onKeyboardObservable.hasObservers()) {
  25855. var pi = new BABYLON.KeyboardInfo(type, evt);
  25856. _this.onKeyboardObservable.notifyObservers(pi, type);
  25857. }
  25858. if (_this.actionManager) {
  25859. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25860. }
  25861. };
  25862. this._onKeyUp = function (evt) {
  25863. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25864. if (_this.onPreKeyboardObservable.hasObservers()) {
  25865. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25866. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25867. if (pi.skipOnPointerObservable) {
  25868. return;
  25869. }
  25870. }
  25871. if (_this.onKeyboardObservable.hasObservers()) {
  25872. var pi = new BABYLON.KeyboardInfo(type, evt);
  25873. _this.onKeyboardObservable.notifyObservers(pi, type);
  25874. }
  25875. if (_this.actionManager) {
  25876. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25877. }
  25878. };
  25879. var engine = this.getEngine();
  25880. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25881. if (!canvas) {
  25882. return;
  25883. }
  25884. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25885. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25886. });
  25887. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25888. if (!canvas) {
  25889. return;
  25890. }
  25891. canvas.removeEventListener("keydown", _this._onKeyDown);
  25892. canvas.removeEventListener("keyup", _this._onKeyUp);
  25893. });
  25894. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25895. var canvas = this._engine.getRenderingCanvas();
  25896. if (!canvas) {
  25897. return;
  25898. }
  25899. if (attachMove) {
  25900. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25901. // Wheel
  25902. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25903. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25904. }
  25905. if (attachDown) {
  25906. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25907. }
  25908. if (attachUp) {
  25909. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25910. }
  25911. canvas.tabIndex = 1;
  25912. };
  25913. /** Detaches all event handlers*/
  25914. Scene.prototype.detachControl = function () {
  25915. var engine = this.getEngine();
  25916. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25917. var canvas = engine.getRenderingCanvas();
  25918. if (!canvas) {
  25919. return;
  25920. }
  25921. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25922. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25923. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25924. if (this._onCanvasBlurObserver) {
  25925. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25926. }
  25927. if (this._onCanvasFocusObserver) {
  25928. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25929. }
  25930. // Wheel
  25931. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25932. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25933. // Keyboard
  25934. canvas.removeEventListener("keydown", this._onKeyDown);
  25935. canvas.removeEventListener("keyup", this._onKeyUp);
  25936. // Observables
  25937. this.onKeyboardObservable.clear();
  25938. this.onPreKeyboardObservable.clear();
  25939. this.onPointerObservable.clear();
  25940. this.onPrePointerObservable.clear();
  25941. };
  25942. /**
  25943. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25944. * Delay loaded resources are not taking in account
  25945. * @return true if all required resources are ready
  25946. */
  25947. Scene.prototype.isReady = function () {
  25948. if (this._isDisposed) {
  25949. return false;
  25950. }
  25951. if (this._pendingData.length > 0) {
  25952. return false;
  25953. }
  25954. var index;
  25955. var engine = this.getEngine();
  25956. // Geometries
  25957. for (index = 0; index < this.geometries.length; index++) {
  25958. var geometry = this.geometries[index];
  25959. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25960. return false;
  25961. }
  25962. }
  25963. // Meshes
  25964. for (index = 0; index < this.meshes.length; index++) {
  25965. var mesh = this.meshes[index];
  25966. if (!mesh.isEnabled()) {
  25967. continue;
  25968. }
  25969. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25970. continue;
  25971. }
  25972. if (!mesh.isReady(true)) {
  25973. return false;
  25974. }
  25975. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25976. // Is Ready For Mesh
  25977. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25978. var step = _a[_i];
  25979. if (!step.action(mesh, hardwareInstancedRendering)) {
  25980. return false;
  25981. }
  25982. }
  25983. }
  25984. // Post-processes
  25985. if (this.activeCameras && this.activeCameras.length > 0) {
  25986. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25987. var camera = _c[_b];
  25988. if (!camera.isReady(true)) {
  25989. return false;
  25990. }
  25991. }
  25992. }
  25993. else if (this.activeCamera) {
  25994. if (!this.activeCamera.isReady(true)) {
  25995. return false;
  25996. }
  25997. }
  25998. // Particles
  25999. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26000. var particleSystem = _e[_d];
  26001. if (!particleSystem.isReady()) {
  26002. return false;
  26003. }
  26004. }
  26005. return true;
  26006. };
  26007. /** Resets all cached information relative to material (including effect and visibility) */
  26008. Scene.prototype.resetCachedMaterial = function () {
  26009. this._cachedMaterial = null;
  26010. this._cachedEffect = null;
  26011. this._cachedVisibility = null;
  26012. };
  26013. /**
  26014. * Registers a function to be called before every frame render
  26015. * @param func defines the function to register
  26016. */
  26017. Scene.prototype.registerBeforeRender = function (func) {
  26018. this.onBeforeRenderObservable.add(func);
  26019. };
  26020. /**
  26021. * Unregisters a function called before every frame render
  26022. * @param func defines the function to unregister
  26023. */
  26024. Scene.prototype.unregisterBeforeRender = function (func) {
  26025. this.onBeforeRenderObservable.removeCallback(func);
  26026. };
  26027. /**
  26028. * Registers a function to be called after every frame render
  26029. * @param func defines the function to register
  26030. */
  26031. Scene.prototype.registerAfterRender = function (func) {
  26032. this.onAfterRenderObservable.add(func);
  26033. };
  26034. /**
  26035. * Unregisters a function called after every frame render
  26036. * @param func defines the function to unregister
  26037. */
  26038. Scene.prototype.unregisterAfterRender = function (func) {
  26039. this.onAfterRenderObservable.removeCallback(func);
  26040. };
  26041. Scene.prototype._executeOnceBeforeRender = function (func) {
  26042. var _this = this;
  26043. var execFunc = function () {
  26044. func();
  26045. setTimeout(function () {
  26046. _this.unregisterBeforeRender(execFunc);
  26047. });
  26048. };
  26049. this.registerBeforeRender(execFunc);
  26050. };
  26051. /**
  26052. * The provided function will run before render once and will be disposed afterwards.
  26053. * A timeout delay can be provided so that the function will be executed in N ms.
  26054. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26055. * @param func The function to be executed.
  26056. * @param timeout optional delay in ms
  26057. */
  26058. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26059. var _this = this;
  26060. if (timeout !== undefined) {
  26061. setTimeout(function () {
  26062. _this._executeOnceBeforeRender(func);
  26063. }, timeout);
  26064. }
  26065. else {
  26066. this._executeOnceBeforeRender(func);
  26067. }
  26068. };
  26069. /** @hidden */
  26070. Scene.prototype._addPendingData = function (data) {
  26071. this._pendingData.push(data);
  26072. };
  26073. /** @hidden */
  26074. Scene.prototype._removePendingData = function (data) {
  26075. var wasLoading = this.isLoading;
  26076. var index = this._pendingData.indexOf(data);
  26077. if (index !== -1) {
  26078. this._pendingData.splice(index, 1);
  26079. }
  26080. if (wasLoading && !this.isLoading) {
  26081. this.onDataLoadedObservable.notifyObservers(this);
  26082. }
  26083. };
  26084. /**
  26085. * Returns the number of items waiting to be loaded
  26086. * @returns the number of items waiting to be loaded
  26087. */
  26088. Scene.prototype.getWaitingItemsCount = function () {
  26089. return this._pendingData.length;
  26090. };
  26091. Object.defineProperty(Scene.prototype, "isLoading", {
  26092. /**
  26093. * Returns a boolean indicating if the scene is still loading data
  26094. */
  26095. get: function () {
  26096. return this._pendingData.length > 0;
  26097. },
  26098. enumerable: true,
  26099. configurable: true
  26100. });
  26101. /**
  26102. * Registers a function to be executed when the scene is ready
  26103. * @param {Function} func - the function to be executed
  26104. */
  26105. Scene.prototype.executeWhenReady = function (func) {
  26106. var _this = this;
  26107. this.onReadyObservable.add(func);
  26108. if (this._executeWhenReadyTimeoutId !== -1) {
  26109. return;
  26110. }
  26111. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26112. _this._checkIsReady();
  26113. }, 150);
  26114. };
  26115. /**
  26116. * Returns a promise that resolves when the scene is ready
  26117. * @returns A promise that resolves when the scene is ready
  26118. */
  26119. Scene.prototype.whenReadyAsync = function () {
  26120. var _this = this;
  26121. return new Promise(function (resolve) {
  26122. _this.executeWhenReady(function () {
  26123. resolve();
  26124. });
  26125. });
  26126. };
  26127. /** @hidden */
  26128. Scene.prototype._checkIsReady = function () {
  26129. var _this = this;
  26130. this._registerTransientComponents();
  26131. if (this.isReady()) {
  26132. this.onReadyObservable.notifyObservers(this);
  26133. this.onReadyObservable.clear();
  26134. this._executeWhenReadyTimeoutId = -1;
  26135. return;
  26136. }
  26137. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26138. _this._checkIsReady();
  26139. }, 150);
  26140. };
  26141. // Animations
  26142. /**
  26143. * Will start the animation sequence of a given target
  26144. * @param target defines the target
  26145. * @param from defines from which frame should animation start
  26146. * @param to defines until which frame should animation run.
  26147. * @param weight defines the weight to apply to the animation (1.0 by default)
  26148. * @param loop defines if the animation loops
  26149. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26150. * @param onAnimationEnd defines the function to be executed when the animation ends
  26151. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26152. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26153. * @returns the animatable object created for this animation
  26154. */
  26155. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26156. if (weight === void 0) { weight = 1.0; }
  26157. if (speedRatio === void 0) { speedRatio = 1.0; }
  26158. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26159. returnedAnimatable.weight = weight;
  26160. return returnedAnimatable;
  26161. };
  26162. /**
  26163. * Will start the animation sequence of a given target
  26164. * @param target defines the target
  26165. * @param from defines from which frame should animation start
  26166. * @param to defines until which frame should animation run.
  26167. * @param loop defines if the animation loops
  26168. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26169. * @param onAnimationEnd defines the function to be executed when the animation ends
  26170. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26171. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26172. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26173. * @returns the animatable object created for this animation
  26174. */
  26175. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26176. if (speedRatio === void 0) { speedRatio = 1.0; }
  26177. if (stopCurrent === void 0) { stopCurrent = true; }
  26178. if (from > to && speedRatio > 0) {
  26179. speedRatio *= -1;
  26180. }
  26181. if (stopCurrent) {
  26182. this.stopAnimation(target, undefined, targetMask);
  26183. }
  26184. if (!animatable) {
  26185. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26186. }
  26187. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26188. // Local animations
  26189. if (target.animations && shouldRunTargetAnimations) {
  26190. animatable.appendAnimations(target, target.animations);
  26191. }
  26192. // Children animations
  26193. if (target.getAnimatables) {
  26194. var animatables = target.getAnimatables();
  26195. for (var index = 0; index < animatables.length; index++) {
  26196. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26197. }
  26198. }
  26199. animatable.reset();
  26200. return animatable;
  26201. };
  26202. /**
  26203. * Begin a new animation on a given node
  26204. * @param target defines the target where the animation will take place
  26205. * @param animations defines the list of animations to start
  26206. * @param from defines the initial value
  26207. * @param to defines the final value
  26208. * @param loop defines if you want animation to loop (off by default)
  26209. * @param speedRatio defines the speed ratio to apply to all animations
  26210. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26211. * @returns the list of created animatables
  26212. */
  26213. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26214. if (speedRatio === undefined) {
  26215. speedRatio = 1.0;
  26216. }
  26217. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26218. return animatable;
  26219. };
  26220. /**
  26221. * Begin a new animation on a given node and its hierarchy
  26222. * @param target defines the root node where the animation will take place
  26223. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  26224. * @param animations defines the list of animations to start
  26225. * @param from defines the initial value
  26226. * @param to defines the final value
  26227. * @param loop defines if you want animation to loop (off by default)
  26228. * @param speedRatio defines the speed ratio to apply to all animations
  26229. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26230. * @returns the list of animatables created for all nodes
  26231. */
  26232. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26233. var children = target.getDescendants(directDescendantsOnly);
  26234. var result = [];
  26235. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26236. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26237. var child = children_1[_i];
  26238. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26239. }
  26240. return result;
  26241. };
  26242. /**
  26243. * Gets the animatable associated with a specific target
  26244. * @param target defines the target of the animatable
  26245. * @returns the required animatable if found
  26246. */
  26247. Scene.prototype.getAnimatableByTarget = function (target) {
  26248. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26249. if (this._activeAnimatables[index].target === target) {
  26250. return this._activeAnimatables[index];
  26251. }
  26252. }
  26253. return null;
  26254. };
  26255. /**
  26256. * Gets all animatables associated with a given target
  26257. * @param target defines the target to look animatables for
  26258. * @returns an array of Animatables
  26259. */
  26260. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26261. var result = [];
  26262. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26263. if (this._activeAnimatables[index].target === target) {
  26264. result.push(this._activeAnimatables[index]);
  26265. }
  26266. }
  26267. return result;
  26268. };
  26269. Object.defineProperty(Scene.prototype, "animatables", {
  26270. /**
  26271. * Gets all animatable attached to the scene
  26272. */
  26273. get: function () {
  26274. return this._activeAnimatables;
  26275. },
  26276. enumerable: true,
  26277. configurable: true
  26278. });
  26279. /**
  26280. * Will stop the animation of the given target
  26281. * @param target - the target
  26282. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26283. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26284. */
  26285. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26286. var animatables = this.getAllAnimatablesByTarget(target);
  26287. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26288. var animatable = animatables_1[_i];
  26289. animatable.stop(animationName, targetMask);
  26290. }
  26291. };
  26292. /**
  26293. * Stops and removes all animations that have been applied to the scene
  26294. */
  26295. Scene.prototype.stopAllAnimations = function () {
  26296. if (this._activeAnimatables) {
  26297. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26298. this._activeAnimatables[i].stop();
  26299. }
  26300. this._activeAnimatables = [];
  26301. }
  26302. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26303. var group = _a[_i];
  26304. group.stop();
  26305. }
  26306. };
  26307. Scene.prototype._animate = function () {
  26308. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26309. return;
  26310. }
  26311. // Getting time
  26312. var now = BABYLON.Tools.Now;
  26313. if (!this._animationTimeLast) {
  26314. if (this._pendingData.length > 0) {
  26315. return;
  26316. }
  26317. this._animationTimeLast = now;
  26318. }
  26319. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26320. this._animationTime += deltaTime;
  26321. this._animationTimeLast = now;
  26322. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26323. this._activeAnimatables[index]._animate(this._animationTime);
  26324. }
  26325. // Late animation bindings
  26326. this._processLateAnimationBindings();
  26327. };
  26328. /** @hidden */
  26329. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26330. var target = runtimeAnimation.target;
  26331. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26332. if (!target._lateAnimationHolders) {
  26333. target._lateAnimationHolders = {};
  26334. }
  26335. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26336. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26337. totalWeight: 0,
  26338. animations: [],
  26339. originalValue: originalValue
  26340. };
  26341. }
  26342. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26343. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26344. };
  26345. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26346. var normalizer = 1.0;
  26347. var finalPosition = BABYLON.Tmp.Vector3[0];
  26348. var finalScaling = BABYLON.Tmp.Vector3[1];
  26349. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26350. var startIndex = 0;
  26351. var originalAnimation = holder.animations[0];
  26352. var originalValue = holder.originalValue;
  26353. var scale = 1;
  26354. if (holder.totalWeight < 1.0) {
  26355. // We need to mix the original value in
  26356. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26357. scale = 1.0 - holder.totalWeight;
  26358. }
  26359. else {
  26360. startIndex = 1;
  26361. // We need to normalize the weights
  26362. normalizer = holder.totalWeight;
  26363. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26364. scale = originalAnimation.weight / normalizer;
  26365. if (scale == 1) {
  26366. return originalAnimation.currentValue;
  26367. }
  26368. }
  26369. finalScaling.scaleInPlace(scale);
  26370. finalPosition.scaleInPlace(scale);
  26371. finalQuaternion.scaleInPlace(scale);
  26372. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26373. var runtimeAnimation = holder.animations[animIndex];
  26374. var scale = runtimeAnimation.weight / normalizer;
  26375. var currentPosition = BABYLON.Tmp.Vector3[2];
  26376. var currentScaling = BABYLON.Tmp.Vector3[3];
  26377. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26378. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26379. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26380. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26381. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26382. }
  26383. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26384. return originalAnimation._workValue;
  26385. };
  26386. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26387. var originalAnimation = holder.animations[0];
  26388. var originalValue = holder.originalValue;
  26389. if (holder.animations.length === 1) {
  26390. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26391. return refQuaternion;
  26392. }
  26393. var normalizer = 1.0;
  26394. var quaternions;
  26395. var weights;
  26396. if (holder.totalWeight < 1.0) {
  26397. var scale = 1.0 - holder.totalWeight;
  26398. quaternions = [];
  26399. weights = [];
  26400. quaternions.push(originalValue);
  26401. weights.push(scale);
  26402. }
  26403. else {
  26404. if (holder.animations.length === 2) { // Slerp as soon as we can
  26405. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26406. return refQuaternion;
  26407. }
  26408. quaternions = [];
  26409. weights = [];
  26410. normalizer = holder.totalWeight;
  26411. }
  26412. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26413. var runtimeAnimation = holder.animations[animIndex];
  26414. quaternions.push(runtimeAnimation.currentValue);
  26415. weights.push(runtimeAnimation.weight / normalizer);
  26416. }
  26417. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26418. var cumulativeAmount = 0;
  26419. var cumulativeQuaternion = null;
  26420. for (var index = 0; index < quaternions.length;) {
  26421. if (!cumulativeQuaternion) {
  26422. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26423. cumulativeQuaternion = refQuaternion;
  26424. cumulativeAmount = weights[index] + weights[index + 1];
  26425. index += 2;
  26426. continue;
  26427. }
  26428. cumulativeAmount += weights[index];
  26429. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26430. index++;
  26431. }
  26432. return cumulativeQuaternion;
  26433. };
  26434. Scene.prototype._processLateAnimationBindings = function () {
  26435. if (!this._registeredForLateAnimationBindings.length) {
  26436. return;
  26437. }
  26438. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26439. var target = this._registeredForLateAnimationBindings.data[index];
  26440. for (var path in target._lateAnimationHolders) {
  26441. var holder = target._lateAnimationHolders[path];
  26442. var originalAnimation = holder.animations[0];
  26443. var originalValue = holder.originalValue;
  26444. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26445. var finalValue = target[path];
  26446. if (matrixDecomposeMode) {
  26447. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26448. }
  26449. else {
  26450. var quaternionMode = originalValue.w !== undefined;
  26451. if (quaternionMode) {
  26452. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26453. }
  26454. else {
  26455. var startIndex = 0;
  26456. var normalizer = 1.0;
  26457. if (holder.totalWeight < 1.0) {
  26458. // We need to mix the original value in
  26459. if (originalValue.scale) {
  26460. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26461. }
  26462. else {
  26463. finalValue = originalValue * (1.0 - holder.totalWeight);
  26464. }
  26465. }
  26466. else {
  26467. // We need to normalize the weights
  26468. normalizer = holder.totalWeight;
  26469. var scale_1 = originalAnimation.weight / normalizer;
  26470. if (scale_1 !== 1) {
  26471. if (originalAnimation.currentValue.scale) {
  26472. finalValue = originalAnimation.currentValue.scale(scale_1);
  26473. }
  26474. else {
  26475. finalValue = originalAnimation.currentValue * scale_1;
  26476. }
  26477. }
  26478. else {
  26479. finalValue = originalAnimation.currentValue;
  26480. }
  26481. startIndex = 1;
  26482. }
  26483. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26484. var runtimeAnimation = holder.animations[animIndex];
  26485. var scale = runtimeAnimation.weight / normalizer;
  26486. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26487. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26488. }
  26489. else {
  26490. finalValue += runtimeAnimation.currentValue * scale;
  26491. }
  26492. }
  26493. }
  26494. }
  26495. target[path] = finalValue;
  26496. }
  26497. target._lateAnimationHolders = {};
  26498. }
  26499. this._registeredForLateAnimationBindings.reset();
  26500. };
  26501. // Matrix
  26502. /** @hidden */
  26503. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26504. this._useAlternateCameraConfiguration = active;
  26505. };
  26506. /**
  26507. * Gets the current view matrix
  26508. * @returns a Matrix
  26509. */
  26510. Scene.prototype.getViewMatrix = function () {
  26511. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26512. };
  26513. /**
  26514. * Gets the current projection matrix
  26515. * @returns a Matrix
  26516. */
  26517. Scene.prototype.getProjectionMatrix = function () {
  26518. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26519. };
  26520. /**
  26521. * Gets the current transform matrix
  26522. * @returns a Matrix made of View * Projection
  26523. */
  26524. Scene.prototype.getTransformMatrix = function () {
  26525. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26526. };
  26527. /**
  26528. * Sets the current transform matrix
  26529. * @param view defines the View matrix to use
  26530. * @param projection defines the Projection matrix to use
  26531. */
  26532. Scene.prototype.setTransformMatrix = function (view, projection) {
  26533. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26534. return;
  26535. }
  26536. this._viewUpdateFlag = view.updateFlag;
  26537. this._projectionUpdateFlag = projection.updateFlag;
  26538. this._viewMatrix = view;
  26539. this._projectionMatrix = projection;
  26540. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26541. // Update frustum
  26542. if (!this._frustumPlanes) {
  26543. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26544. }
  26545. else {
  26546. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26547. }
  26548. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26549. var otherCamera = this.activeCamera._alternateCamera;
  26550. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26551. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26552. }
  26553. if (this._sceneUbo.useUbo) {
  26554. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26555. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26556. this._sceneUbo.update();
  26557. }
  26558. };
  26559. /** @hidden */
  26560. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26561. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26562. return;
  26563. }
  26564. this._alternateViewUpdateFlag = view.updateFlag;
  26565. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26566. this._alternateViewMatrix = view;
  26567. this._alternateProjectionMatrix = projection;
  26568. if (!this._alternateTransformMatrix) {
  26569. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26570. }
  26571. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26572. if (!this._alternateSceneUbo) {
  26573. this._createAlternateUbo();
  26574. }
  26575. if (this._alternateSceneUbo.useUbo) {
  26576. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26577. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26578. this._alternateSceneUbo.update();
  26579. }
  26580. };
  26581. /**
  26582. * Gets the uniform buffer used to store scene data
  26583. * @returns a UniformBuffer
  26584. */
  26585. Scene.prototype.getSceneUniformBuffer = function () {
  26586. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26587. };
  26588. /**
  26589. * Gets an unique (relatively to the current scene) Id
  26590. * @returns an unique number for the scene
  26591. */
  26592. Scene.prototype.getUniqueId = function () {
  26593. var result = Scene._uniqueIdCounter;
  26594. Scene._uniqueIdCounter++;
  26595. return result;
  26596. };
  26597. /**
  26598. * Add a mesh to the list of scene's meshes
  26599. * @param newMesh defines the mesh to add
  26600. * @param recursive if all child meshes should also be added to the scene
  26601. */
  26602. Scene.prototype.addMesh = function (newMesh, recursive) {
  26603. var _this = this;
  26604. if (recursive === void 0) { recursive = false; }
  26605. this.meshes.push(newMesh);
  26606. //notify the collision coordinator
  26607. if (this.collisionCoordinator) {
  26608. this.collisionCoordinator.onMeshAdded(newMesh);
  26609. }
  26610. newMesh._resyncLightSources();
  26611. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26612. if (recursive) {
  26613. newMesh.getChildMeshes().forEach(function (m) {
  26614. _this.addMesh(m);
  26615. });
  26616. }
  26617. };
  26618. /**
  26619. * Remove a mesh for the list of scene's meshes
  26620. * @param toRemove defines the mesh to remove
  26621. * @param recursive if all child meshes should also be removed from the scene
  26622. * @returns the index where the mesh was in the mesh list
  26623. */
  26624. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26625. var _this = this;
  26626. if (recursive === void 0) { recursive = false; }
  26627. var index = this.meshes.indexOf(toRemove);
  26628. if (index !== -1) {
  26629. // Remove from the scene if mesh found
  26630. this.meshes.splice(index, 1);
  26631. }
  26632. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26633. if (recursive) {
  26634. toRemove.getChildMeshes().forEach(function (m) {
  26635. _this.removeMesh(m);
  26636. });
  26637. }
  26638. return index;
  26639. };
  26640. /**
  26641. * Add a transform node to the list of scene's transform nodes
  26642. * @param newTransformNode defines the transform node to add
  26643. */
  26644. Scene.prototype.addTransformNode = function (newTransformNode) {
  26645. this.transformNodes.push(newTransformNode);
  26646. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26647. };
  26648. /**
  26649. * Remove a transform node for the list of scene's transform nodes
  26650. * @param toRemove defines the transform node to remove
  26651. * @returns the index where the transform node was in the transform node list
  26652. */
  26653. Scene.prototype.removeTransformNode = function (toRemove) {
  26654. var index = this.transformNodes.indexOf(toRemove);
  26655. if (index !== -1) {
  26656. // Remove from the scene if found
  26657. this.transformNodes.splice(index, 1);
  26658. }
  26659. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26660. return index;
  26661. };
  26662. /**
  26663. * Remove a skeleton for the list of scene's skeletons
  26664. * @param toRemove defines the skeleton to remove
  26665. * @returns the index where the skeleton was in the skeleton list
  26666. */
  26667. Scene.prototype.removeSkeleton = function (toRemove) {
  26668. var index = this.skeletons.indexOf(toRemove);
  26669. if (index !== -1) {
  26670. // Remove from the scene if found
  26671. this.skeletons.splice(index, 1);
  26672. }
  26673. return index;
  26674. };
  26675. /**
  26676. * Remove a morph target for the list of scene's morph targets
  26677. * @param toRemove defines the morph target to remove
  26678. * @returns the index where the morph target was in the morph target list
  26679. */
  26680. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26681. var index = this.morphTargetManagers.indexOf(toRemove);
  26682. if (index !== -1) {
  26683. // Remove from the scene if found
  26684. this.morphTargetManagers.splice(index, 1);
  26685. }
  26686. return index;
  26687. };
  26688. /**
  26689. * Remove a light for the list of scene's lights
  26690. * @param toRemove defines the light to remove
  26691. * @returns the index where the light was in the light list
  26692. */
  26693. Scene.prototype.removeLight = function (toRemove) {
  26694. var index = this.lights.indexOf(toRemove);
  26695. if (index !== -1) {
  26696. // Remove from meshes
  26697. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26698. var mesh = _a[_i];
  26699. mesh._removeLightSource(toRemove);
  26700. }
  26701. // Remove from the scene if mesh found
  26702. this.lights.splice(index, 1);
  26703. this.sortLightsByPriority();
  26704. }
  26705. this.onLightRemovedObservable.notifyObservers(toRemove);
  26706. return index;
  26707. };
  26708. /**
  26709. * Remove a camera for the list of scene's cameras
  26710. * @param toRemove defines the camera to remove
  26711. * @returns the index where the camera was in the camera list
  26712. */
  26713. Scene.prototype.removeCamera = function (toRemove) {
  26714. var index = this.cameras.indexOf(toRemove);
  26715. if (index !== -1) {
  26716. // Remove from the scene if mesh found
  26717. this.cameras.splice(index, 1);
  26718. }
  26719. // Remove from activeCameras
  26720. var index2 = this.activeCameras.indexOf(toRemove);
  26721. if (index2 !== -1) {
  26722. // Remove from the scene if mesh found
  26723. this.activeCameras.splice(index2, 1);
  26724. }
  26725. // Reset the activeCamera
  26726. if (this.activeCamera === toRemove) {
  26727. if (this.cameras.length > 0) {
  26728. this.activeCamera = this.cameras[0];
  26729. }
  26730. else {
  26731. this.activeCamera = null;
  26732. }
  26733. }
  26734. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26735. return index;
  26736. };
  26737. /**
  26738. * Remove a particle system for the list of scene's particle systems
  26739. * @param toRemove defines the particle system to remove
  26740. * @returns the index where the particle system was in the particle system list
  26741. */
  26742. Scene.prototype.removeParticleSystem = function (toRemove) {
  26743. var index = this.particleSystems.indexOf(toRemove);
  26744. if (index !== -1) {
  26745. this.particleSystems.splice(index, 1);
  26746. }
  26747. return index;
  26748. };
  26749. /**
  26750. * Remove a animation for the list of scene's animations
  26751. * @param toRemove defines the animation to remove
  26752. * @returns the index where the animation was in the animation list
  26753. */
  26754. Scene.prototype.removeAnimation = function (toRemove) {
  26755. var index = this.animations.indexOf(toRemove);
  26756. if (index !== -1) {
  26757. this.animations.splice(index, 1);
  26758. }
  26759. return index;
  26760. };
  26761. /**
  26762. * Removes the given animation group from this scene.
  26763. * @param toRemove The animation group to remove
  26764. * @returns The index of the removed animation group
  26765. */
  26766. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26767. var index = this.animationGroups.indexOf(toRemove);
  26768. if (index !== -1) {
  26769. this.animationGroups.splice(index, 1);
  26770. }
  26771. return index;
  26772. };
  26773. /**
  26774. * Removes the given multi-material from this scene.
  26775. * @param toRemove The multi-material to remove
  26776. * @returns The index of the removed multi-material
  26777. */
  26778. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26779. var index = this.multiMaterials.indexOf(toRemove);
  26780. if (index !== -1) {
  26781. this.multiMaterials.splice(index, 1);
  26782. }
  26783. return index;
  26784. };
  26785. /**
  26786. * Removes the given material from this scene.
  26787. * @param toRemove The material to remove
  26788. * @returns The index of the removed material
  26789. */
  26790. Scene.prototype.removeMaterial = function (toRemove) {
  26791. var index = this.materials.indexOf(toRemove);
  26792. if (index !== -1) {
  26793. this.materials.splice(index, 1);
  26794. }
  26795. return index;
  26796. };
  26797. /**
  26798. * Removes the given action manager from this scene.
  26799. * @param toRemove The action manager to remove
  26800. * @returns The index of the removed action manager
  26801. */
  26802. Scene.prototype.removeActionManager = function (toRemove) {
  26803. var index = this.actionManagers.indexOf(toRemove);
  26804. if (index !== -1) {
  26805. this.actionManagers.splice(index, 1);
  26806. }
  26807. return index;
  26808. };
  26809. /**
  26810. * Removes the given texture from this scene.
  26811. * @param toRemove The texture to remove
  26812. * @returns The index of the removed texture
  26813. */
  26814. Scene.prototype.removeTexture = function (toRemove) {
  26815. var index = this.textures.indexOf(toRemove);
  26816. if (index !== -1) {
  26817. this.textures.splice(index, 1);
  26818. }
  26819. return index;
  26820. };
  26821. /**
  26822. * Adds the given light to this scene
  26823. * @param newLight The light to add
  26824. */
  26825. Scene.prototype.addLight = function (newLight) {
  26826. this.lights.push(newLight);
  26827. this.sortLightsByPriority();
  26828. // Add light to all meshes (To support if the light is removed and then readded)
  26829. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26830. var mesh = _a[_i];
  26831. if (mesh._lightSources.indexOf(newLight) === -1) {
  26832. mesh._lightSources.push(newLight);
  26833. mesh._resyncLightSources();
  26834. }
  26835. }
  26836. this.onNewLightAddedObservable.notifyObservers(newLight);
  26837. };
  26838. /**
  26839. * Sorts the list list based on light priorities
  26840. */
  26841. Scene.prototype.sortLightsByPriority = function () {
  26842. if (this.requireLightSorting) {
  26843. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26844. }
  26845. };
  26846. /**
  26847. * Adds the given camera to this scene
  26848. * @param newCamera The camera to add
  26849. */
  26850. Scene.prototype.addCamera = function (newCamera) {
  26851. this.cameras.push(newCamera);
  26852. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26853. };
  26854. /**
  26855. * Adds the given skeleton to this scene
  26856. * @param newSkeleton The skeleton to add
  26857. */
  26858. Scene.prototype.addSkeleton = function (newSkeleton) {
  26859. this.skeletons.push(newSkeleton);
  26860. };
  26861. /**
  26862. * Adds the given particle system to this scene
  26863. * @param newParticleSystem The particle system to add
  26864. */
  26865. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26866. this.particleSystems.push(newParticleSystem);
  26867. };
  26868. /**
  26869. * Adds the given animation to this scene
  26870. * @param newAnimation The animation to add
  26871. */
  26872. Scene.prototype.addAnimation = function (newAnimation) {
  26873. this.animations.push(newAnimation);
  26874. };
  26875. /**
  26876. * Adds the given animation group to this scene.
  26877. * @param newAnimationGroup The animation group to add
  26878. */
  26879. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26880. this.animationGroups.push(newAnimationGroup);
  26881. };
  26882. /**
  26883. * Adds the given multi-material to this scene
  26884. * @param newMultiMaterial The multi-material to add
  26885. */
  26886. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26887. this.multiMaterials.push(newMultiMaterial);
  26888. };
  26889. /**
  26890. * Adds the given material to this scene
  26891. * @param newMaterial The material to add
  26892. */
  26893. Scene.prototype.addMaterial = function (newMaterial) {
  26894. this.materials.push(newMaterial);
  26895. };
  26896. /**
  26897. * Adds the given morph target to this scene
  26898. * @param newMorphTargetManager The morph target to add
  26899. */
  26900. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26901. this.morphTargetManagers.push(newMorphTargetManager);
  26902. };
  26903. /**
  26904. * Adds the given geometry to this scene
  26905. * @param newGeometry The geometry to add
  26906. */
  26907. Scene.prototype.addGeometry = function (newGeometry) {
  26908. this.geometries.push(newGeometry);
  26909. };
  26910. /**
  26911. * Adds the given action manager to this scene
  26912. * @param newActionManager The action manager to add
  26913. */
  26914. Scene.prototype.addActionManager = function (newActionManager) {
  26915. this.actionManagers.push(newActionManager);
  26916. };
  26917. /**
  26918. * Adds the given texture to this scene.
  26919. * @param newTexture The texture to add
  26920. */
  26921. Scene.prototype.addTexture = function (newTexture) {
  26922. this.textures.push(newTexture);
  26923. };
  26924. /**
  26925. * Switch active camera
  26926. * @param newCamera defines the new active camera
  26927. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26928. */
  26929. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26930. if (attachControl === void 0) { attachControl = true; }
  26931. var canvas = this._engine.getRenderingCanvas();
  26932. if (!canvas) {
  26933. return;
  26934. }
  26935. if (this.activeCamera) {
  26936. this.activeCamera.detachControl(canvas);
  26937. }
  26938. this.activeCamera = newCamera;
  26939. if (attachControl) {
  26940. newCamera.attachControl(canvas);
  26941. }
  26942. };
  26943. /**
  26944. * sets the active camera of the scene using its ID
  26945. * @param id defines the camera's ID
  26946. * @return the new active camera or null if none found.
  26947. */
  26948. Scene.prototype.setActiveCameraByID = function (id) {
  26949. var camera = this.getCameraByID(id);
  26950. if (camera) {
  26951. this.activeCamera = camera;
  26952. return camera;
  26953. }
  26954. return null;
  26955. };
  26956. /**
  26957. * sets the active camera of the scene using its name
  26958. * @param name defines the camera's name
  26959. * @returns the new active camera or null if none found.
  26960. */
  26961. Scene.prototype.setActiveCameraByName = function (name) {
  26962. var camera = this.getCameraByName(name);
  26963. if (camera) {
  26964. this.activeCamera = camera;
  26965. return camera;
  26966. }
  26967. return null;
  26968. };
  26969. /**
  26970. * get an animation group using its name
  26971. * @param name defines the material's name
  26972. * @return the animation group or null if none found.
  26973. */
  26974. Scene.prototype.getAnimationGroupByName = function (name) {
  26975. for (var index = 0; index < this.animationGroups.length; index++) {
  26976. if (this.animationGroups[index].name === name) {
  26977. return this.animationGroups[index];
  26978. }
  26979. }
  26980. return null;
  26981. };
  26982. /**
  26983. * get a material using its id
  26984. * @param id defines the material's ID
  26985. * @return the material or null if none found.
  26986. */
  26987. Scene.prototype.getMaterialByID = function (id) {
  26988. for (var index = 0; index < this.materials.length; index++) {
  26989. if (this.materials[index].id === id) {
  26990. return this.materials[index];
  26991. }
  26992. }
  26993. return null;
  26994. };
  26995. /**
  26996. * Gets a material using its name
  26997. * @param name defines the material's name
  26998. * @return the material or null if none found.
  26999. */
  27000. Scene.prototype.getMaterialByName = function (name) {
  27001. for (var index = 0; index < this.materials.length; index++) {
  27002. if (this.materials[index].name === name) {
  27003. return this.materials[index];
  27004. }
  27005. }
  27006. return null;
  27007. };
  27008. /**
  27009. * Gets a camera using its id
  27010. * @param id defines the id to look for
  27011. * @returns the camera or null if not found
  27012. */
  27013. Scene.prototype.getCameraByID = function (id) {
  27014. for (var index = 0; index < this.cameras.length; index++) {
  27015. if (this.cameras[index].id === id) {
  27016. return this.cameras[index];
  27017. }
  27018. }
  27019. return null;
  27020. };
  27021. /**
  27022. * Gets a camera using its unique id
  27023. * @param uniqueId defines the unique id to look for
  27024. * @returns the camera or null if not found
  27025. */
  27026. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27027. for (var index = 0; index < this.cameras.length; index++) {
  27028. if (this.cameras[index].uniqueId === uniqueId) {
  27029. return this.cameras[index];
  27030. }
  27031. }
  27032. return null;
  27033. };
  27034. /**
  27035. * Gets a camera using its name
  27036. * @param name defines the camera's name
  27037. * @return the camera or null if none found.
  27038. */
  27039. Scene.prototype.getCameraByName = function (name) {
  27040. for (var index = 0; index < this.cameras.length; index++) {
  27041. if (this.cameras[index].name === name) {
  27042. return this.cameras[index];
  27043. }
  27044. }
  27045. return null;
  27046. };
  27047. /**
  27048. * Gets a bone using its id
  27049. * @param id defines the bone's id
  27050. * @return the bone or null if not found
  27051. */
  27052. Scene.prototype.getBoneByID = function (id) {
  27053. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27054. var skeleton = this.skeletons[skeletonIndex];
  27055. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27056. if (skeleton.bones[boneIndex].id === id) {
  27057. return skeleton.bones[boneIndex];
  27058. }
  27059. }
  27060. }
  27061. return null;
  27062. };
  27063. /**
  27064. * Gets a bone using its id
  27065. * @param name defines the bone's name
  27066. * @return the bone or null if not found
  27067. */
  27068. Scene.prototype.getBoneByName = function (name) {
  27069. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27070. var skeleton = this.skeletons[skeletonIndex];
  27071. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27072. if (skeleton.bones[boneIndex].name === name) {
  27073. return skeleton.bones[boneIndex];
  27074. }
  27075. }
  27076. }
  27077. return null;
  27078. };
  27079. /**
  27080. * Gets a light node using its name
  27081. * @param name defines the the light's name
  27082. * @return the light or null if none found.
  27083. */
  27084. Scene.prototype.getLightByName = function (name) {
  27085. for (var index = 0; index < this.lights.length; index++) {
  27086. if (this.lights[index].name === name) {
  27087. return this.lights[index];
  27088. }
  27089. }
  27090. return null;
  27091. };
  27092. /**
  27093. * Gets a light node using its id
  27094. * @param id defines the light's id
  27095. * @return the light or null if none found.
  27096. */
  27097. Scene.prototype.getLightByID = function (id) {
  27098. for (var index = 0; index < this.lights.length; index++) {
  27099. if (this.lights[index].id === id) {
  27100. return this.lights[index];
  27101. }
  27102. }
  27103. return null;
  27104. };
  27105. /**
  27106. * Gets a light node using its scene-generated unique ID
  27107. * @param uniqueId defines the light's unique id
  27108. * @return the light or null if none found.
  27109. */
  27110. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27111. for (var index = 0; index < this.lights.length; index++) {
  27112. if (this.lights[index].uniqueId === uniqueId) {
  27113. return this.lights[index];
  27114. }
  27115. }
  27116. return null;
  27117. };
  27118. /**
  27119. * Gets a particle system by id
  27120. * @param id defines the particle system id
  27121. * @return the corresponding system or null if none found
  27122. */
  27123. Scene.prototype.getParticleSystemByID = function (id) {
  27124. for (var index = 0; index < this.particleSystems.length; index++) {
  27125. if (this.particleSystems[index].id === id) {
  27126. return this.particleSystems[index];
  27127. }
  27128. }
  27129. return null;
  27130. };
  27131. /**
  27132. * Gets a geometry using its ID
  27133. * @param id defines the geometry's id
  27134. * @return the geometry or null if none found.
  27135. */
  27136. Scene.prototype.getGeometryByID = function (id) {
  27137. for (var index = 0; index < this.geometries.length; index++) {
  27138. if (this.geometries[index].id === id) {
  27139. return this.geometries[index];
  27140. }
  27141. }
  27142. return null;
  27143. };
  27144. /**
  27145. * Add a new geometry to this scene
  27146. * @param geometry defines the geometry to be added to the scene.
  27147. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27148. * @return a boolean defining if the geometry was added or not
  27149. */
  27150. Scene.prototype.pushGeometry = function (geometry, force) {
  27151. if (!force && this.getGeometryByID(geometry.id)) {
  27152. return false;
  27153. }
  27154. this.geometries.push(geometry);
  27155. //notify the collision coordinator
  27156. if (this.collisionCoordinator) {
  27157. this.collisionCoordinator.onGeometryAdded(geometry);
  27158. }
  27159. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27160. return true;
  27161. };
  27162. /**
  27163. * Removes an existing geometry
  27164. * @param geometry defines the geometry to be removed from the scene
  27165. * @return a boolean defining if the geometry was removed or not
  27166. */
  27167. Scene.prototype.removeGeometry = function (geometry) {
  27168. var index = this.geometries.indexOf(geometry);
  27169. if (index > -1) {
  27170. this.geometries.splice(index, 1);
  27171. //notify the collision coordinator
  27172. if (this.collisionCoordinator) {
  27173. this.collisionCoordinator.onGeometryDeleted(geometry);
  27174. }
  27175. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27176. return true;
  27177. }
  27178. return false;
  27179. };
  27180. /**
  27181. * Gets the list of geometries attached to the scene
  27182. * @returns an array of Geometry
  27183. */
  27184. Scene.prototype.getGeometries = function () {
  27185. return this.geometries;
  27186. };
  27187. /**
  27188. * Gets the first added mesh found of a given ID
  27189. * @param id defines the id to search for
  27190. * @return the mesh found or null if not found at all
  27191. */
  27192. Scene.prototype.getMeshByID = function (id) {
  27193. for (var index = 0; index < this.meshes.length; index++) {
  27194. if (this.meshes[index].id === id) {
  27195. return this.meshes[index];
  27196. }
  27197. }
  27198. return null;
  27199. };
  27200. /**
  27201. * Gets a list of meshes using their id
  27202. * @param id defines the id to search for
  27203. * @returns a list of meshes
  27204. */
  27205. Scene.prototype.getMeshesByID = function (id) {
  27206. return this.meshes.filter(function (m) {
  27207. return m.id === id;
  27208. });
  27209. };
  27210. /**
  27211. * Gets the first added transform node found of a given ID
  27212. * @param id defines the id to search for
  27213. * @return the found transform node or null if not found at all.
  27214. */
  27215. Scene.prototype.getTransformNodeByID = function (id) {
  27216. for (var index = 0; index < this.transformNodes.length; index++) {
  27217. if (this.transformNodes[index].id === id) {
  27218. return this.transformNodes[index];
  27219. }
  27220. }
  27221. return null;
  27222. };
  27223. /**
  27224. * Gets a list of transform nodes using their id
  27225. * @param id defines the id to search for
  27226. * @returns a list of transform nodes
  27227. */
  27228. Scene.prototype.getTransformNodesByID = function (id) {
  27229. return this.transformNodes.filter(function (m) {
  27230. return m.id === id;
  27231. });
  27232. };
  27233. /**
  27234. * Gets a mesh with its auto-generated unique id
  27235. * @param uniqueId defines the unique id to search for
  27236. * @return the found mesh or null if not found at all.
  27237. */
  27238. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27239. for (var index = 0; index < this.meshes.length; index++) {
  27240. if (this.meshes[index].uniqueId === uniqueId) {
  27241. return this.meshes[index];
  27242. }
  27243. }
  27244. return null;
  27245. };
  27246. /**
  27247. * Gets a the last added mesh using a given id
  27248. * @param id defines the id to search for
  27249. * @return the found mesh or null if not found at all.
  27250. */
  27251. Scene.prototype.getLastMeshByID = function (id) {
  27252. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27253. if (this.meshes[index].id === id) {
  27254. return this.meshes[index];
  27255. }
  27256. }
  27257. return null;
  27258. };
  27259. /**
  27260. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27261. * @param id defines the id to search for
  27262. * @return the found node or null if not found at all
  27263. */
  27264. Scene.prototype.getLastEntryByID = function (id) {
  27265. var index;
  27266. for (index = this.meshes.length - 1; index >= 0; index--) {
  27267. if (this.meshes[index].id === id) {
  27268. return this.meshes[index];
  27269. }
  27270. }
  27271. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27272. if (this.transformNodes[index].id === id) {
  27273. return this.transformNodes[index];
  27274. }
  27275. }
  27276. for (index = this.cameras.length - 1; index >= 0; index--) {
  27277. if (this.cameras[index].id === id) {
  27278. return this.cameras[index];
  27279. }
  27280. }
  27281. for (index = this.lights.length - 1; index >= 0; index--) {
  27282. if (this.lights[index].id === id) {
  27283. return this.lights[index];
  27284. }
  27285. }
  27286. return null;
  27287. };
  27288. /**
  27289. * Gets a node (Mesh, Camera, Light) using a given id
  27290. * @param id defines the id to search for
  27291. * @return the found node or null if not found at all
  27292. */
  27293. Scene.prototype.getNodeByID = function (id) {
  27294. var mesh = this.getMeshByID(id);
  27295. if (mesh) {
  27296. return mesh;
  27297. }
  27298. var light = this.getLightByID(id);
  27299. if (light) {
  27300. return light;
  27301. }
  27302. var camera = this.getCameraByID(id);
  27303. if (camera) {
  27304. return camera;
  27305. }
  27306. var bone = this.getBoneByID(id);
  27307. return bone;
  27308. };
  27309. /**
  27310. * Gets a node (Mesh, Camera, Light) using a given name
  27311. * @param name defines the name to search for
  27312. * @return the found node or null if not found at all.
  27313. */
  27314. Scene.prototype.getNodeByName = function (name) {
  27315. var mesh = this.getMeshByName(name);
  27316. if (mesh) {
  27317. return mesh;
  27318. }
  27319. var light = this.getLightByName(name);
  27320. if (light) {
  27321. return light;
  27322. }
  27323. var camera = this.getCameraByName(name);
  27324. if (camera) {
  27325. return camera;
  27326. }
  27327. var bone = this.getBoneByName(name);
  27328. return bone;
  27329. };
  27330. /**
  27331. * Gets a mesh using a given name
  27332. * @param name defines the name to search for
  27333. * @return the found mesh or null if not found at all.
  27334. */
  27335. Scene.prototype.getMeshByName = function (name) {
  27336. for (var index = 0; index < this.meshes.length; index++) {
  27337. if (this.meshes[index].name === name) {
  27338. return this.meshes[index];
  27339. }
  27340. }
  27341. return null;
  27342. };
  27343. /**
  27344. * Gets a transform node using a given name
  27345. * @param name defines the name to search for
  27346. * @return the found transform node or null if not found at all.
  27347. */
  27348. Scene.prototype.getTransformNodeByName = function (name) {
  27349. for (var index = 0; index < this.transformNodes.length; index++) {
  27350. if (this.transformNodes[index].name === name) {
  27351. return this.transformNodes[index];
  27352. }
  27353. }
  27354. return null;
  27355. };
  27356. /**
  27357. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27358. * @param id defines the id to search for
  27359. * @return the found skeleton or null if not found at all.
  27360. */
  27361. Scene.prototype.getLastSkeletonByID = function (id) {
  27362. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27363. if (this.skeletons[index].id === id) {
  27364. return this.skeletons[index];
  27365. }
  27366. }
  27367. return null;
  27368. };
  27369. /**
  27370. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27371. * @param id defines the id to search for
  27372. * @return the found skeleton or null if not found at all.
  27373. */
  27374. Scene.prototype.getSkeletonById = function (id) {
  27375. for (var index = 0; index < this.skeletons.length; index++) {
  27376. if (this.skeletons[index].id === id) {
  27377. return this.skeletons[index];
  27378. }
  27379. }
  27380. return null;
  27381. };
  27382. /**
  27383. * Gets a skeleton using a given name
  27384. * @param name defines the name to search for
  27385. * @return the found skeleton or null if not found at all.
  27386. */
  27387. Scene.prototype.getSkeletonByName = function (name) {
  27388. for (var index = 0; index < this.skeletons.length; index++) {
  27389. if (this.skeletons[index].name === name) {
  27390. return this.skeletons[index];
  27391. }
  27392. }
  27393. return null;
  27394. };
  27395. /**
  27396. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27397. * @param id defines the id to search for
  27398. * @return the found morph target manager or null if not found at all.
  27399. */
  27400. Scene.prototype.getMorphTargetManagerById = function (id) {
  27401. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27402. if (this.morphTargetManagers[index].uniqueId === id) {
  27403. return this.morphTargetManagers[index];
  27404. }
  27405. }
  27406. return null;
  27407. };
  27408. /**
  27409. * Gets a boolean indicating if the given mesh is active
  27410. * @param mesh defines the mesh to look for
  27411. * @returns true if the mesh is in the active list
  27412. */
  27413. Scene.prototype.isActiveMesh = function (mesh) {
  27414. return (this._activeMeshes.indexOf(mesh) !== -1);
  27415. };
  27416. Object.defineProperty(Scene.prototype, "uid", {
  27417. /**
  27418. * Return a unique id as a string which can serve as an identifier for the scene
  27419. */
  27420. get: function () {
  27421. if (!this._uid) {
  27422. this._uid = BABYLON.Tools.RandomId();
  27423. }
  27424. return this._uid;
  27425. },
  27426. enumerable: true,
  27427. configurable: true
  27428. });
  27429. /**
  27430. * Add an externaly attached data from its key.
  27431. * This method call will fail and return false, if such key already exists.
  27432. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27433. * @param key the unique key that identifies the data
  27434. * @param data the data object to associate to the key for this Engine instance
  27435. * @return true if no such key were already present and the data was added successfully, false otherwise
  27436. */
  27437. Scene.prototype.addExternalData = function (key, data) {
  27438. if (!this._externalData) {
  27439. this._externalData = new BABYLON.StringDictionary();
  27440. }
  27441. return this._externalData.add(key, data);
  27442. };
  27443. /**
  27444. * Get an externaly attached data from its key
  27445. * @param key the unique key that identifies the data
  27446. * @return the associated data, if present (can be null), or undefined if not present
  27447. */
  27448. Scene.prototype.getExternalData = function (key) {
  27449. if (!this._externalData) {
  27450. return null;
  27451. }
  27452. return this._externalData.get(key);
  27453. };
  27454. /**
  27455. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27456. * @param key the unique key that identifies the data
  27457. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27458. * @return the associated data, can be null if the factory returned null.
  27459. */
  27460. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27461. if (!this._externalData) {
  27462. this._externalData = new BABYLON.StringDictionary();
  27463. }
  27464. return this._externalData.getOrAddWithFactory(key, factory);
  27465. };
  27466. /**
  27467. * Remove an externaly attached data from the Engine instance
  27468. * @param key the unique key that identifies the data
  27469. * @return true if the data was successfully removed, false if it doesn't exist
  27470. */
  27471. Scene.prototype.removeExternalData = function (key) {
  27472. return this._externalData.remove(key);
  27473. };
  27474. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27475. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27476. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27477. var step = _a[_i];
  27478. step.action(mesh, subMesh);
  27479. }
  27480. var material = subMesh.getMaterial();
  27481. if (material !== null && material !== undefined) {
  27482. // Render targets
  27483. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27484. if (this._processedMaterials.indexOf(material) === -1) {
  27485. this._processedMaterials.push(material);
  27486. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27487. }
  27488. }
  27489. // Dispatch
  27490. this._activeIndices.addCount(subMesh.indexCount, false);
  27491. this._renderingManager.dispatch(subMesh, mesh, material);
  27492. }
  27493. }
  27494. };
  27495. /**
  27496. * Clear the processed materials smart array preventing retention point in material dispose.
  27497. */
  27498. Scene.prototype.freeProcessedMaterials = function () {
  27499. this._processedMaterials.dispose();
  27500. };
  27501. /**
  27502. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27503. */
  27504. Scene.prototype.freeActiveMeshes = function () {
  27505. this._activeMeshes.dispose();
  27506. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27507. this.activeCamera._activeMeshes.dispose();
  27508. }
  27509. if (this.activeCameras) {
  27510. for (var i = 0; i < this.activeCameras.length; i++) {
  27511. var activeCamera = this.activeCameras[i];
  27512. if (activeCamera && activeCamera._activeMeshes) {
  27513. activeCamera._activeMeshes.dispose();
  27514. }
  27515. }
  27516. }
  27517. };
  27518. /**
  27519. * Clear the info related to rendering groups preventing retention points during dispose.
  27520. */
  27521. Scene.prototype.freeRenderingGroups = function () {
  27522. if (this._renderingManager) {
  27523. this._renderingManager.freeRenderingGroups();
  27524. }
  27525. if (this.textures) {
  27526. for (var i = 0; i < this.textures.length; i++) {
  27527. var texture = this.textures[i];
  27528. if (texture && texture.renderList) {
  27529. texture.freeRenderingGroups();
  27530. }
  27531. }
  27532. }
  27533. };
  27534. /** @hidden */
  27535. Scene.prototype._isInIntermediateRendering = function () {
  27536. return this._intermediateRendering;
  27537. };
  27538. /**
  27539. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27540. * @returns the current scene
  27541. */
  27542. Scene.prototype.freezeActiveMeshes = function () {
  27543. if (!this.activeCamera) {
  27544. return this;
  27545. }
  27546. if (!this._frustumPlanes) {
  27547. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27548. }
  27549. this._evaluateActiveMeshes();
  27550. this._activeMeshesFrozen = true;
  27551. return this;
  27552. };
  27553. /**
  27554. * Use this function to restart evaluating active meshes on every frame
  27555. * @returns the current scene
  27556. */
  27557. Scene.prototype.unfreezeActiveMeshes = function () {
  27558. this._activeMeshesFrozen = false;
  27559. return this;
  27560. };
  27561. Scene.prototype._evaluateActiveMeshes = function () {
  27562. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27563. return;
  27564. }
  27565. if (!this.activeCamera) {
  27566. return;
  27567. }
  27568. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27569. this.activeCamera._activeMeshes.reset();
  27570. this._activeMeshes.reset();
  27571. this._renderingManager.reset();
  27572. this._processedMaterials.reset();
  27573. this._activeParticleSystems.reset();
  27574. this._activeSkeletons.reset();
  27575. this._softwareSkinnedMeshes.reset();
  27576. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27577. var step = _a[_i];
  27578. step.action();
  27579. }
  27580. // Determine mesh candidates
  27581. var meshes = this.getActiveMeshCandidates();
  27582. // Check each mesh
  27583. var len = meshes.length;
  27584. for (var i = 0; i < len; i++) {
  27585. var mesh = meshes.data[i];
  27586. if (mesh.isBlocked) {
  27587. continue;
  27588. }
  27589. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27590. if (!mesh.isReady() || !mesh.isEnabled()) {
  27591. continue;
  27592. }
  27593. mesh.computeWorldMatrix();
  27594. // Intersections
  27595. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27596. this._meshesForIntersections.pushNoDuplicate(mesh);
  27597. }
  27598. // Switch to current LOD
  27599. var meshLOD = mesh.getLOD(this.activeCamera);
  27600. if (meshLOD === undefined || meshLOD === null) {
  27601. continue;
  27602. }
  27603. mesh._preActivate();
  27604. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27605. this._activeMeshes.push(mesh);
  27606. this.activeCamera._activeMeshes.push(mesh);
  27607. mesh._activate(this._renderId);
  27608. if (meshLOD !== mesh) {
  27609. meshLOD._activate(this._renderId);
  27610. }
  27611. this._activeMesh(mesh, meshLOD);
  27612. }
  27613. }
  27614. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27615. // Particle systems
  27616. if (this.particlesEnabled) {
  27617. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27618. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27619. var particleSystem = this.particleSystems[particleIndex];
  27620. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27621. continue;
  27622. }
  27623. var emitter = particleSystem.emitter;
  27624. if (!emitter.position || emitter.isEnabled()) {
  27625. this._activeParticleSystems.push(particleSystem);
  27626. particleSystem.animate();
  27627. this._renderingManager.dispatchParticles(particleSystem);
  27628. }
  27629. }
  27630. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27631. }
  27632. };
  27633. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27634. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27635. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27636. mesh.skeleton.prepare();
  27637. }
  27638. if (!mesh.computeBonesUsingShaders) {
  27639. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27640. }
  27641. }
  27642. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27643. var step = _a[_i];
  27644. step.action(sourceMesh, mesh);
  27645. }
  27646. if (mesh !== undefined && mesh !== null
  27647. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27648. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27649. var len = subMeshes.length;
  27650. for (var i = 0; i < len; i++) {
  27651. var subMesh = subMeshes.data[i];
  27652. this._evaluateSubMesh(subMesh, mesh);
  27653. }
  27654. }
  27655. };
  27656. /**
  27657. * Update the transform matrix to update from the current active camera
  27658. * @param force defines a boolean used to force the update even if cache is up to date
  27659. */
  27660. Scene.prototype.updateTransformMatrix = function (force) {
  27661. if (!this.activeCamera) {
  27662. return;
  27663. }
  27664. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27665. };
  27666. /**
  27667. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27668. * @param alternateCamera defines the camera to use
  27669. */
  27670. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27671. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27672. };
  27673. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27674. if (camera && camera._skipRendering) {
  27675. return;
  27676. }
  27677. var engine = this._engine;
  27678. this.activeCamera = camera;
  27679. if (!this.activeCamera)
  27680. throw new Error("Active camera not set");
  27681. // Viewport
  27682. engine.setViewport(this.activeCamera.viewport);
  27683. // Camera
  27684. this.resetCachedMaterial();
  27685. this._renderId++;
  27686. this.updateTransformMatrix();
  27687. if (camera._alternateCamera) {
  27688. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27689. this._alternateRendering = true;
  27690. }
  27691. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27692. // Meshes
  27693. this._evaluateActiveMeshes();
  27694. // Software skinning
  27695. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27696. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27697. mesh.applySkeleton(mesh.skeleton);
  27698. }
  27699. // Render targets
  27700. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27701. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27702. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27703. }
  27704. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27705. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27706. }
  27707. // Collects render targets from external components.
  27708. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27709. var step = _a[_i];
  27710. step.action(this._renderTargets);
  27711. }
  27712. if (this.renderTargetsEnabled) {
  27713. this._intermediateRendering = true;
  27714. if (this._renderTargets.length > 0) {
  27715. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27716. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27717. var renderTarget = this._renderTargets.data[renderIndex];
  27718. if (renderTarget._shouldRender()) {
  27719. this._renderId++;
  27720. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27721. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27722. }
  27723. }
  27724. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27725. this._renderId++;
  27726. }
  27727. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27728. var step = _c[_b];
  27729. step.action(this.activeCamera);
  27730. }
  27731. this._intermediateRendering = false;
  27732. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27733. }
  27734. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27735. // Prepare Frame
  27736. if (this.postProcessManager) {
  27737. this.postProcessManager._prepareFrame();
  27738. }
  27739. // Before Camera Draw
  27740. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27741. var step = _e[_d];
  27742. step.action(this.activeCamera);
  27743. }
  27744. // Render
  27745. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27746. this._renderingManager.render(null, null, true, true);
  27747. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27748. // After Camera Draw
  27749. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27750. var step = _g[_f];
  27751. step.action(this.activeCamera);
  27752. }
  27753. // Finalize frame
  27754. if (this.postProcessManager) {
  27755. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27756. }
  27757. // Reset some special arrays
  27758. this._renderTargets.reset();
  27759. this._alternateRendering = false;
  27760. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27761. };
  27762. Scene.prototype._processSubCameras = function (camera) {
  27763. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27764. this._renderForCamera(camera);
  27765. return;
  27766. }
  27767. // rig cameras
  27768. for (var index = 0; index < camera._rigCameras.length; index++) {
  27769. this._renderForCamera(camera._rigCameras[index], camera);
  27770. }
  27771. this.activeCamera = camera;
  27772. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27773. };
  27774. Scene.prototype._checkIntersections = function () {
  27775. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27776. var sourceMesh = this._meshesForIntersections.data[index];
  27777. if (!sourceMesh.actionManager) {
  27778. continue;
  27779. }
  27780. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27781. var action = sourceMesh.actionManager.actions[actionIndex];
  27782. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27783. var parameters = action.getTriggerParameter();
  27784. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27785. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27786. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27787. if (areIntersecting && currentIntersectionInProgress === -1) {
  27788. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27789. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27790. sourceMesh._intersectionsInProgress.push(otherMesh);
  27791. }
  27792. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27793. sourceMesh._intersectionsInProgress.push(otherMesh);
  27794. }
  27795. }
  27796. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27797. //They intersected, and now they don't.
  27798. //is this trigger an exit trigger? execute an event.
  27799. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27800. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27801. }
  27802. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27803. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27804. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27805. return otherMesh === parameterMesh;
  27806. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27807. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27808. }
  27809. }
  27810. }
  27811. }
  27812. }
  27813. };
  27814. /** @hidden */
  27815. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27816. // Do nothing. Code will be replaced if physics engine component is referenced
  27817. };
  27818. /**
  27819. * Render the scene
  27820. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27821. */
  27822. Scene.prototype.render = function (updateCameras) {
  27823. if (updateCameras === void 0) { updateCameras = true; }
  27824. if (this.isDisposed) {
  27825. return;
  27826. }
  27827. this._frameId++;
  27828. // Register components that have been associated lately to the scene.
  27829. this._registerTransientComponents();
  27830. this._activeParticles.fetchNewFrame();
  27831. this._totalVertices.fetchNewFrame();
  27832. this._activeIndices.fetchNewFrame();
  27833. this._activeBones.fetchNewFrame();
  27834. this._meshesForIntersections.reset();
  27835. this.resetCachedMaterial();
  27836. this.onBeforeAnimationsObservable.notifyObservers(this);
  27837. // Actions
  27838. if (this.actionManager) {
  27839. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27840. }
  27841. if (this._engine.isDeterministicLockStep()) {
  27842. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27843. var defaultFPS = (60.0 / 1000.0);
  27844. var defaultFrameTime = this.getDeterministicFrameTime();
  27845. var stepsTaken = 0;
  27846. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27847. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27848. internalSteps = Math.min(internalSteps, maxSubSteps);
  27849. do {
  27850. this.onBeforeStepObservable.notifyObservers(this);
  27851. // Animations
  27852. this._animationRatio = defaultFrameTime * defaultFPS;
  27853. this._animate();
  27854. this.onAfterAnimationsObservable.notifyObservers(this);
  27855. // Physics
  27856. this._advancePhysicsEngineStep(defaultFrameTime);
  27857. this.onAfterStepObservable.notifyObservers(this);
  27858. this._currentStepId++;
  27859. stepsTaken++;
  27860. deltaTime -= defaultFrameTime;
  27861. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27862. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27863. }
  27864. else {
  27865. // Animations
  27866. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27867. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27868. this._animate();
  27869. this.onAfterAnimationsObservable.notifyObservers(this);
  27870. // Physics
  27871. this._advancePhysicsEngineStep(deltaTime);
  27872. }
  27873. // Before camera update steps
  27874. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27875. var step = _a[_i];
  27876. step.action();
  27877. }
  27878. // Update Cameras
  27879. if (updateCameras) {
  27880. if (this.activeCameras.length > 0) {
  27881. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27882. var camera = this.activeCameras[cameraIndex];
  27883. camera.update();
  27884. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27885. // rig cameras
  27886. for (var index = 0; index < camera._rigCameras.length; index++) {
  27887. camera._rigCameras[index].update();
  27888. }
  27889. }
  27890. }
  27891. }
  27892. else if (this.activeCamera) {
  27893. this.activeCamera.update();
  27894. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27895. // rig cameras
  27896. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27897. this.activeCamera._rigCameras[index].update();
  27898. }
  27899. }
  27900. }
  27901. }
  27902. // Before render
  27903. this.onBeforeRenderObservable.notifyObservers(this);
  27904. // Customs render targets
  27905. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27906. var engine = this.getEngine();
  27907. var currentActiveCamera = this.activeCamera;
  27908. if (this.renderTargetsEnabled) {
  27909. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27910. this._intermediateRendering = true;
  27911. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27912. var renderTarget = this.customRenderTargets[customIndex];
  27913. if (renderTarget._shouldRender()) {
  27914. this._renderId++;
  27915. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27916. if (!this.activeCamera)
  27917. throw new Error("Active camera not set");
  27918. // Viewport
  27919. engine.setViewport(this.activeCamera.viewport);
  27920. // Camera
  27921. this.updateTransformMatrix();
  27922. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27923. }
  27924. }
  27925. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27926. this._intermediateRendering = false;
  27927. this._renderId++;
  27928. }
  27929. // Restore back buffer
  27930. if (this.customRenderTargets.length > 0) {
  27931. engine.restoreDefaultFramebuffer();
  27932. }
  27933. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27934. this.activeCamera = currentActiveCamera;
  27935. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27936. var step = _c[_b];
  27937. step.action();
  27938. }
  27939. // Clear
  27940. if (this.autoClearDepthAndStencil || this.autoClear) {
  27941. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27942. }
  27943. // Collects render targets from external components.
  27944. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27945. var step = _e[_d];
  27946. step.action(this._renderTargets);
  27947. }
  27948. // Multi-cameras?
  27949. if (this.activeCameras.length > 0) {
  27950. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27951. if (cameraIndex > 0) {
  27952. this._engine.clear(null, false, true, true);
  27953. }
  27954. this._processSubCameras(this.activeCameras[cameraIndex]);
  27955. }
  27956. }
  27957. else {
  27958. if (!this.activeCamera) {
  27959. throw new Error("No camera defined");
  27960. }
  27961. this._processSubCameras(this.activeCamera);
  27962. }
  27963. // Intersection checks
  27964. this._checkIntersections();
  27965. // Executes the after render stage actions.
  27966. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  27967. var step = _g[_f];
  27968. step.action();
  27969. }
  27970. // After render
  27971. if (this.afterRender) {
  27972. this.afterRender();
  27973. }
  27974. this.onAfterRenderObservable.notifyObservers(this);
  27975. // Cleaning
  27976. if (this._toBeDisposed.length) {
  27977. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27978. var data = this._toBeDisposed[index];
  27979. if (data) {
  27980. data.dispose();
  27981. }
  27982. }
  27983. this._toBeDisposed = [];
  27984. }
  27985. if (this.dumpNextRenderTargets) {
  27986. this.dumpNextRenderTargets = false;
  27987. }
  27988. this._activeBones.addCount(0, true);
  27989. this._activeIndices.addCount(0, true);
  27990. this._activeParticles.addCount(0, true);
  27991. };
  27992. /**
  27993. * Freeze all materials
  27994. * A frozen material will not be updatable but should be faster to render
  27995. */
  27996. Scene.prototype.freezeMaterials = function () {
  27997. for (var i = 0; i < this.materials.length; i++) {
  27998. this.materials[i].freeze();
  27999. }
  28000. };
  28001. /**
  28002. * Unfreeze all materials
  28003. * A frozen material will not be updatable but should be faster to render
  28004. */
  28005. Scene.prototype.unfreezeMaterials = function () {
  28006. for (var i = 0; i < this.materials.length; i++) {
  28007. this.materials[i].unfreeze();
  28008. }
  28009. };
  28010. /**
  28011. * Releases all held ressources
  28012. */
  28013. Scene.prototype.dispose = function () {
  28014. this.beforeRender = null;
  28015. this.afterRender = null;
  28016. this.skeletons = [];
  28017. this.morphTargetManagers = [];
  28018. this._transientComponents = [];
  28019. this._isReadyForMeshStage.clear();
  28020. this._beforeEvaluateActiveMeshStage.clear();
  28021. this._evaluateSubMeshStage.clear();
  28022. this._activeMeshStage.clear();
  28023. this._cameraDrawRenderTargetStage.clear();
  28024. this._beforeCameraDrawStage.clear();
  28025. this._beforeRenderingGroupDrawStage.clear();
  28026. this._beforeRenderingMeshStage.clear();
  28027. this._afterRenderingMeshStage.clear();
  28028. this._afterRenderingGroupDrawStage.clear();
  28029. this._afterCameraDrawStage.clear();
  28030. this._afterRenderStage.clear();
  28031. this._beforeCameraUpdateStage.clear();
  28032. this._beforeClearStage.clear();
  28033. this._gatherRenderTargetsStage.clear();
  28034. this._gatherActiveCameraRenderTargetsStage.clear();
  28035. this._pointerMoveStage.clear();
  28036. this._pointerDownStage.clear();
  28037. this._pointerUpStage.clear();
  28038. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28039. var component = _a[_i];
  28040. component.dispose();
  28041. }
  28042. this.importedMeshesFiles = new Array();
  28043. this.stopAllAnimations();
  28044. this.resetCachedMaterial();
  28045. // Smart arrays
  28046. if (this.activeCamera) {
  28047. this.activeCamera._activeMeshes.dispose();
  28048. this.activeCamera = null;
  28049. }
  28050. this._activeMeshes.dispose();
  28051. this._renderingManager.dispose();
  28052. this._processedMaterials.dispose();
  28053. this._activeParticleSystems.dispose();
  28054. this._activeSkeletons.dispose();
  28055. this._softwareSkinnedMeshes.dispose();
  28056. this._renderTargets.dispose();
  28057. this._registeredForLateAnimationBindings.dispose();
  28058. this._meshesForIntersections.dispose();
  28059. this._toBeDisposed = [];
  28060. // Abort active requests
  28061. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28062. var request = _c[_b];
  28063. request.abort();
  28064. }
  28065. // Events
  28066. this.onDisposeObservable.notifyObservers(this);
  28067. this.onDisposeObservable.clear();
  28068. this.onBeforeRenderObservable.clear();
  28069. this.onAfterRenderObservable.clear();
  28070. this.onBeforeRenderTargetsRenderObservable.clear();
  28071. this.onAfterRenderTargetsRenderObservable.clear();
  28072. this.onAfterStepObservable.clear();
  28073. this.onBeforeStepObservable.clear();
  28074. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28075. this.onAfterActiveMeshesEvaluationObservable.clear();
  28076. this.onBeforeParticlesRenderingObservable.clear();
  28077. this.onAfterParticlesRenderingObservable.clear();
  28078. this.onBeforeDrawPhaseObservable.clear();
  28079. this.onAfterDrawPhaseObservable.clear();
  28080. this.onBeforeAnimationsObservable.clear();
  28081. this.onAfterAnimationsObservable.clear();
  28082. this.onDataLoadedObservable.clear();
  28083. this.onBeforeRenderingGroupObservable.clear();
  28084. this.onAfterRenderingGroupObservable.clear();
  28085. this.onMeshImportedObservable.clear();
  28086. this.detachControl();
  28087. // Detach cameras
  28088. var canvas = this._engine.getRenderingCanvas();
  28089. if (canvas) {
  28090. var index;
  28091. for (index = 0; index < this.cameras.length; index++) {
  28092. this.cameras[index].detachControl(canvas);
  28093. }
  28094. }
  28095. // Release animation groups
  28096. while (this.animationGroups.length) {
  28097. this.animationGroups[0].dispose();
  28098. }
  28099. // Release lights
  28100. while (this.lights.length) {
  28101. this.lights[0].dispose();
  28102. }
  28103. // Release meshes
  28104. while (this.meshes.length) {
  28105. this.meshes[0].dispose(true);
  28106. }
  28107. while (this.transformNodes.length) {
  28108. this.removeTransformNode(this.transformNodes[0]);
  28109. }
  28110. // Release cameras
  28111. while (this.cameras.length) {
  28112. this.cameras[0].dispose();
  28113. }
  28114. // Release materials
  28115. if (this.defaultMaterial) {
  28116. this.defaultMaterial.dispose();
  28117. }
  28118. while (this.multiMaterials.length) {
  28119. this.multiMaterials[0].dispose();
  28120. }
  28121. while (this.materials.length) {
  28122. this.materials[0].dispose();
  28123. }
  28124. // Release particles
  28125. while (this.particleSystems.length) {
  28126. this.particleSystems[0].dispose();
  28127. }
  28128. // Release postProcesses
  28129. while (this.postProcesses.length) {
  28130. this.postProcesses[0].dispose();
  28131. }
  28132. // Release textures
  28133. while (this.textures.length) {
  28134. this.textures[0].dispose();
  28135. }
  28136. // Release UBO
  28137. this._sceneUbo.dispose();
  28138. if (this._alternateSceneUbo) {
  28139. this._alternateSceneUbo.dispose();
  28140. }
  28141. // Post-processes
  28142. this.postProcessManager.dispose();
  28143. // Remove from engine
  28144. index = this._engine.scenes.indexOf(this);
  28145. if (index > -1) {
  28146. this._engine.scenes.splice(index, 1);
  28147. }
  28148. this._engine.wipeCaches(true);
  28149. this._isDisposed = true;
  28150. };
  28151. Object.defineProperty(Scene.prototype, "isDisposed", {
  28152. /**
  28153. * Gets if the scene is already disposed
  28154. */
  28155. get: function () {
  28156. return this._isDisposed;
  28157. },
  28158. enumerable: true,
  28159. configurable: true
  28160. });
  28161. /**
  28162. * Call this function to reduce memory footprint of the scene.
  28163. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28164. */
  28165. Scene.prototype.clearCachedVertexData = function () {
  28166. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28167. var mesh = this.meshes[meshIndex];
  28168. var geometry = mesh.geometry;
  28169. if (geometry) {
  28170. geometry._indices = [];
  28171. for (var vbName in geometry._vertexBuffers) {
  28172. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28173. continue;
  28174. }
  28175. geometry._vertexBuffers[vbName]._buffer._data = null;
  28176. }
  28177. }
  28178. }
  28179. };
  28180. /**
  28181. * This function will remove the local cached buffer data from texture.
  28182. * It will save memory but will prevent the texture from being rebuilt
  28183. */
  28184. Scene.prototype.cleanCachedTextureBuffer = function () {
  28185. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28186. var baseTexture = _a[_i];
  28187. var buffer = baseTexture._buffer;
  28188. if (buffer) {
  28189. baseTexture._buffer = null;
  28190. }
  28191. }
  28192. };
  28193. /**
  28194. * Get the world extend vectors with an optional filter
  28195. *
  28196. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28197. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28198. */
  28199. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28200. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28201. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28202. filterPredicate = filterPredicate || (function () { return true; });
  28203. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28204. mesh.computeWorldMatrix(true);
  28205. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28206. return;
  28207. }
  28208. var boundingInfo = mesh.getBoundingInfo();
  28209. var minBox = boundingInfo.boundingBox.minimumWorld;
  28210. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28211. BABYLON.Tools.CheckExtends(minBox, min, max);
  28212. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28213. });
  28214. return {
  28215. min: min,
  28216. max: max
  28217. };
  28218. };
  28219. // Picking
  28220. /**
  28221. * Creates a ray that can be used to pick in the scene
  28222. * @param x defines the x coordinate of the origin (on-screen)
  28223. * @param y defines the y coordinate of the origin (on-screen)
  28224. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28225. * @param camera defines the camera to use for the picking
  28226. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28227. * @returns a Ray
  28228. */
  28229. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28230. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28231. var result = BABYLON.Ray.Zero();
  28232. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28233. return result;
  28234. };
  28235. /**
  28236. * Creates a ray that can be used to pick in the scene
  28237. * @param x defines the x coordinate of the origin (on-screen)
  28238. * @param y defines the y coordinate of the origin (on-screen)
  28239. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28240. * @param result defines the ray where to store the picking ray
  28241. * @param camera defines the camera to use for the picking
  28242. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28243. * @returns the current scene
  28244. */
  28245. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28246. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28247. var engine = this._engine;
  28248. if (!camera) {
  28249. if (!this.activeCamera)
  28250. throw new Error("Active camera not set");
  28251. camera = this.activeCamera;
  28252. }
  28253. var cameraViewport = camera.viewport;
  28254. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28255. // Moving coordinates to local viewport world
  28256. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28257. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28258. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28259. return this;
  28260. };
  28261. /**
  28262. * Creates a ray that can be used to pick in the scene
  28263. * @param x defines the x coordinate of the origin (on-screen)
  28264. * @param y defines the y coordinate of the origin (on-screen)
  28265. * @param camera defines the camera to use for the picking
  28266. * @returns a Ray
  28267. */
  28268. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28269. var result = BABYLON.Ray.Zero();
  28270. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28271. return result;
  28272. };
  28273. /**
  28274. * Creates a ray that can be used to pick in the scene
  28275. * @param x defines the x coordinate of the origin (on-screen)
  28276. * @param y defines the y coordinate of the origin (on-screen)
  28277. * @param result defines the ray where to store the picking ray
  28278. * @param camera defines the camera to use for the picking
  28279. * @returns the current scene
  28280. */
  28281. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28282. if (!BABYLON.PickingInfo) {
  28283. return this;
  28284. }
  28285. var engine = this._engine;
  28286. if (!camera) {
  28287. if (!this.activeCamera)
  28288. throw new Error("Active camera not set");
  28289. camera = this.activeCamera;
  28290. }
  28291. var cameraViewport = camera.viewport;
  28292. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28293. var identity = BABYLON.Matrix.Identity();
  28294. // Moving coordinates to local viewport world
  28295. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28296. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28297. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28298. return this;
  28299. };
  28300. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28301. if (!BABYLON.PickingInfo) {
  28302. return null;
  28303. }
  28304. var pickingInfo = null;
  28305. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28306. var mesh = this.meshes[meshIndex];
  28307. if (predicate) {
  28308. if (!predicate(mesh)) {
  28309. continue;
  28310. }
  28311. }
  28312. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28313. continue;
  28314. }
  28315. var world = mesh.getWorldMatrix();
  28316. var ray = rayFunction(world);
  28317. var result = mesh.intersects(ray, fastCheck);
  28318. if (!result || !result.hit)
  28319. continue;
  28320. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28321. continue;
  28322. pickingInfo = result;
  28323. if (fastCheck) {
  28324. break;
  28325. }
  28326. }
  28327. return pickingInfo || new BABYLON.PickingInfo();
  28328. };
  28329. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28330. if (!BABYLON.PickingInfo) {
  28331. return null;
  28332. }
  28333. var pickingInfos = new Array();
  28334. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28335. var mesh = this.meshes[meshIndex];
  28336. if (predicate) {
  28337. if (!predicate(mesh)) {
  28338. continue;
  28339. }
  28340. }
  28341. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28342. continue;
  28343. }
  28344. var world = mesh.getWorldMatrix();
  28345. var ray = rayFunction(world);
  28346. var result = mesh.intersects(ray, false);
  28347. if (!result || !result.hit)
  28348. continue;
  28349. pickingInfos.push(result);
  28350. }
  28351. return pickingInfos;
  28352. };
  28353. /** Launch a ray to try to pick a mesh in the scene
  28354. * @param x position on screen
  28355. * @param y position on screen
  28356. * @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
  28357. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28358. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28359. * @returns a PickingInfo
  28360. */
  28361. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28362. var _this = this;
  28363. if (!BABYLON.PickingInfo) {
  28364. return null;
  28365. }
  28366. var result = this._internalPick(function (world) {
  28367. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28368. return _this._tempPickingRay;
  28369. }, predicate, fastCheck);
  28370. if (result) {
  28371. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28372. }
  28373. return result;
  28374. };
  28375. /** Use the given ray to pick a mesh in the scene
  28376. * @param ray The ray to use to pick meshes
  28377. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28378. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28379. * @returns a PickingInfo
  28380. */
  28381. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28382. var _this = this;
  28383. var result = this._internalPick(function (world) {
  28384. if (!_this._pickWithRayInverseMatrix) {
  28385. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28386. }
  28387. world.invertToRef(_this._pickWithRayInverseMatrix);
  28388. if (!_this._cachedRayForTransform) {
  28389. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28390. }
  28391. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28392. return _this._cachedRayForTransform;
  28393. }, predicate, fastCheck);
  28394. if (result) {
  28395. result.ray = ray;
  28396. }
  28397. return result;
  28398. };
  28399. /**
  28400. * Launch a ray to try to pick a mesh in the scene
  28401. * @param x X position on screen
  28402. * @param y Y position on screen
  28403. * @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
  28404. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28405. * @returns an array of PickingInfo
  28406. */
  28407. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28408. var _this = this;
  28409. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28410. };
  28411. /**
  28412. * Launch a ray to try to pick a mesh in the scene
  28413. * @param ray Ray to use
  28414. * @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
  28415. * @returns an array of PickingInfo
  28416. */
  28417. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28418. var _this = this;
  28419. return this._internalMultiPick(function (world) {
  28420. if (!_this._pickWithRayInverseMatrix) {
  28421. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28422. }
  28423. world.invertToRef(_this._pickWithRayInverseMatrix);
  28424. if (!_this._cachedRayForTransform) {
  28425. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28426. }
  28427. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28428. return _this._cachedRayForTransform;
  28429. }, predicate);
  28430. };
  28431. /**
  28432. * Force the value of meshUnderPointer
  28433. * @param mesh defines the mesh to use
  28434. */
  28435. Scene.prototype.setPointerOverMesh = function (mesh) {
  28436. if (this._pointerOverMesh === mesh) {
  28437. return;
  28438. }
  28439. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28440. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28441. }
  28442. this._pointerOverMesh = mesh;
  28443. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28444. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28445. }
  28446. };
  28447. /**
  28448. * Gets the mesh under the pointer
  28449. * @returns a Mesh or null if no mesh is under the pointer
  28450. */
  28451. Scene.prototype.getPointerOverMesh = function () {
  28452. return this._pointerOverMesh;
  28453. };
  28454. // Misc.
  28455. /** @hidden */
  28456. Scene.prototype._rebuildGeometries = function () {
  28457. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28458. var geometry = _a[_i];
  28459. geometry._rebuild();
  28460. }
  28461. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28462. var mesh = _c[_b];
  28463. mesh._rebuild();
  28464. }
  28465. if (this.postProcessManager) {
  28466. this.postProcessManager._rebuild();
  28467. }
  28468. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28469. var component = _e[_d];
  28470. component.rebuild();
  28471. }
  28472. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28473. var system = _g[_f];
  28474. system.rebuild();
  28475. }
  28476. };
  28477. /** @hidden */
  28478. Scene.prototype._rebuildTextures = function () {
  28479. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28480. var texture = _a[_i];
  28481. texture._rebuild();
  28482. }
  28483. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28484. };
  28485. // Tags
  28486. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28487. if (tagsQuery === undefined) {
  28488. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28489. return list;
  28490. }
  28491. var listByTags = [];
  28492. forEach = forEach || (function (item) { return; });
  28493. for (var i in list) {
  28494. var item = list[i];
  28495. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28496. listByTags.push(item);
  28497. forEach(item);
  28498. }
  28499. }
  28500. return listByTags;
  28501. };
  28502. /**
  28503. * Get a list of meshes by tags
  28504. * @param tagsQuery defines the tags query to use
  28505. * @param forEach defines a predicate used to filter results
  28506. * @returns an array of Mesh
  28507. */
  28508. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28509. return this._getByTags(this.meshes, tagsQuery, forEach);
  28510. };
  28511. /**
  28512. * Get a list of cameras by tags
  28513. * @param tagsQuery defines the tags query to use
  28514. * @param forEach defines a predicate used to filter results
  28515. * @returns an array of Camera
  28516. */
  28517. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28518. return this._getByTags(this.cameras, tagsQuery, forEach);
  28519. };
  28520. /**
  28521. * Get a list of lights by tags
  28522. * @param tagsQuery defines the tags query to use
  28523. * @param forEach defines a predicate used to filter results
  28524. * @returns an array of Light
  28525. */
  28526. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28527. return this._getByTags(this.lights, tagsQuery, forEach);
  28528. };
  28529. /**
  28530. * Get a list of materials by tags
  28531. * @param tagsQuery defines the tags query to use
  28532. * @param forEach defines a predicate used to filter results
  28533. * @returns an array of Material
  28534. */
  28535. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28536. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28537. };
  28538. /**
  28539. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28540. * This allowed control for front to back rendering or reversly depending of the special needs.
  28541. *
  28542. * @param renderingGroupId The rendering group id corresponding to its index
  28543. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28544. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28545. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28546. */
  28547. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28548. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28549. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28550. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28551. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28552. };
  28553. /**
  28554. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28555. *
  28556. * @param renderingGroupId The rendering group id corresponding to its index
  28557. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28558. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28559. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28560. */
  28561. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28562. if (depth === void 0) { depth = true; }
  28563. if (stencil === void 0) { stencil = true; }
  28564. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28565. };
  28566. /**
  28567. * Gets the current auto clear configuration for one rendering group of the rendering
  28568. * manager.
  28569. * @param index the rendering group index to get the information for
  28570. * @returns The auto clear setup for the requested rendering group
  28571. */
  28572. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28573. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28574. };
  28575. /**
  28576. * Will flag all materials as dirty to trigger new shader compilation
  28577. * @param flag defines the flag used to specify which material part must be marked as dirty
  28578. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28579. */
  28580. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28581. if (this.blockMaterialDirtyMechanism) {
  28582. return;
  28583. }
  28584. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28585. var material = _a[_i];
  28586. if (predicate && !predicate(material)) {
  28587. continue;
  28588. }
  28589. material.markAsDirty(flag);
  28590. }
  28591. };
  28592. /** @hidden */
  28593. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28594. var _this = this;
  28595. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28596. this._activeRequests.push(request);
  28597. request.onCompleteObservable.add(function (request) {
  28598. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28599. });
  28600. return request;
  28601. };
  28602. /** @hidden */
  28603. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28604. var _this = this;
  28605. return new Promise(function (resolve, reject) {
  28606. _this._loadFile(url, function (data) {
  28607. resolve(data);
  28608. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28609. reject(exception);
  28610. });
  28611. });
  28612. };
  28613. // Statics
  28614. Scene._uniqueIdCounter = 0;
  28615. /** The fog is deactivated */
  28616. Scene.FOGMODE_NONE = 0;
  28617. /** The fog density is following an exponential function */
  28618. Scene.FOGMODE_EXP = 1;
  28619. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28620. Scene.FOGMODE_EXP2 = 2;
  28621. /** The fog density is following a linear function. */
  28622. Scene.FOGMODE_LINEAR = 3;
  28623. /**
  28624. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28625. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28626. */
  28627. Scene.MinDeltaTime = 1.0;
  28628. /**
  28629. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28630. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28631. */
  28632. Scene.MaxDeltaTime = 1000.0;
  28633. /** The distance in pixel that you have to move to prevent some events */
  28634. Scene.DragMovementThreshold = 10; // in pixels
  28635. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28636. Scene.LongPressDelay = 500; // in milliseconds
  28637. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28638. Scene.DoubleClickDelay = 300; // in milliseconds
  28639. /** If you need to check double click without raising a single click at first click, enable this flag */
  28640. Scene.ExclusiveDoubleClickMode = false;
  28641. return Scene;
  28642. }(BABYLON.AbstractScene));
  28643. BABYLON.Scene = Scene;
  28644. })(BABYLON || (BABYLON = {}));
  28645. //# sourceMappingURL=babylon.scene.js.map
  28646. var BABYLON;
  28647. (function (BABYLON) {
  28648. /**
  28649. * Set of assets to keep when moving a scene into an asset container.
  28650. */
  28651. var KeepAssets = /** @class */ (function (_super) {
  28652. __extends(KeepAssets, _super);
  28653. function KeepAssets() {
  28654. return _super !== null && _super.apply(this, arguments) || this;
  28655. }
  28656. return KeepAssets;
  28657. }(BABYLON.AbstractScene));
  28658. BABYLON.KeepAssets = KeepAssets;
  28659. /**
  28660. * Container with a set of assets that can be added or removed from a scene.
  28661. */
  28662. var AssetContainer = /** @class */ (function (_super) {
  28663. __extends(AssetContainer, _super);
  28664. /**
  28665. * Instantiates an AssetContainer.
  28666. * @param scene The scene the AssetContainer belongs to.
  28667. */
  28668. function AssetContainer(scene) {
  28669. var _this = _super.call(this) || this;
  28670. _this.scene = scene;
  28671. return _this;
  28672. }
  28673. /**
  28674. * Adds all the assets from the container to the scene.
  28675. */
  28676. AssetContainer.prototype.addAllToScene = function () {
  28677. var _this = this;
  28678. this.cameras.forEach(function (o) {
  28679. _this.scene.addCamera(o);
  28680. });
  28681. this.lights.forEach(function (o) {
  28682. _this.scene.addLight(o);
  28683. });
  28684. this.meshes.forEach(function (o) {
  28685. _this.scene.addMesh(o);
  28686. });
  28687. this.skeletons.forEach(function (o) {
  28688. _this.scene.addSkeleton(o);
  28689. });
  28690. this.animations.forEach(function (o) {
  28691. _this.scene.addAnimation(o);
  28692. });
  28693. this.animationGroups.forEach(function (o) {
  28694. _this.scene.addAnimationGroup(o);
  28695. });
  28696. this.multiMaterials.forEach(function (o) {
  28697. _this.scene.addMultiMaterial(o);
  28698. });
  28699. this.materials.forEach(function (o) {
  28700. _this.scene.addMaterial(o);
  28701. });
  28702. this.morphTargetManagers.forEach(function (o) {
  28703. _this.scene.addMorphTargetManager(o);
  28704. });
  28705. this.geometries.forEach(function (o) {
  28706. _this.scene.addGeometry(o);
  28707. });
  28708. this.transformNodes.forEach(function (o) {
  28709. _this.scene.addTransformNode(o);
  28710. });
  28711. this.actionManagers.forEach(function (o) {
  28712. _this.scene.addActionManager(o);
  28713. });
  28714. this.textures.forEach(function (o) {
  28715. _this.scene.addTexture(o);
  28716. });
  28717. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28718. var component = _a[_i];
  28719. component.addFromContainer(this.scene);
  28720. }
  28721. };
  28722. /**
  28723. * Removes all the assets in the container from the scene
  28724. */
  28725. AssetContainer.prototype.removeAllFromScene = function () {
  28726. var _this = this;
  28727. this.cameras.forEach(function (o) {
  28728. _this.scene.removeCamera(o);
  28729. });
  28730. this.lights.forEach(function (o) {
  28731. _this.scene.removeLight(o);
  28732. });
  28733. this.meshes.forEach(function (o) {
  28734. _this.scene.removeMesh(o);
  28735. });
  28736. this.skeletons.forEach(function (o) {
  28737. _this.scene.removeSkeleton(o);
  28738. });
  28739. this.animations.forEach(function (o) {
  28740. _this.scene.removeAnimation(o);
  28741. });
  28742. this.animationGroups.forEach(function (o) {
  28743. _this.scene.removeAnimationGroup(o);
  28744. });
  28745. this.multiMaterials.forEach(function (o) {
  28746. _this.scene.removeMultiMaterial(o);
  28747. });
  28748. this.materials.forEach(function (o) {
  28749. _this.scene.removeMaterial(o);
  28750. });
  28751. this.morphTargetManagers.forEach(function (o) {
  28752. _this.scene.removeMorphTargetManager(o);
  28753. });
  28754. this.geometries.forEach(function (o) {
  28755. _this.scene.removeGeometry(o);
  28756. });
  28757. this.transformNodes.forEach(function (o) {
  28758. _this.scene.removeTransformNode(o);
  28759. });
  28760. this.actionManagers.forEach(function (o) {
  28761. _this.scene.removeActionManager(o);
  28762. });
  28763. this.textures.forEach(function (o) {
  28764. _this.scene.removeTexture(o);
  28765. });
  28766. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28767. var component = _a[_i];
  28768. component.removeFromContainer(this.scene);
  28769. }
  28770. };
  28771. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28772. if (!sourceAssets) {
  28773. return;
  28774. }
  28775. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28776. var asset = sourceAssets_1[_i];
  28777. var move = true;
  28778. if (keepAssets) {
  28779. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28780. var keepAsset = keepAssets_1[_a];
  28781. if (asset === keepAsset) {
  28782. move = false;
  28783. break;
  28784. }
  28785. }
  28786. }
  28787. if (move) {
  28788. targetAssets.push(asset);
  28789. }
  28790. }
  28791. };
  28792. /**
  28793. * Removes all the assets contained in the scene and adds them to the container.
  28794. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28795. */
  28796. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28797. if (keepAssets === undefined) {
  28798. keepAssets = new KeepAssets();
  28799. }
  28800. for (var key in this) {
  28801. if (this.hasOwnProperty(key)) {
  28802. this[key] = this[key] || [];
  28803. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28804. }
  28805. }
  28806. this.removeAllFromScene();
  28807. };
  28808. /**
  28809. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  28810. * @returns the root mesh
  28811. */
  28812. AssetContainer.prototype.createRootMesh = function () {
  28813. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28814. this.meshes.forEach(function (m) {
  28815. if (!m.parent) {
  28816. rootMesh.addChild(m);
  28817. }
  28818. });
  28819. this.meshes.unshift(rootMesh);
  28820. return rootMesh;
  28821. };
  28822. return AssetContainer;
  28823. }(BABYLON.AbstractScene));
  28824. BABYLON.AssetContainer = AssetContainer;
  28825. })(BABYLON || (BABYLON = {}));
  28826. //# sourceMappingURL=babylon.assetContainer.js.map
  28827. var BABYLON;
  28828. (function (BABYLON) {
  28829. var Buffer = /** @class */ (function () {
  28830. /**
  28831. * Constructor
  28832. * @param engine the engine
  28833. * @param data the data to use for this buffer
  28834. * @param updatable whether the data is updatable
  28835. * @param stride the stride (optional)
  28836. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28837. * @param instanced whether the buffer is instanced (optional)
  28838. * @param useBytes set to true if the stride in in bytes (optional)
  28839. */
  28840. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28841. if (stride === void 0) { stride = 0; }
  28842. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28843. if (instanced === void 0) { instanced = false; }
  28844. if (useBytes === void 0) { useBytes = false; }
  28845. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28846. this._engine = engine.getScene().getEngine();
  28847. }
  28848. else {
  28849. this._engine = engine;
  28850. }
  28851. this._updatable = updatable;
  28852. this._instanced = instanced;
  28853. this._data = data;
  28854. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28855. if (!postponeInternalCreation) { // by default
  28856. this.create();
  28857. }
  28858. }
  28859. /**
  28860. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28861. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28862. * @param offset defines offset in the buffer (0 by default)
  28863. * @param size defines the size in floats of attributes (position is 3 for instance)
  28864. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28865. * @param instanced defines if the vertex buffer contains indexed data
  28866. * @param useBytes defines if the offset and stride are in bytes
  28867. * @returns the new vertex buffer
  28868. */
  28869. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28870. if (useBytes === void 0) { useBytes = false; }
  28871. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28872. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28873. // a lot of these parameters are ignored as they are overriden by the buffer
  28874. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28875. };
  28876. // Properties
  28877. Buffer.prototype.isUpdatable = function () {
  28878. return this._updatable;
  28879. };
  28880. Buffer.prototype.getData = function () {
  28881. return this._data;
  28882. };
  28883. Buffer.prototype.getBuffer = function () {
  28884. return this._buffer;
  28885. };
  28886. /**
  28887. * Gets the stride in float32 units (i.e. byte stride / 4).
  28888. * May not be an integer if the byte stride is not divisible by 4.
  28889. * DEPRECATED. Use byteStride instead.
  28890. * @returns the stride in float32 units
  28891. */
  28892. Buffer.prototype.getStrideSize = function () {
  28893. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28894. };
  28895. // Methods
  28896. Buffer.prototype.create = function (data) {
  28897. if (data === void 0) { data = null; }
  28898. if (!data && this._buffer) {
  28899. return; // nothing to do
  28900. }
  28901. data = data || this._data;
  28902. if (!data) {
  28903. return;
  28904. }
  28905. if (!this._buffer) { // create buffer
  28906. if (this._updatable) {
  28907. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28908. this._data = data;
  28909. }
  28910. else {
  28911. this._buffer = this._engine.createVertexBuffer(data);
  28912. }
  28913. }
  28914. else if (this._updatable) { // update buffer
  28915. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28916. this._data = data;
  28917. }
  28918. };
  28919. /** @hidden */
  28920. Buffer.prototype._rebuild = function () {
  28921. this._buffer = null;
  28922. this.create(this._data);
  28923. };
  28924. Buffer.prototype.update = function (data) {
  28925. this.create(data);
  28926. };
  28927. /**
  28928. * Updates the data directly.
  28929. * @param data the new data
  28930. * @param offset the new offset
  28931. * @param vertexCount the vertex count (optional)
  28932. * @param useBytes set to true if the offset is in bytes
  28933. */
  28934. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28935. if (useBytes === void 0) { useBytes = false; }
  28936. if (!this._buffer) {
  28937. return;
  28938. }
  28939. if (this._updatable) { // update buffer
  28940. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28941. this._data = null;
  28942. }
  28943. };
  28944. Buffer.prototype.dispose = function () {
  28945. if (!this._buffer) {
  28946. return;
  28947. }
  28948. if (this._engine._releaseBuffer(this._buffer)) {
  28949. this._buffer = null;
  28950. }
  28951. };
  28952. return Buffer;
  28953. }());
  28954. BABYLON.Buffer = Buffer;
  28955. })(BABYLON || (BABYLON = {}));
  28956. //# sourceMappingURL=babylon.buffer.js.map
  28957. var BABYLON;
  28958. (function (BABYLON) {
  28959. var VertexBuffer = /** @class */ (function () {
  28960. /**
  28961. * Constructor
  28962. * @param engine the engine
  28963. * @param data the data to use for this vertex buffer
  28964. * @param kind the vertex buffer kind
  28965. * @param updatable whether the data is updatable
  28966. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28967. * @param stride the stride (optional)
  28968. * @param instanced whether the buffer is instanced (optional)
  28969. * @param offset the offset of the data (optional)
  28970. * @param size the number of components (optional)
  28971. * @param type the type of the component (optional)
  28972. * @param normalized whether the data contains normalized data (optional)
  28973. * @param useBytes set to true if stride and offset are in bytes (optional)
  28974. */
  28975. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28976. if (normalized === void 0) { normalized = false; }
  28977. if (useBytes === void 0) { useBytes = false; }
  28978. if (data instanceof BABYLON.Buffer) {
  28979. this._buffer = data;
  28980. this._ownsBuffer = false;
  28981. }
  28982. else {
  28983. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28984. this._ownsBuffer = true;
  28985. }
  28986. this._kind = kind;
  28987. if (type == undefined) {
  28988. var data_1 = this.getData();
  28989. this.type = VertexBuffer.FLOAT;
  28990. if (data_1 instanceof Int8Array)
  28991. this.type = VertexBuffer.BYTE;
  28992. else if (data_1 instanceof Uint8Array)
  28993. this.type = VertexBuffer.UNSIGNED_BYTE;
  28994. else if (data_1 instanceof Int16Array)
  28995. this.type = VertexBuffer.SHORT;
  28996. else if (data_1 instanceof Uint16Array)
  28997. this.type = VertexBuffer.UNSIGNED_SHORT;
  28998. else if (data_1 instanceof Int32Array)
  28999. this.type = VertexBuffer.INT;
  29000. else if (data_1 instanceof Uint32Array)
  29001. this.type = VertexBuffer.UNSIGNED_INT;
  29002. }
  29003. else {
  29004. this.type = type;
  29005. }
  29006. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29007. if (useBytes) {
  29008. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29009. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29010. this.byteOffset = offset || 0;
  29011. }
  29012. else {
  29013. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29014. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29015. this.byteOffset = (offset || 0) * typeByteLength;
  29016. }
  29017. this.normalized = normalized;
  29018. this._instanced = instanced !== undefined ? instanced : false;
  29019. this._instanceDivisor = instanced ? 1 : 0;
  29020. }
  29021. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29022. /**
  29023. * Gets or sets the instance divisor when in instanced mode
  29024. */
  29025. get: function () {
  29026. return this._instanceDivisor;
  29027. },
  29028. set: function (value) {
  29029. this._instanceDivisor = value;
  29030. if (value == 0) {
  29031. this._instanced = false;
  29032. }
  29033. else {
  29034. this._instanced = true;
  29035. }
  29036. },
  29037. enumerable: true,
  29038. configurable: true
  29039. });
  29040. /** @hidden */
  29041. VertexBuffer.prototype._rebuild = function () {
  29042. if (!this._buffer) {
  29043. return;
  29044. }
  29045. this._buffer._rebuild();
  29046. };
  29047. /**
  29048. * Returns the kind of the VertexBuffer (string).
  29049. */
  29050. VertexBuffer.prototype.getKind = function () {
  29051. return this._kind;
  29052. };
  29053. // Properties
  29054. /**
  29055. * Boolean : is the VertexBuffer updatable ?
  29056. */
  29057. VertexBuffer.prototype.isUpdatable = function () {
  29058. return this._buffer.isUpdatable();
  29059. };
  29060. /**
  29061. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29062. */
  29063. VertexBuffer.prototype.getData = function () {
  29064. return this._buffer.getData();
  29065. };
  29066. /**
  29067. * Returns the WebGLBuffer associated to the VertexBuffer.
  29068. */
  29069. VertexBuffer.prototype.getBuffer = function () {
  29070. return this._buffer.getBuffer();
  29071. };
  29072. /**
  29073. * Returns the stride as a multiple of the type byte length.
  29074. * DEPRECATED. Use byteStride instead.
  29075. */
  29076. VertexBuffer.prototype.getStrideSize = function () {
  29077. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29078. };
  29079. /**
  29080. * Returns the offset as a multiple of the type byte length.
  29081. * DEPRECATED. Use byteOffset instead.
  29082. */
  29083. VertexBuffer.prototype.getOffset = function () {
  29084. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29085. };
  29086. /**
  29087. * Returns the number of components per vertex attribute (integer).
  29088. */
  29089. VertexBuffer.prototype.getSize = function () {
  29090. return this._size;
  29091. };
  29092. /**
  29093. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29094. */
  29095. VertexBuffer.prototype.getIsInstanced = function () {
  29096. return this._instanced;
  29097. };
  29098. /**
  29099. * Returns the instancing divisor, zero for non-instanced (integer).
  29100. */
  29101. VertexBuffer.prototype.getInstanceDivisor = function () {
  29102. return this._instanceDivisor;
  29103. };
  29104. // Methods
  29105. /**
  29106. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29107. * Returns the created WebGLBuffer.
  29108. */
  29109. VertexBuffer.prototype.create = function (data) {
  29110. return this._buffer.create(data);
  29111. };
  29112. /**
  29113. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29114. * This function will create a new buffer if the current one is not updatable
  29115. * Returns the updated WebGLBuffer.
  29116. */
  29117. VertexBuffer.prototype.update = function (data) {
  29118. return this._buffer.update(data);
  29119. };
  29120. /**
  29121. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29122. * Returns the directly updated WebGLBuffer.
  29123. * @param data the new data
  29124. * @param offset the new offset
  29125. * @param useBytes set to true if the offset is in bytes
  29126. */
  29127. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29128. if (useBytes === void 0) { useBytes = false; }
  29129. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29130. };
  29131. /**
  29132. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29133. */
  29134. VertexBuffer.prototype.dispose = function () {
  29135. if (this._ownsBuffer) {
  29136. this._buffer.dispose();
  29137. }
  29138. };
  29139. /**
  29140. * Enumerates each value of this vertex buffer as numbers.
  29141. * @param count the number of values to enumerate
  29142. * @param callback the callback function called for each value
  29143. */
  29144. VertexBuffer.prototype.forEach = function (count, callback) {
  29145. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29146. };
  29147. Object.defineProperty(VertexBuffer, "PositionKind", {
  29148. get: function () {
  29149. return VertexBuffer._PositionKind;
  29150. },
  29151. enumerable: true,
  29152. configurable: true
  29153. });
  29154. Object.defineProperty(VertexBuffer, "NormalKind", {
  29155. get: function () {
  29156. return VertexBuffer._NormalKind;
  29157. },
  29158. enumerable: true,
  29159. configurable: true
  29160. });
  29161. Object.defineProperty(VertexBuffer, "TangentKind", {
  29162. get: function () {
  29163. return VertexBuffer._TangentKind;
  29164. },
  29165. enumerable: true,
  29166. configurable: true
  29167. });
  29168. Object.defineProperty(VertexBuffer, "UVKind", {
  29169. get: function () {
  29170. return VertexBuffer._UVKind;
  29171. },
  29172. enumerable: true,
  29173. configurable: true
  29174. });
  29175. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29176. get: function () {
  29177. return VertexBuffer._UV2Kind;
  29178. },
  29179. enumerable: true,
  29180. configurable: true
  29181. });
  29182. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29183. get: function () {
  29184. return VertexBuffer._UV3Kind;
  29185. },
  29186. enumerable: true,
  29187. configurable: true
  29188. });
  29189. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29190. get: function () {
  29191. return VertexBuffer._UV4Kind;
  29192. },
  29193. enumerable: true,
  29194. configurable: true
  29195. });
  29196. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29197. get: function () {
  29198. return VertexBuffer._UV5Kind;
  29199. },
  29200. enumerable: true,
  29201. configurable: true
  29202. });
  29203. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29204. get: function () {
  29205. return VertexBuffer._UV6Kind;
  29206. },
  29207. enumerable: true,
  29208. configurable: true
  29209. });
  29210. Object.defineProperty(VertexBuffer, "ColorKind", {
  29211. get: function () {
  29212. return VertexBuffer._ColorKind;
  29213. },
  29214. enumerable: true,
  29215. configurable: true
  29216. });
  29217. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29218. get: function () {
  29219. return VertexBuffer._MatricesIndicesKind;
  29220. },
  29221. enumerable: true,
  29222. configurable: true
  29223. });
  29224. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29225. get: function () {
  29226. return VertexBuffer._MatricesWeightsKind;
  29227. },
  29228. enumerable: true,
  29229. configurable: true
  29230. });
  29231. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29232. get: function () {
  29233. return VertexBuffer._MatricesIndicesExtraKind;
  29234. },
  29235. enumerable: true,
  29236. configurable: true
  29237. });
  29238. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29239. get: function () {
  29240. return VertexBuffer._MatricesWeightsExtraKind;
  29241. },
  29242. enumerable: true,
  29243. configurable: true
  29244. });
  29245. /**
  29246. * Deduces the stride given a kind.
  29247. * @param kind The kind string to deduce
  29248. * @returns The deduced stride
  29249. */
  29250. VertexBuffer.DeduceStride = function (kind) {
  29251. switch (kind) {
  29252. case VertexBuffer.UVKind:
  29253. case VertexBuffer.UV2Kind:
  29254. case VertexBuffer.UV3Kind:
  29255. case VertexBuffer.UV4Kind:
  29256. case VertexBuffer.UV5Kind:
  29257. case VertexBuffer.UV6Kind:
  29258. return 2;
  29259. case VertexBuffer.NormalKind:
  29260. case VertexBuffer.PositionKind:
  29261. return 3;
  29262. case VertexBuffer.ColorKind:
  29263. case VertexBuffer.MatricesIndicesKind:
  29264. case VertexBuffer.MatricesIndicesExtraKind:
  29265. case VertexBuffer.MatricesWeightsKind:
  29266. case VertexBuffer.MatricesWeightsExtraKind:
  29267. case VertexBuffer.TangentKind:
  29268. return 4;
  29269. default:
  29270. throw new Error("Invalid kind '" + kind + "'");
  29271. }
  29272. };
  29273. /**
  29274. * Gets the byte length of the given type.
  29275. * @param type the type
  29276. * @returns the number of bytes
  29277. */
  29278. VertexBuffer.GetTypeByteLength = function (type) {
  29279. switch (type) {
  29280. case VertexBuffer.BYTE:
  29281. case VertexBuffer.UNSIGNED_BYTE:
  29282. return 1;
  29283. case VertexBuffer.SHORT:
  29284. case VertexBuffer.UNSIGNED_SHORT:
  29285. return 2;
  29286. case VertexBuffer.INT:
  29287. case VertexBuffer.FLOAT:
  29288. return 4;
  29289. default:
  29290. throw new Error("Invalid type '" + type + "'");
  29291. }
  29292. };
  29293. /**
  29294. * Enumerates each value of the given parameters as numbers.
  29295. * @param data the data to enumerate
  29296. * @param byteOffset the byte offset of the data
  29297. * @param byteStride the byte stride of the data
  29298. * @param componentCount the number of components per element
  29299. * @param componentType the type of the component
  29300. * @param count the total number of components
  29301. * @param normalized whether the data is normalized
  29302. * @param callback the callback function called for each value
  29303. */
  29304. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29305. if (data instanceof Array) {
  29306. var offset = byteOffset / 4;
  29307. var stride = byteStride / 4;
  29308. for (var index = 0; index < count; index += componentCount) {
  29309. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29310. callback(data[offset + componentIndex], index + componentIndex);
  29311. }
  29312. offset += stride;
  29313. }
  29314. }
  29315. else {
  29316. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29317. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29318. for (var index = 0; index < count; index += componentCount) {
  29319. var componentByteOffset = byteOffset;
  29320. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29321. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29322. callback(value, index + componentIndex);
  29323. componentByteOffset += componentByteLength;
  29324. }
  29325. byteOffset += byteStride;
  29326. }
  29327. }
  29328. };
  29329. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29330. switch (type) {
  29331. case VertexBuffer.BYTE: {
  29332. var value = dataView.getInt8(byteOffset);
  29333. if (normalized) {
  29334. value = Math.max(value / 127, -1);
  29335. }
  29336. return value;
  29337. }
  29338. case VertexBuffer.UNSIGNED_BYTE: {
  29339. var value = dataView.getUint8(byteOffset);
  29340. if (normalized) {
  29341. value = value / 255;
  29342. }
  29343. return value;
  29344. }
  29345. case VertexBuffer.SHORT: {
  29346. var value = dataView.getInt16(byteOffset, true);
  29347. if (normalized) {
  29348. value = Math.max(value / 16383, -1);
  29349. }
  29350. return value;
  29351. }
  29352. case VertexBuffer.UNSIGNED_SHORT: {
  29353. var value = dataView.getUint16(byteOffset, true);
  29354. if (normalized) {
  29355. value = value / 65535;
  29356. }
  29357. return value;
  29358. }
  29359. case VertexBuffer.FLOAT: {
  29360. return dataView.getFloat32(byteOffset, true);
  29361. }
  29362. default: {
  29363. throw new Error("Invalid component type " + type);
  29364. }
  29365. }
  29366. };
  29367. /**
  29368. * The byte type.
  29369. */
  29370. VertexBuffer.BYTE = 5120;
  29371. /**
  29372. * The unsigned byte type.
  29373. */
  29374. VertexBuffer.UNSIGNED_BYTE = 5121;
  29375. /**
  29376. * The short type.
  29377. */
  29378. VertexBuffer.SHORT = 5122;
  29379. /**
  29380. * The unsigned short type.
  29381. */
  29382. VertexBuffer.UNSIGNED_SHORT = 5123;
  29383. /**
  29384. * The integer type.
  29385. */
  29386. VertexBuffer.INT = 5124;
  29387. /**
  29388. * The unsigned integer type.
  29389. */
  29390. VertexBuffer.UNSIGNED_INT = 5125;
  29391. /**
  29392. * The float type.
  29393. */
  29394. VertexBuffer.FLOAT = 5126;
  29395. // Enums
  29396. VertexBuffer._PositionKind = "position";
  29397. VertexBuffer._NormalKind = "normal";
  29398. VertexBuffer._TangentKind = "tangent";
  29399. VertexBuffer._UVKind = "uv";
  29400. VertexBuffer._UV2Kind = "uv2";
  29401. VertexBuffer._UV3Kind = "uv3";
  29402. VertexBuffer._UV4Kind = "uv4";
  29403. VertexBuffer._UV5Kind = "uv5";
  29404. VertexBuffer._UV6Kind = "uv6";
  29405. VertexBuffer._ColorKind = "color";
  29406. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29407. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29408. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29409. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29410. return VertexBuffer;
  29411. }());
  29412. BABYLON.VertexBuffer = VertexBuffer;
  29413. })(BABYLON || (BABYLON = {}));
  29414. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29415. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29416. var BABYLON;
  29417. (function (BABYLON) {
  29418. /**
  29419. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29420. */
  29421. var DummyInternalTextureTracker = /** @class */ (function () {
  29422. function DummyInternalTextureTracker() {
  29423. /**
  29424. * Gets or set the previous tracker in the list
  29425. */
  29426. this.previous = null;
  29427. /**
  29428. * Gets or set the next tracker in the list
  29429. */
  29430. this.next = null;
  29431. }
  29432. return DummyInternalTextureTracker;
  29433. }());
  29434. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29435. })(BABYLON || (BABYLON = {}));
  29436. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29437. var BABYLON;
  29438. (function (BABYLON) {
  29439. /**
  29440. * Class used to store data associated with WebGL texture data for the engine
  29441. * This class should not be used directly
  29442. */
  29443. var InternalTexture = /** @class */ (function () {
  29444. /**
  29445. * Creates a new InternalTexture
  29446. * @param engine defines the engine to use
  29447. * @param dataSource defines the type of data that will be used
  29448. */
  29449. function InternalTexture(engine, dataSource) {
  29450. /**
  29451. * Observable called when the texture is loaded
  29452. */
  29453. this.onLoadedObservable = new BABYLON.Observable();
  29454. /**
  29455. * Gets or set the previous tracker in the list
  29456. */
  29457. this.previous = null;
  29458. /**
  29459. * Gets or set the next tracker in the list
  29460. */
  29461. this.next = null;
  29462. // Private
  29463. /** @hidden */
  29464. this._initialSlot = -1;
  29465. /** @hidden */
  29466. this._designatedSlot = -1;
  29467. /** @hidden */
  29468. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29469. /** @hidden */
  29470. this._comparisonFunction = 0;
  29471. /** @hidden */
  29472. this._sphericalPolynomial = null;
  29473. /** @hidden */
  29474. this._lodGenerationScale = 0;
  29475. /** @hidden */
  29476. this._lodGenerationOffset = 0;
  29477. /** @hidden */
  29478. this._isRGBD = false;
  29479. /** @hidden */
  29480. this._references = 1;
  29481. this._engine = engine;
  29482. this._dataSource = dataSource;
  29483. this._webGLTexture = engine._createTexture();
  29484. }
  29485. /**
  29486. * Gets the Engine the texture belongs to.
  29487. * @returns The babylon engine
  29488. */
  29489. InternalTexture.prototype.getEngine = function () {
  29490. return this._engine;
  29491. };
  29492. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29493. /**
  29494. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29495. */
  29496. get: function () {
  29497. return this._dataSource;
  29498. },
  29499. enumerable: true,
  29500. configurable: true
  29501. });
  29502. /**
  29503. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29504. */
  29505. InternalTexture.prototype.incrementReferences = function () {
  29506. this._references++;
  29507. };
  29508. /**
  29509. * Change the size of the texture (not the size of the content)
  29510. * @param width defines the new width
  29511. * @param height defines the new height
  29512. * @param depth defines the new depth (1 by default)
  29513. */
  29514. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29515. if (depth === void 0) { depth = 1; }
  29516. this.width = width;
  29517. this.height = height;
  29518. this.depth = depth;
  29519. this.baseWidth = width;
  29520. this.baseHeight = height;
  29521. this.baseDepth = depth;
  29522. this._size = width * height * depth;
  29523. };
  29524. /** @hidden */
  29525. InternalTexture.prototype._rebuild = function () {
  29526. var _this = this;
  29527. var proxy;
  29528. this.isReady = false;
  29529. this._cachedCoordinatesMode = null;
  29530. this._cachedWrapU = null;
  29531. this._cachedWrapV = null;
  29532. this._cachedAnisotropicFilteringLevel = null;
  29533. switch (this._dataSource) {
  29534. case InternalTexture.DATASOURCE_TEMP:
  29535. return;
  29536. case InternalTexture.DATASOURCE_URL:
  29537. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29538. _this.isReady = true;
  29539. }, null, this._buffer, undefined, this.format);
  29540. proxy._swapAndDie(this);
  29541. return;
  29542. case InternalTexture.DATASOURCE_RAW:
  29543. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29544. proxy._swapAndDie(this);
  29545. this.isReady = true;
  29546. return;
  29547. case InternalTexture.DATASOURCE_RAW3D:
  29548. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29549. proxy._swapAndDie(this);
  29550. this.isReady = true;
  29551. return;
  29552. case InternalTexture.DATASOURCE_DYNAMIC:
  29553. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29554. proxy._swapAndDie(this);
  29555. // The engine will make sure to update content so no need to flag it as isReady = true
  29556. return;
  29557. case InternalTexture.DATASOURCE_RENDERTARGET:
  29558. var options = new BABYLON.RenderTargetCreationOptions();
  29559. options.generateDepthBuffer = this._generateDepthBuffer;
  29560. options.generateMipMaps = this.generateMipMaps;
  29561. options.generateStencilBuffer = this._generateStencilBuffer;
  29562. options.samplingMode = this.samplingMode;
  29563. options.type = this.type;
  29564. if (this.isCube) {
  29565. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29566. }
  29567. else {
  29568. var size = {
  29569. width: this.width,
  29570. height: this.height
  29571. };
  29572. proxy = this._engine.createRenderTargetTexture(size, options);
  29573. }
  29574. proxy._swapAndDie(this);
  29575. this.isReady = true;
  29576. return;
  29577. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29578. var depthTextureOptions = {
  29579. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29580. comparisonFunction: this._comparisonFunction,
  29581. generateStencil: this._generateStencilBuffer,
  29582. isCube: this.isCube
  29583. };
  29584. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29585. proxy._swapAndDie(this);
  29586. this.isReady = true;
  29587. return;
  29588. case InternalTexture.DATASOURCE_CUBE:
  29589. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29590. _this.isReady = true;
  29591. }, null, this.format, this._extension);
  29592. proxy._swapAndDie(this);
  29593. return;
  29594. case InternalTexture.DATASOURCE_CUBERAW:
  29595. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29596. proxy._swapAndDie(this);
  29597. this.isReady = true;
  29598. return;
  29599. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29600. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29601. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29602. _this.isReady = true;
  29603. });
  29604. proxy._swapAndDie(this);
  29605. return;
  29606. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29607. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29608. if (proxy) {
  29609. proxy._swapAndDie(_this);
  29610. }
  29611. _this.isReady = true;
  29612. }, null, this.format, this._extension);
  29613. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29614. return;
  29615. }
  29616. };
  29617. /** @hidden */
  29618. InternalTexture.prototype._swapAndDie = function (target) {
  29619. target._webGLTexture = this._webGLTexture;
  29620. if (this._framebuffer) {
  29621. target._framebuffer = this._framebuffer;
  29622. }
  29623. if (this._depthStencilBuffer) {
  29624. target._depthStencilBuffer = this._depthStencilBuffer;
  29625. }
  29626. if (this._lodTextureHigh) {
  29627. if (target._lodTextureHigh) {
  29628. target._lodTextureHigh.dispose();
  29629. }
  29630. target._lodTextureHigh = this._lodTextureHigh;
  29631. }
  29632. if (this._lodTextureMid) {
  29633. if (target._lodTextureMid) {
  29634. target._lodTextureMid.dispose();
  29635. }
  29636. target._lodTextureMid = this._lodTextureMid;
  29637. }
  29638. if (this._lodTextureLow) {
  29639. if (target._lodTextureLow) {
  29640. target._lodTextureLow.dispose();
  29641. }
  29642. target._lodTextureLow = this._lodTextureLow;
  29643. }
  29644. var cache = this._engine.getLoadedTexturesCache();
  29645. var index = cache.indexOf(this);
  29646. if (index !== -1) {
  29647. cache.splice(index, 1);
  29648. }
  29649. };
  29650. /**
  29651. * Dispose the current allocated resources
  29652. */
  29653. InternalTexture.prototype.dispose = function () {
  29654. if (!this._webGLTexture) {
  29655. return;
  29656. }
  29657. this._references--;
  29658. if (this._references === 0) {
  29659. this._engine._releaseTexture(this);
  29660. this._webGLTexture = null;
  29661. this.previous = null;
  29662. this.next = null;
  29663. }
  29664. };
  29665. /**
  29666. * The source of the texture data is unknown
  29667. */
  29668. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29669. /**
  29670. * Texture data comes from an URL
  29671. */
  29672. InternalTexture.DATASOURCE_URL = 1;
  29673. /**
  29674. * Texture data is only used for temporary storage
  29675. */
  29676. InternalTexture.DATASOURCE_TEMP = 2;
  29677. /**
  29678. * Texture data comes from raw data (ArrayBuffer)
  29679. */
  29680. InternalTexture.DATASOURCE_RAW = 3;
  29681. /**
  29682. * Texture content is dynamic (video or dynamic texture)
  29683. */
  29684. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29685. /**
  29686. * Texture content is generated by rendering to it
  29687. */
  29688. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29689. /**
  29690. * Texture content is part of a multi render target process
  29691. */
  29692. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29693. /**
  29694. * Texture data comes from a cube data file
  29695. */
  29696. InternalTexture.DATASOURCE_CUBE = 7;
  29697. /**
  29698. * Texture data comes from a raw cube data
  29699. */
  29700. InternalTexture.DATASOURCE_CUBERAW = 8;
  29701. /**
  29702. * Texture data come from a prefiltered cube data file
  29703. */
  29704. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29705. /**
  29706. * Texture content is raw 3D data
  29707. */
  29708. InternalTexture.DATASOURCE_RAW3D = 10;
  29709. /**
  29710. * Texture content is a depth texture
  29711. */
  29712. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29713. /**
  29714. * Texture data comes from a raw cube data encoded with RGBD
  29715. */
  29716. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29717. return InternalTexture;
  29718. }());
  29719. BABYLON.InternalTexture = InternalTexture;
  29720. })(BABYLON || (BABYLON = {}));
  29721. //# sourceMappingURL=babylon.internalTexture.js.map
  29722. var BABYLON;
  29723. (function (BABYLON) {
  29724. var BaseTexture = /** @class */ (function () {
  29725. function BaseTexture(scene) {
  29726. this._hasAlpha = false;
  29727. this.getAlphaFromRGB = false;
  29728. this.level = 1;
  29729. this.coordinatesIndex = 0;
  29730. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29731. /**
  29732. * | Value | Type | Description |
  29733. * | ----- | ------------------ | ----------- |
  29734. * | 0 | CLAMP_ADDRESSMODE | |
  29735. * | 1 | WRAP_ADDRESSMODE | |
  29736. * | 2 | MIRROR_ADDRESSMODE | |
  29737. */
  29738. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29739. /**
  29740. * | Value | Type | Description |
  29741. * | ----- | ------------------ | ----------- |
  29742. * | 0 | CLAMP_ADDRESSMODE | |
  29743. * | 1 | WRAP_ADDRESSMODE | |
  29744. * | 2 | MIRROR_ADDRESSMODE | |
  29745. */
  29746. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29747. /**
  29748. * | Value | Type | Description |
  29749. * | ----- | ------------------ | ----------- |
  29750. * | 0 | CLAMP_ADDRESSMODE | |
  29751. * | 1 | WRAP_ADDRESSMODE | |
  29752. * | 2 | MIRROR_ADDRESSMODE | |
  29753. */
  29754. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29755. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29756. this.isCube = false;
  29757. this.is3D = false;
  29758. this.gammaSpace = true;
  29759. this.invertZ = false;
  29760. this.lodLevelInAlpha = false;
  29761. this.isRenderTarget = false;
  29762. this.animations = new Array();
  29763. /**
  29764. * An event triggered when the texture is disposed.
  29765. */
  29766. this.onDisposeObservable = new BABYLON.Observable();
  29767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29768. this._cachedSize = BABYLON.Size.Zero();
  29769. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29770. if (this._scene) {
  29771. this._scene.textures.push(this);
  29772. }
  29773. this._uid = null;
  29774. }
  29775. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29776. get: function () {
  29777. return this._hasAlpha;
  29778. },
  29779. set: function (value) {
  29780. if (this._hasAlpha === value) {
  29781. return;
  29782. }
  29783. this._hasAlpha = value;
  29784. if (this._scene) {
  29785. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29786. }
  29787. },
  29788. enumerable: true,
  29789. configurable: true
  29790. });
  29791. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29792. get: function () {
  29793. return this._coordinatesMode;
  29794. },
  29795. /**
  29796. * How a texture is mapped.
  29797. *
  29798. * | Value | Type | Description |
  29799. * | ----- | ----------------------------------- | ----------- |
  29800. * | 0 | EXPLICIT_MODE | |
  29801. * | 1 | SPHERICAL_MODE | |
  29802. * | 2 | PLANAR_MODE | |
  29803. * | 3 | CUBIC_MODE | |
  29804. * | 4 | PROJECTION_MODE | |
  29805. * | 5 | SKYBOX_MODE | |
  29806. * | 6 | INVCUBIC_MODE | |
  29807. * | 7 | EQUIRECTANGULAR_MODE | |
  29808. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29809. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29810. */
  29811. set: function (value) {
  29812. if (this._coordinatesMode === value) {
  29813. return;
  29814. }
  29815. this._coordinatesMode = value;
  29816. if (this._scene) {
  29817. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29818. }
  29819. },
  29820. enumerable: true,
  29821. configurable: true
  29822. });
  29823. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29824. /**
  29825. * Gets whether or not the texture contains RGBD data.
  29826. */
  29827. get: function () {
  29828. return this._texture != null && this._texture._isRGBD;
  29829. },
  29830. enumerable: true,
  29831. configurable: true
  29832. });
  29833. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29834. get: function () {
  29835. if (this._texture)
  29836. return this._texture._lodGenerationOffset;
  29837. return 0.0;
  29838. },
  29839. set: function (value) {
  29840. if (this._texture)
  29841. this._texture._lodGenerationOffset = value;
  29842. },
  29843. enumerable: true,
  29844. configurable: true
  29845. });
  29846. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29847. get: function () {
  29848. if (this._texture)
  29849. return this._texture._lodGenerationScale;
  29850. return 0.0;
  29851. },
  29852. set: function (value) {
  29853. if (this._texture)
  29854. this._texture._lodGenerationScale = value;
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. Object.defineProperty(BaseTexture.prototype, "uid", {
  29860. get: function () {
  29861. if (!this._uid) {
  29862. this._uid = BABYLON.Tools.RandomId();
  29863. }
  29864. return this._uid;
  29865. },
  29866. enumerable: true,
  29867. configurable: true
  29868. });
  29869. BaseTexture.prototype.toString = function () {
  29870. return this.name;
  29871. };
  29872. BaseTexture.prototype.getClassName = function () {
  29873. return "BaseTexture";
  29874. };
  29875. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29876. set: function (callback) {
  29877. if (this._onDisposeObserver) {
  29878. this.onDisposeObservable.remove(this._onDisposeObserver);
  29879. }
  29880. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29881. },
  29882. enumerable: true,
  29883. configurable: true
  29884. });
  29885. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29886. get: function () {
  29887. return true;
  29888. },
  29889. enumerable: true,
  29890. configurable: true
  29891. });
  29892. BaseTexture.prototype.getScene = function () {
  29893. return this._scene;
  29894. };
  29895. BaseTexture.prototype.getTextureMatrix = function () {
  29896. return BABYLON.Matrix.IdentityReadOnly;
  29897. };
  29898. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29899. return BABYLON.Matrix.IdentityReadOnly;
  29900. };
  29901. BaseTexture.prototype.getInternalTexture = function () {
  29902. return this._texture;
  29903. };
  29904. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29905. return !this.isBlocking || this.isReady();
  29906. };
  29907. BaseTexture.prototype.isReady = function () {
  29908. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29909. this.delayLoad();
  29910. return false;
  29911. }
  29912. if (this._texture) {
  29913. return this._texture.isReady;
  29914. }
  29915. return false;
  29916. };
  29917. BaseTexture.prototype.getSize = function () {
  29918. if (this._texture) {
  29919. if (this._texture.width) {
  29920. this._cachedSize.width = this._texture.width;
  29921. this._cachedSize.height = this._texture.height;
  29922. return this._cachedSize;
  29923. }
  29924. if (this._texture._size) {
  29925. this._cachedSize.width = this._texture._size;
  29926. this._cachedSize.height = this._texture._size;
  29927. return this._cachedSize;
  29928. }
  29929. }
  29930. return this._cachedSize;
  29931. };
  29932. BaseTexture.prototype.getBaseSize = function () {
  29933. if (!this.isReady() || !this._texture)
  29934. return BABYLON.Size.Zero();
  29935. if (this._texture._size) {
  29936. return new BABYLON.Size(this._texture._size, this._texture._size);
  29937. }
  29938. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29939. };
  29940. BaseTexture.prototype.scale = function (ratio) {
  29941. };
  29942. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29943. get: function () {
  29944. return false;
  29945. },
  29946. enumerable: true,
  29947. configurable: true
  29948. });
  29949. /** @hidden */
  29950. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29951. if (!this._scene) {
  29952. return null;
  29953. }
  29954. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29955. for (var index = 0; index < texturesCache.length; index++) {
  29956. var texturesCacheEntry = texturesCache[index];
  29957. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29958. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29959. texturesCacheEntry.incrementReferences();
  29960. return texturesCacheEntry;
  29961. }
  29962. }
  29963. }
  29964. return null;
  29965. };
  29966. /** @hidden */
  29967. BaseTexture.prototype._rebuild = function () {
  29968. };
  29969. BaseTexture.prototype.delayLoad = function () {
  29970. };
  29971. BaseTexture.prototype.clone = function () {
  29972. return null;
  29973. };
  29974. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29975. get: function () {
  29976. if (!this._texture) {
  29977. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29978. }
  29979. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29980. },
  29981. enumerable: true,
  29982. configurable: true
  29983. });
  29984. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29985. get: function () {
  29986. if (!this._texture) {
  29987. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29988. }
  29989. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29990. },
  29991. enumerable: true,
  29992. configurable: true
  29993. });
  29994. /**
  29995. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  29996. * This will returns an RGBA array buffer containing either in values (0-255) or
  29997. * float values (0-1) depending of the underlying buffer type.
  29998. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  29999. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30000. * @param buffer defines a user defined buffer to fill with data (can be null)
  30001. * @returns The Array buffer containing the pixels data.
  30002. */
  30003. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30004. if (faceIndex === void 0) { faceIndex = 0; }
  30005. if (level === void 0) { level = 0; }
  30006. if (buffer === void 0) { buffer = null; }
  30007. if (!this._texture) {
  30008. return null;
  30009. }
  30010. var size = this.getSize();
  30011. var width = size.width;
  30012. var height = size.height;
  30013. var scene = this.getScene();
  30014. if (!scene) {
  30015. return null;
  30016. }
  30017. var engine = scene.getEngine();
  30018. if (level != 0) {
  30019. width = width / Math.pow(2, level);
  30020. height = height / Math.pow(2, level);
  30021. width = Math.round(width);
  30022. height = Math.round(height);
  30023. }
  30024. if (this._texture.isCube) {
  30025. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30026. }
  30027. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30028. };
  30029. BaseTexture.prototype.releaseInternalTexture = function () {
  30030. if (this._texture) {
  30031. this._texture.dispose();
  30032. this._texture = null;
  30033. }
  30034. };
  30035. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30036. get: function () {
  30037. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30038. return null;
  30039. }
  30040. if (!this._texture._sphericalPolynomial) {
  30041. this._texture._sphericalPolynomial =
  30042. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30043. }
  30044. return this._texture._sphericalPolynomial;
  30045. },
  30046. set: function (value) {
  30047. if (this._texture) {
  30048. this._texture._sphericalPolynomial = value;
  30049. }
  30050. },
  30051. enumerable: true,
  30052. configurable: true
  30053. });
  30054. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30055. get: function () {
  30056. if (this._texture) {
  30057. return this._texture._lodTextureHigh;
  30058. }
  30059. return null;
  30060. },
  30061. enumerable: true,
  30062. configurable: true
  30063. });
  30064. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30065. get: function () {
  30066. if (this._texture) {
  30067. return this._texture._lodTextureMid;
  30068. }
  30069. return null;
  30070. },
  30071. enumerable: true,
  30072. configurable: true
  30073. });
  30074. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30075. get: function () {
  30076. if (this._texture) {
  30077. return this._texture._lodTextureLow;
  30078. }
  30079. return null;
  30080. },
  30081. enumerable: true,
  30082. configurable: true
  30083. });
  30084. BaseTexture.prototype.dispose = function () {
  30085. if (!this._scene) {
  30086. return;
  30087. }
  30088. // Animations
  30089. this._scene.stopAnimation(this);
  30090. // Remove from scene
  30091. this._scene._removePendingData(this);
  30092. var index = this._scene.textures.indexOf(this);
  30093. if (index >= 0) {
  30094. this._scene.textures.splice(index, 1);
  30095. }
  30096. if (this._texture === undefined) {
  30097. return;
  30098. }
  30099. // Release
  30100. this.releaseInternalTexture();
  30101. // Callback
  30102. this.onDisposeObservable.notifyObservers(this);
  30103. this.onDisposeObservable.clear();
  30104. };
  30105. BaseTexture.prototype.serialize = function () {
  30106. if (!this.name) {
  30107. return null;
  30108. }
  30109. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30110. // Animations
  30111. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30112. return serializationObject;
  30113. };
  30114. BaseTexture.WhenAllReady = function (textures, callback) {
  30115. var numRemaining = textures.length;
  30116. if (numRemaining === 0) {
  30117. callback();
  30118. return;
  30119. }
  30120. var _loop_1 = function () {
  30121. texture = textures[i];
  30122. if (texture.isReady()) {
  30123. if (--numRemaining === 0) {
  30124. callback();
  30125. }
  30126. }
  30127. else {
  30128. onLoadObservable = texture.onLoadObservable;
  30129. var onLoadCallback_1 = function () {
  30130. onLoadObservable.removeCallback(onLoadCallback_1);
  30131. if (--numRemaining === 0) {
  30132. callback();
  30133. }
  30134. };
  30135. onLoadObservable.add(onLoadCallback_1);
  30136. }
  30137. };
  30138. var texture, onLoadObservable;
  30139. for (var i = 0; i < textures.length; i++) {
  30140. _loop_1();
  30141. }
  30142. };
  30143. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30144. __decorate([
  30145. BABYLON.serialize()
  30146. ], BaseTexture.prototype, "name", void 0);
  30147. __decorate([
  30148. BABYLON.serialize("hasAlpha")
  30149. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30150. __decorate([
  30151. BABYLON.serialize()
  30152. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30153. __decorate([
  30154. BABYLON.serialize()
  30155. ], BaseTexture.prototype, "level", void 0);
  30156. __decorate([
  30157. BABYLON.serialize()
  30158. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30159. __decorate([
  30160. BABYLON.serialize("coordinatesMode")
  30161. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30162. __decorate([
  30163. BABYLON.serialize()
  30164. ], BaseTexture.prototype, "wrapU", void 0);
  30165. __decorate([
  30166. BABYLON.serialize()
  30167. ], BaseTexture.prototype, "wrapV", void 0);
  30168. __decorate([
  30169. BABYLON.serialize()
  30170. ], BaseTexture.prototype, "wrapR", void 0);
  30171. __decorate([
  30172. BABYLON.serialize()
  30173. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30174. __decorate([
  30175. BABYLON.serialize()
  30176. ], BaseTexture.prototype, "isCube", void 0);
  30177. __decorate([
  30178. BABYLON.serialize()
  30179. ], BaseTexture.prototype, "is3D", void 0);
  30180. __decorate([
  30181. BABYLON.serialize()
  30182. ], BaseTexture.prototype, "gammaSpace", void 0);
  30183. __decorate([
  30184. BABYLON.serialize()
  30185. ], BaseTexture.prototype, "invertZ", void 0);
  30186. __decorate([
  30187. BABYLON.serialize()
  30188. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30189. __decorate([
  30190. BABYLON.serialize()
  30191. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30192. __decorate([
  30193. BABYLON.serialize()
  30194. ], BaseTexture.prototype, "lodGenerationScale", null);
  30195. __decorate([
  30196. BABYLON.serialize()
  30197. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30198. return BaseTexture;
  30199. }());
  30200. BABYLON.BaseTexture = BaseTexture;
  30201. })(BABYLON || (BABYLON = {}));
  30202. //# sourceMappingURL=babylon.baseTexture.js.map
  30203. var BABYLON;
  30204. (function (BABYLON) {
  30205. var Texture = /** @class */ (function (_super) {
  30206. __extends(Texture, _super);
  30207. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30208. if (noMipmap === void 0) { noMipmap = false; }
  30209. if (invertY === void 0) { invertY = true; }
  30210. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30211. if (onLoad === void 0) { onLoad = null; }
  30212. if (onError === void 0) { onError = null; }
  30213. if (buffer === void 0) { buffer = null; }
  30214. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30215. var _this = _super.call(this, scene) || this;
  30216. _this.uOffset = 0;
  30217. _this.vOffset = 0;
  30218. _this.uScale = 1.0;
  30219. _this.vScale = 1.0;
  30220. _this.uAng = 0;
  30221. _this.vAng = 0;
  30222. _this.wAng = 0;
  30223. /**
  30224. * Defines the center of rotation (U)
  30225. */
  30226. _this.uRotationCenter = 0.5;
  30227. /**
  30228. * Defines the center of rotation (V)
  30229. */
  30230. _this.vRotationCenter = 0.5;
  30231. /**
  30232. * Defines the center of rotation (W)
  30233. */
  30234. _this.wRotationCenter = 0.5;
  30235. _this._isBlocking = true;
  30236. _this.name = url || "";
  30237. _this.url = url;
  30238. _this._noMipmap = noMipmap;
  30239. _this._invertY = invertY;
  30240. _this._samplingMode = samplingMode;
  30241. _this._buffer = buffer;
  30242. _this._deleteBuffer = deleteBuffer;
  30243. if (format) {
  30244. _this._format = format;
  30245. }
  30246. scene = _this.getScene();
  30247. if (!scene) {
  30248. return _this;
  30249. }
  30250. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30251. var load = function () {
  30252. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30253. _this.onLoadObservable.notifyObservers(_this);
  30254. }
  30255. if (onLoad) {
  30256. onLoad();
  30257. }
  30258. if (!_this.isBlocking && scene) {
  30259. scene.resetCachedMaterial();
  30260. }
  30261. };
  30262. if (!_this.url) {
  30263. _this._delayedOnLoad = load;
  30264. _this._delayedOnError = onError;
  30265. return _this;
  30266. }
  30267. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30268. if (!_this._texture) {
  30269. if (!scene.useDelayedTextureLoading) {
  30270. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30271. if (deleteBuffer) {
  30272. delete _this._buffer;
  30273. }
  30274. }
  30275. else {
  30276. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30277. _this._delayedOnLoad = load;
  30278. _this._delayedOnError = onError;
  30279. }
  30280. }
  30281. else {
  30282. if (_this._texture.isReady) {
  30283. BABYLON.Tools.SetImmediate(function () { return load(); });
  30284. }
  30285. else {
  30286. _this._texture.onLoadedObservable.add(load);
  30287. }
  30288. }
  30289. return _this;
  30290. }
  30291. Object.defineProperty(Texture.prototype, "noMipmap", {
  30292. get: function () {
  30293. return this._noMipmap;
  30294. },
  30295. enumerable: true,
  30296. configurable: true
  30297. });
  30298. Object.defineProperty(Texture.prototype, "isBlocking", {
  30299. get: function () {
  30300. return this._isBlocking;
  30301. },
  30302. set: function (value) {
  30303. this._isBlocking = value;
  30304. },
  30305. enumerable: true,
  30306. configurable: true
  30307. });
  30308. Object.defineProperty(Texture.prototype, "samplingMode", {
  30309. get: function () {
  30310. return this._samplingMode;
  30311. },
  30312. enumerable: true,
  30313. configurable: true
  30314. });
  30315. /**
  30316. * Update the url (and optional buffer) of this texture if url was null during construction.
  30317. * @param url the url of the texture
  30318. * @param buffer the buffer of the texture (defaults to null)
  30319. */
  30320. Texture.prototype.updateURL = function (url, buffer) {
  30321. if (buffer === void 0) { buffer = null; }
  30322. if (this.url) {
  30323. throw new Error("URL is already set");
  30324. }
  30325. this.url = url;
  30326. this._buffer = buffer;
  30327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30328. this.delayLoad();
  30329. };
  30330. Texture.prototype.delayLoad = function () {
  30331. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30332. return;
  30333. }
  30334. var scene = this.getScene();
  30335. if (!scene) {
  30336. return;
  30337. }
  30338. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30339. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30340. if (!this._texture) {
  30341. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30342. if (this._deleteBuffer) {
  30343. delete this._buffer;
  30344. }
  30345. }
  30346. else {
  30347. if (this._delayedOnLoad) {
  30348. if (this._texture.isReady) {
  30349. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30350. }
  30351. else {
  30352. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30353. }
  30354. }
  30355. }
  30356. this._delayedOnLoad = null;
  30357. this._delayedOnError = null;
  30358. };
  30359. /**
  30360. * Default is Trilinear mode.
  30361. *
  30362. * | Value | Type | Description |
  30363. * | ----- | ------------------ | ----------- |
  30364. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30365. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30366. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30367. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30368. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30369. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30370. * | 7 | NEAREST_LINEAR | |
  30371. * | 8 | NEAREST_NEAREST | |
  30372. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30373. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30374. * | 11 | LINEAR_LINEAR | |
  30375. * | 12 | LINEAR_NEAREST | |
  30376. *
  30377. * > _mag_: magnification filter (close to the viewer)
  30378. * > _min_: minification filter (far from the viewer)
  30379. * > _mip_: filter used between mip map levels
  30380. *
  30381. */
  30382. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30383. if (!this._texture) {
  30384. return;
  30385. }
  30386. var scene = this.getScene();
  30387. if (!scene) {
  30388. return;
  30389. }
  30390. this._samplingMode = samplingMode;
  30391. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30392. };
  30393. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30394. x *= this.uScale;
  30395. y *= this.vScale;
  30396. x -= this.uRotationCenter * this.uScale;
  30397. y -= this.vRotationCenter * this.vScale;
  30398. z -= this.wRotationCenter;
  30399. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30400. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30401. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30402. t.z += this.wRotationCenter;
  30403. };
  30404. Texture.prototype.getTextureMatrix = function () {
  30405. var _this = this;
  30406. if (this.uOffset === this._cachedUOffset &&
  30407. this.vOffset === this._cachedVOffset &&
  30408. this.uScale === this._cachedUScale &&
  30409. this.vScale === this._cachedVScale &&
  30410. this.uAng === this._cachedUAng &&
  30411. this.vAng === this._cachedVAng &&
  30412. this.wAng === this._cachedWAng) {
  30413. return this._cachedTextureMatrix;
  30414. }
  30415. this._cachedUOffset = this.uOffset;
  30416. this._cachedVOffset = this.vOffset;
  30417. this._cachedUScale = this.uScale;
  30418. this._cachedVScale = this.vScale;
  30419. this._cachedUAng = this.uAng;
  30420. this._cachedVAng = this.vAng;
  30421. this._cachedWAng = this.wAng;
  30422. if (!this._cachedTextureMatrix) {
  30423. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30424. this._rowGenerationMatrix = new BABYLON.Matrix();
  30425. this._t0 = BABYLON.Vector3.Zero();
  30426. this._t1 = BABYLON.Vector3.Zero();
  30427. this._t2 = BABYLON.Vector3.Zero();
  30428. }
  30429. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30430. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30431. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30432. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30433. this._t1.subtractInPlace(this._t0);
  30434. this._t2.subtractInPlace(this._t0);
  30435. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30436. this._cachedTextureMatrix.m[0] = this._t1.x;
  30437. this._cachedTextureMatrix.m[1] = this._t1.y;
  30438. this._cachedTextureMatrix.m[2] = this._t1.z;
  30439. this._cachedTextureMatrix.m[4] = this._t2.x;
  30440. this._cachedTextureMatrix.m[5] = this._t2.y;
  30441. this._cachedTextureMatrix.m[6] = this._t2.z;
  30442. this._cachedTextureMatrix.m[8] = this._t0.x;
  30443. this._cachedTextureMatrix.m[9] = this._t0.y;
  30444. this._cachedTextureMatrix.m[10] = this._t0.z;
  30445. var scene = this.getScene();
  30446. if (!scene) {
  30447. return this._cachedTextureMatrix;
  30448. }
  30449. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30450. return mat.hasTexture(_this);
  30451. });
  30452. return this._cachedTextureMatrix;
  30453. };
  30454. Texture.prototype.getReflectionTextureMatrix = function () {
  30455. var _this = this;
  30456. var scene = this.getScene();
  30457. if (!scene) {
  30458. return this._cachedTextureMatrix;
  30459. }
  30460. if (this.uOffset === this._cachedUOffset &&
  30461. this.vOffset === this._cachedVOffset &&
  30462. this.uScale === this._cachedUScale &&
  30463. this.vScale === this._cachedVScale &&
  30464. this.coordinatesMode === this._cachedCoordinatesMode) {
  30465. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30466. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30467. return this._cachedTextureMatrix;
  30468. }
  30469. }
  30470. else {
  30471. return this._cachedTextureMatrix;
  30472. }
  30473. }
  30474. if (!this._cachedTextureMatrix) {
  30475. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30476. }
  30477. if (!this._projectionModeMatrix) {
  30478. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30479. }
  30480. this._cachedUOffset = this.uOffset;
  30481. this._cachedVOffset = this.vOffset;
  30482. this._cachedUScale = this.uScale;
  30483. this._cachedVScale = this.vScale;
  30484. this._cachedCoordinatesMode = this.coordinatesMode;
  30485. switch (this.coordinatesMode) {
  30486. case Texture.PLANAR_MODE:
  30487. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30488. this._cachedTextureMatrix[0] = this.uScale;
  30489. this._cachedTextureMatrix[5] = this.vScale;
  30490. this._cachedTextureMatrix[12] = this.uOffset;
  30491. this._cachedTextureMatrix[13] = this.vOffset;
  30492. break;
  30493. case Texture.PROJECTION_MODE:
  30494. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30495. this._projectionModeMatrix.m[0] = 0.5;
  30496. this._projectionModeMatrix.m[5] = -0.5;
  30497. this._projectionModeMatrix.m[10] = 0.0;
  30498. this._projectionModeMatrix.m[12] = 0.5;
  30499. this._projectionModeMatrix.m[13] = 0.5;
  30500. this._projectionModeMatrix.m[14] = 1.0;
  30501. this._projectionModeMatrix.m[15] = 1.0;
  30502. var projectionMatrix = scene.getProjectionMatrix();
  30503. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30504. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30505. break;
  30506. default:
  30507. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30508. break;
  30509. }
  30510. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30511. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30512. });
  30513. return this._cachedTextureMatrix;
  30514. };
  30515. Texture.prototype.clone = function () {
  30516. var _this = this;
  30517. return BABYLON.SerializationHelper.Clone(function () {
  30518. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30519. }, this);
  30520. };
  30521. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30522. get: function () {
  30523. if (!this._onLoadObservable) {
  30524. this._onLoadObservable = new BABYLON.Observable();
  30525. }
  30526. return this._onLoadObservable;
  30527. },
  30528. enumerable: true,
  30529. configurable: true
  30530. });
  30531. Texture.prototype.serialize = function () {
  30532. var serializationObject = _super.prototype.serialize.call(this);
  30533. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30534. serializationObject.base64String = this._buffer;
  30535. serializationObject.name = serializationObject.name.replace("data:", "");
  30536. }
  30537. serializationObject.invertY = this._invertY;
  30538. serializationObject.samplingMode = this.samplingMode;
  30539. return serializationObject;
  30540. };
  30541. Texture.prototype.getClassName = function () {
  30542. return "Texture";
  30543. };
  30544. Texture.prototype.dispose = function () {
  30545. _super.prototype.dispose.call(this);
  30546. if (this._onLoadObservable) {
  30547. this._onLoadObservable.clear();
  30548. this._onLoadObservable = null;
  30549. }
  30550. this._delayedOnLoad = null;
  30551. this._delayedOnError = null;
  30552. };
  30553. // Statics
  30554. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30555. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30556. if (onLoad === void 0) { onLoad = null; }
  30557. if (onError === void 0) { onError = null; }
  30558. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30559. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30560. };
  30561. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30562. if (parsedTexture.customType) {
  30563. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30564. // Update Sampling Mode
  30565. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30566. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30567. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30568. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30569. }
  30570. }
  30571. return parsedCustomTexture;
  30572. }
  30573. if (parsedTexture.isCube) {
  30574. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30575. }
  30576. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30577. return null;
  30578. }
  30579. var texture = BABYLON.SerializationHelper.Parse(function () {
  30580. var generateMipMaps = true;
  30581. if (parsedTexture.noMipmap) {
  30582. generateMipMaps = false;
  30583. }
  30584. if (parsedTexture.mirrorPlane) {
  30585. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30586. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30587. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30588. return mirrorTexture;
  30589. }
  30590. else if (parsedTexture.isRenderTarget) {
  30591. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30592. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30593. return renderTargetTexture;
  30594. }
  30595. else {
  30596. var texture;
  30597. if (parsedTexture.base64String) {
  30598. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30599. }
  30600. else {
  30601. var url = rootUrl + parsedTexture.name;
  30602. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30603. url = parsedTexture.url;
  30604. }
  30605. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30606. }
  30607. return texture;
  30608. }
  30609. }, parsedTexture, scene);
  30610. // Update Sampling Mode
  30611. if (parsedTexture.samplingMode) {
  30612. var sampling = parsedTexture.samplingMode;
  30613. if (texture._samplingMode !== sampling) {
  30614. texture.updateSamplingMode(sampling);
  30615. }
  30616. }
  30617. // Animations
  30618. if (parsedTexture.animations) {
  30619. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30620. var parsedAnimation = parsedTexture.animations[animationIndex];
  30621. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30622. }
  30623. }
  30624. return texture;
  30625. };
  30626. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30627. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30628. if (noMipmap === void 0) { noMipmap = false; }
  30629. if (invertY === void 0) { invertY = true; }
  30630. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30631. if (onLoad === void 0) { onLoad = null; }
  30632. if (onError === void 0) { onError = null; }
  30633. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30634. if (name.substr(0, 5) !== "data:") {
  30635. name = "data:" + name;
  30636. }
  30637. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30638. };
  30639. // Constants
  30640. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30641. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30642. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30643. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30644. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30645. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30646. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30647. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30648. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30649. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30650. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30651. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30652. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30653. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30654. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30655. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30656. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30657. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30658. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30659. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30660. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30661. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30662. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30663. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30664. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30665. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30666. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30667. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30668. /**
  30669. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  30670. */
  30671. Texture.UseSerializedUrlIfAny = false;
  30672. __decorate([
  30673. BABYLON.serialize()
  30674. ], Texture.prototype, "url", void 0);
  30675. __decorate([
  30676. BABYLON.serialize()
  30677. ], Texture.prototype, "uOffset", void 0);
  30678. __decorate([
  30679. BABYLON.serialize()
  30680. ], Texture.prototype, "vOffset", void 0);
  30681. __decorate([
  30682. BABYLON.serialize()
  30683. ], Texture.prototype, "uScale", void 0);
  30684. __decorate([
  30685. BABYLON.serialize()
  30686. ], Texture.prototype, "vScale", void 0);
  30687. __decorate([
  30688. BABYLON.serialize()
  30689. ], Texture.prototype, "uAng", void 0);
  30690. __decorate([
  30691. BABYLON.serialize()
  30692. ], Texture.prototype, "vAng", void 0);
  30693. __decorate([
  30694. BABYLON.serialize()
  30695. ], Texture.prototype, "wAng", void 0);
  30696. __decorate([
  30697. BABYLON.serialize()
  30698. ], Texture.prototype, "uRotationCenter", void 0);
  30699. __decorate([
  30700. BABYLON.serialize()
  30701. ], Texture.prototype, "vRotationCenter", void 0);
  30702. __decorate([
  30703. BABYLON.serialize()
  30704. ], Texture.prototype, "wRotationCenter", void 0);
  30705. __decorate([
  30706. BABYLON.serialize()
  30707. ], Texture.prototype, "isBlocking", null);
  30708. return Texture;
  30709. }(BABYLON.BaseTexture));
  30710. BABYLON.Texture = Texture;
  30711. })(BABYLON || (BABYLON = {}));
  30712. //# sourceMappingURL=babylon.texture.js.map
  30713. var BABYLON;
  30714. (function (BABYLON) {
  30715. /**
  30716. * @hidden
  30717. **/
  30718. var _InstancesBatch = /** @class */ (function () {
  30719. function _InstancesBatch() {
  30720. this.mustReturn = false;
  30721. this.visibleInstances = new Array();
  30722. this.renderSelf = new Array();
  30723. }
  30724. return _InstancesBatch;
  30725. }());
  30726. BABYLON._InstancesBatch = _InstancesBatch;
  30727. /**
  30728. * Class used to represent renderable models
  30729. */
  30730. var Mesh = /** @class */ (function (_super) {
  30731. __extends(Mesh, _super);
  30732. /**
  30733. * @constructor
  30734. * @param name The value used by scene.getMeshByName() to do a lookup.
  30735. * @param scene The scene to add this mesh to.
  30736. * @param parent The parent of this mesh, if it has one
  30737. * @param source An optional Mesh from which geometry is shared, cloned.
  30738. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30739. * When false, achieved by calling a clone(), also passing False.
  30740. * This will make creation of children, recursive.
  30741. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30742. */
  30743. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30744. if (scene === void 0) { scene = null; }
  30745. if (parent === void 0) { parent = null; }
  30746. if (source === void 0) { source = null; }
  30747. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30748. var _this = _super.call(this, name, scene) || this;
  30749. // Members
  30750. /**
  30751. * Gets the delay loading state of the mesh (when delay loading is turned on)
  30752. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  30753. */
  30754. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30755. /**
  30756. * Gets the list of instances created from this mesh
  30757. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  30758. */
  30759. _this.instances = new Array();
  30760. _this._LODLevels = new Array();
  30761. /** @hidden */
  30762. _this._visibleInstances = {};
  30763. _this._renderIdForInstances = new Array();
  30764. _this._batchCache = new _InstancesBatch();
  30765. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30766. // Use by builder only to know what orientation were the mesh build in.
  30767. /** @hidden */
  30768. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  30769. /**
  30770. * Use this property to change the original side orientation defined at construction time
  30771. */
  30772. _this.overrideMaterialSideOrientation = null;
  30773. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30774. // Will be used to save a source mesh reference, If any
  30775. _this._source = null;
  30776. scene = _this.getScene();
  30777. if (source) {
  30778. // Geometry
  30779. if (source._geometry) {
  30780. source._geometry.applyToMesh(_this);
  30781. }
  30782. // Deep copy
  30783. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30784. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30785. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30786. ], ["_poseMatrix"]);
  30787. // Source mesh
  30788. _this._source = source;
  30789. // Construction Params
  30790. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30791. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30792. var myAnyThis = _this;
  30793. var myAnySource = source;
  30794. myAnyThis._closePath = myAnySource._closePath;
  30795. myAnyThis._idx = myAnySource._idx;
  30796. myAnyThis.dashSize = myAnySource.dashSize;
  30797. myAnyThis.gapSize = myAnySource.gapSize;
  30798. myAnyThis.path3D = myAnySource.path3D;
  30799. myAnyThis.pathArray = myAnySource.pathArray;
  30800. myAnyThis.arc = myAnySource.arc;
  30801. myAnyThis.radius = myAnySource.radius;
  30802. // Animation ranges
  30803. if (_this._source._ranges) {
  30804. var ranges = _this._source._ranges;
  30805. for (var name in ranges) {
  30806. if (!ranges.hasOwnProperty(name)) {
  30807. continue;
  30808. }
  30809. if (!ranges[name]) {
  30810. continue;
  30811. }
  30812. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30813. }
  30814. }
  30815. // Metadata
  30816. if (source.metadata && source.metadata.clone) {
  30817. _this.metadata = source.metadata.clone();
  30818. }
  30819. else {
  30820. _this.metadata = source.metadata;
  30821. }
  30822. // Tags
  30823. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30824. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30825. }
  30826. // Parent
  30827. _this.parent = source.parent;
  30828. // Pivot
  30829. _this.setPivotMatrix(source.getPivotMatrix());
  30830. _this.id = name + "." + source.id;
  30831. // Material
  30832. _this.material = source.material;
  30833. var index;
  30834. if (!doNotCloneChildren) {
  30835. // Children
  30836. var directDescendants = source.getDescendants(true);
  30837. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30838. var child = directDescendants[index_1];
  30839. if (child.clone) {
  30840. child.clone(name + "." + child.name, _this);
  30841. }
  30842. }
  30843. }
  30844. // Physics clone
  30845. var physicsEngine = _this.getScene().getPhysicsEngine();
  30846. if (clonePhysicsImpostor && physicsEngine) {
  30847. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30848. if (impostor) {
  30849. _this.physicsImpostor = impostor.clone(_this);
  30850. }
  30851. }
  30852. // Particles
  30853. for (index = 0; index < scene.particleSystems.length; index++) {
  30854. var system = scene.particleSystems[index];
  30855. if (system.emitter === source) {
  30856. system.clone(system.name, _this);
  30857. }
  30858. }
  30859. _this.refreshBoundingInfo();
  30860. _this.computeWorldMatrix(true);
  30861. }
  30862. // Parent
  30863. if (parent !== null) {
  30864. _this.parent = parent;
  30865. }
  30866. return _this;
  30867. }
  30868. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30869. /**
  30870. * An event triggered before rendering the mesh
  30871. */
  30872. get: function () {
  30873. if (!this._onBeforeRenderObservable) {
  30874. this._onBeforeRenderObservable = new BABYLON.Observable();
  30875. }
  30876. return this._onBeforeRenderObservable;
  30877. },
  30878. enumerable: true,
  30879. configurable: true
  30880. });
  30881. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30882. /**
  30883. * An event triggered after rendering the mesh
  30884. */
  30885. get: function () {
  30886. if (!this._onAfterRenderObservable) {
  30887. this._onAfterRenderObservable = new BABYLON.Observable();
  30888. }
  30889. return this._onAfterRenderObservable;
  30890. },
  30891. enumerable: true,
  30892. configurable: true
  30893. });
  30894. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30895. /**
  30896. * An event triggered before drawing the mesh
  30897. */
  30898. get: function () {
  30899. if (!this._onBeforeDrawObservable) {
  30900. this._onBeforeDrawObservable = new BABYLON.Observable();
  30901. }
  30902. return this._onBeforeDrawObservable;
  30903. },
  30904. enumerable: true,
  30905. configurable: true
  30906. });
  30907. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30908. /**
  30909. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  30910. */
  30911. set: function (callback) {
  30912. if (this._onBeforeDrawObserver) {
  30913. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30914. }
  30915. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30916. },
  30917. enumerable: true,
  30918. configurable: true
  30919. });
  30920. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30921. /**
  30922. * Gets or sets the morph target manager
  30923. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  30924. */
  30925. get: function () {
  30926. return this._morphTargetManager;
  30927. },
  30928. set: function (value) {
  30929. if (this._morphTargetManager === value) {
  30930. return;
  30931. }
  30932. this._morphTargetManager = value;
  30933. this._syncGeometryWithMorphTargetManager();
  30934. },
  30935. enumerable: true,
  30936. configurable: true
  30937. });
  30938. Object.defineProperty(Mesh.prototype, "source", {
  30939. /**
  30940. * Gets the source mesh (the one used to clone this one from)
  30941. */
  30942. get: function () {
  30943. return this._source;
  30944. },
  30945. enumerable: true,
  30946. configurable: true
  30947. });
  30948. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30949. /**
  30950. * Gets or sets a boolean indicating that this mesh does not use index buffer
  30951. */
  30952. get: function () {
  30953. return this._unIndexed;
  30954. },
  30955. set: function (value) {
  30956. if (this._unIndexed !== value) {
  30957. this._unIndexed = value;
  30958. this._markSubMeshesAsAttributesDirty();
  30959. }
  30960. },
  30961. enumerable: true,
  30962. configurable: true
  30963. });
  30964. // Methods
  30965. /**
  30966. * Gets the class name
  30967. * @returns the string "Mesh".
  30968. */
  30969. Mesh.prototype.getClassName = function () {
  30970. return "Mesh";
  30971. };
  30972. /**
  30973. * Returns a description of this mesh
  30974. * @param fullDetails define if full details about this mesh must be used
  30975. * @returns a descriptive string representing this mesh
  30976. */
  30977. Mesh.prototype.toString = function (fullDetails) {
  30978. var ret = _super.prototype.toString.call(this, fullDetails);
  30979. ret += ", n vertices: " + this.getTotalVertices();
  30980. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30981. if (this.animations) {
  30982. for (var i = 0; i < this.animations.length; i++) {
  30983. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30984. }
  30985. }
  30986. if (fullDetails) {
  30987. if (this._geometry) {
  30988. var ib = this.getIndices();
  30989. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30990. if (vb && ib) {
  30991. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30992. }
  30993. }
  30994. else {
  30995. ret += ", flat shading: UNKNOWN";
  30996. }
  30997. }
  30998. return ret;
  30999. };
  31000. /** @hidden */
  31001. Mesh.prototype._unBindEffect = function () {
  31002. _super.prototype._unBindEffect.call(this);
  31003. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31004. var instance = _a[_i];
  31005. instance._unBindEffect();
  31006. }
  31007. };
  31008. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31009. /**
  31010. * Gets a boolean indicating if this mesh has LOD
  31011. */
  31012. get: function () {
  31013. return this._LODLevels.length > 0;
  31014. },
  31015. enumerable: true,
  31016. configurable: true
  31017. });
  31018. /**
  31019. * Gets the list of MeshLODLevel associated with the current mesh
  31020. * @returns an array of MeshLODLevel
  31021. */
  31022. Mesh.prototype.getLODLevels = function () {
  31023. return this._LODLevels;
  31024. };
  31025. Mesh.prototype._sortLODLevels = function () {
  31026. this._LODLevels.sort(function (a, b) {
  31027. if (a.distance < b.distance) {
  31028. return 1;
  31029. }
  31030. if (a.distance > b.distance) {
  31031. return -1;
  31032. }
  31033. return 0;
  31034. });
  31035. };
  31036. /**
  31037. * Add a mesh as LOD level triggered at the given distance.
  31038. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31039. * @param distance The distance from the center of the object to show this level
  31040. * @param mesh The mesh to be added as LOD level (can be null)
  31041. * @return This mesh (for chaining)
  31042. */
  31043. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31044. if (mesh && mesh._masterMesh) {
  31045. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31046. return this;
  31047. }
  31048. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31049. this._LODLevels.push(level);
  31050. if (mesh) {
  31051. mesh._masterMesh = this;
  31052. }
  31053. this._sortLODLevels();
  31054. return this;
  31055. };
  31056. /**
  31057. * Returns the LOD level mesh at the passed distance or null if not found.
  31058. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31059. * @param distance The distance from the center of the object to show this level
  31060. * @returns a Mesh or `null`
  31061. */
  31062. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31063. for (var index = 0; index < this._LODLevels.length; index++) {
  31064. var level = this._LODLevels[index];
  31065. if (level.distance === distance) {
  31066. return level.mesh;
  31067. }
  31068. }
  31069. return null;
  31070. };
  31071. /**
  31072. * Remove a mesh from the LOD array
  31073. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31074. * @param mesh defines the mesh to be removed
  31075. * @return This mesh (for chaining)
  31076. */
  31077. Mesh.prototype.removeLODLevel = function (mesh) {
  31078. for (var index = 0; index < this._LODLevels.length; index++) {
  31079. if (this._LODLevels[index].mesh === mesh) {
  31080. this._LODLevels.splice(index, 1);
  31081. if (mesh) {
  31082. mesh._masterMesh = null;
  31083. }
  31084. }
  31085. }
  31086. this._sortLODLevels();
  31087. return this;
  31088. };
  31089. /**
  31090. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31091. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31092. * @param camera defines the camera to use to compute distance
  31093. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31094. * @return This mesh (for chaining)
  31095. */
  31096. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31097. if (!this._LODLevels || this._LODLevels.length === 0) {
  31098. return this;
  31099. }
  31100. var bSphere;
  31101. if (boundingSphere) {
  31102. bSphere = boundingSphere;
  31103. }
  31104. else {
  31105. var boundingInfo = this.getBoundingInfo();
  31106. bSphere = boundingInfo.boundingSphere;
  31107. }
  31108. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31109. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31110. if (this.onLODLevelSelection) {
  31111. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31112. }
  31113. return this;
  31114. }
  31115. for (var index = 0; index < this._LODLevels.length; index++) {
  31116. var level = this._LODLevels[index];
  31117. if (level.distance < distanceToCamera) {
  31118. if (level.mesh) {
  31119. level.mesh._preActivate();
  31120. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31121. }
  31122. if (this.onLODLevelSelection) {
  31123. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31124. }
  31125. return level.mesh;
  31126. }
  31127. }
  31128. if (this.onLODLevelSelection) {
  31129. this.onLODLevelSelection(distanceToCamera, this, this);
  31130. }
  31131. return this;
  31132. };
  31133. Object.defineProperty(Mesh.prototype, "geometry", {
  31134. /**
  31135. * Gets the mesh internal Geometry object
  31136. */
  31137. get: function () {
  31138. return this._geometry;
  31139. },
  31140. enumerable: true,
  31141. configurable: true
  31142. });
  31143. /**
  31144. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31145. * @returns the total number of vertices
  31146. */
  31147. Mesh.prototype.getTotalVertices = function () {
  31148. if (this._geometry === null || this._geometry === undefined) {
  31149. return 0;
  31150. }
  31151. return this._geometry.getTotalVertices();
  31152. };
  31153. /**
  31154. * Returns the content of an associated vertex buffer
  31155. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31156. * - BABYLON.VertexBuffer.PositionKind
  31157. * - BABYLON.VertexBuffer.UVKind
  31158. * - BABYLON.VertexBuffer.UV2Kind
  31159. * - BABYLON.VertexBuffer.UV3Kind
  31160. * - BABYLON.VertexBuffer.UV4Kind
  31161. * - BABYLON.VertexBuffer.UV5Kind
  31162. * - BABYLON.VertexBuffer.UV6Kind
  31163. * - BABYLON.VertexBuffer.ColorKind
  31164. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31165. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31166. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31167. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31168. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  31169. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31170. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31171. */
  31172. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31173. if (!this._geometry) {
  31174. return null;
  31175. }
  31176. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31177. };
  31178. /**
  31179. * Returns the mesh VertexBuffer object from the requested `kind`
  31180. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31181. * - BABYLON.VertexBuffer.PositionKind
  31182. * - BABYLON.VertexBuffer.UVKind
  31183. * - BABYLON.VertexBuffer.UV2Kind
  31184. * - BABYLON.VertexBuffer.UV3Kind
  31185. * - BABYLON.VertexBuffer.UV4Kind
  31186. * - BABYLON.VertexBuffer.UV5Kind
  31187. * - BABYLON.VertexBuffer.UV6Kind
  31188. * - BABYLON.VertexBuffer.ColorKind
  31189. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31190. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31191. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31192. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31193. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31194. */
  31195. Mesh.prototype.getVertexBuffer = function (kind) {
  31196. if (!this._geometry) {
  31197. return null;
  31198. }
  31199. return this._geometry.getVertexBuffer(kind);
  31200. };
  31201. /**
  31202. * Tests if a specific vertex buffer is associated with this mesh
  31203. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31204. * - BABYLON.VertexBuffer.PositionKind
  31205. * - BABYLON.VertexBuffer.UVKind
  31206. * - BABYLON.VertexBuffer.UV2Kind
  31207. * - BABYLON.VertexBuffer.UV3Kind
  31208. * - BABYLON.VertexBuffer.UV4Kind
  31209. * - BABYLON.VertexBuffer.UV5Kind
  31210. * - BABYLON.VertexBuffer.UV6Kind
  31211. * - BABYLON.VertexBuffer.ColorKind
  31212. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31213. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31214. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31215. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31216. * @returns a boolean
  31217. */
  31218. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31219. if (!this._geometry) {
  31220. if (this._delayInfo) {
  31221. return this._delayInfo.indexOf(kind) !== -1;
  31222. }
  31223. return false;
  31224. }
  31225. return this._geometry.isVerticesDataPresent(kind);
  31226. };
  31227. /**
  31228. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31229. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31230. * - BABYLON.VertexBuffer.PositionKind
  31231. * - BABYLON.VertexBuffer.UVKind
  31232. * - BABYLON.VertexBuffer.UV2Kind
  31233. * - BABYLON.VertexBuffer.UV3Kind
  31234. * - BABYLON.VertexBuffer.UV4Kind
  31235. * - BABYLON.VertexBuffer.UV5Kind
  31236. * - BABYLON.VertexBuffer.UV6Kind
  31237. * - BABYLON.VertexBuffer.ColorKind
  31238. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31239. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31240. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31241. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31242. * @returns a boolean
  31243. */
  31244. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31245. if (!this._geometry) {
  31246. if (this._delayInfo) {
  31247. return this._delayInfo.indexOf(kind) !== -1;
  31248. }
  31249. return false;
  31250. }
  31251. return this._geometry.isVertexBufferUpdatable(kind);
  31252. };
  31253. /**
  31254. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31255. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31256. * - BABYLON.VertexBuffer.PositionKind
  31257. * - BABYLON.VertexBuffer.UVKind
  31258. * - BABYLON.VertexBuffer.UV2Kind
  31259. * - BABYLON.VertexBuffer.UV3Kind
  31260. * - BABYLON.VertexBuffer.UV4Kind
  31261. * - BABYLON.VertexBuffer.UV5Kind
  31262. * - BABYLON.VertexBuffer.UV6Kind
  31263. * - BABYLON.VertexBuffer.ColorKind
  31264. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31265. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31266. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31267. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31268. * @returns an array of strings
  31269. */
  31270. Mesh.prototype.getVerticesDataKinds = function () {
  31271. if (!this._geometry) {
  31272. var result = new Array();
  31273. if (this._delayInfo) {
  31274. this._delayInfo.forEach(function (kind, index, array) {
  31275. result.push(kind);
  31276. });
  31277. }
  31278. return result;
  31279. }
  31280. return this._geometry.getVerticesDataKinds();
  31281. };
  31282. /**
  31283. * Returns a positive integer : the total number of indices in this mesh geometry.
  31284. * @returns the numner of indices or zero if the mesh has no geometry.
  31285. */
  31286. Mesh.prototype.getTotalIndices = function () {
  31287. if (!this._geometry) {
  31288. return 0;
  31289. }
  31290. return this._geometry.getTotalIndices();
  31291. };
  31292. /**
  31293. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31294. * @param copyWhenShared If 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.
  31295. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31296. * @returns the indices array or an empty array if the mesh has no geometry
  31297. */
  31298. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31299. if (!this._geometry) {
  31300. return [];
  31301. }
  31302. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31303. };
  31304. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31305. get: function () {
  31306. return this._masterMesh !== null && this._masterMesh !== undefined;
  31307. },
  31308. enumerable: true,
  31309. configurable: true
  31310. });
  31311. /**
  31312. * Determine if the current mesh is ready to be rendered
  31313. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31314. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31315. * @returns true if all associated assets are ready (material, textures, shaders)
  31316. */
  31317. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31318. if (completeCheck === void 0) { completeCheck = false; }
  31319. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31320. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31321. return false;
  31322. }
  31323. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31324. return false;
  31325. }
  31326. if (!this.subMeshes || this.subMeshes.length === 0) {
  31327. return true;
  31328. }
  31329. if (!completeCheck) {
  31330. return true;
  31331. }
  31332. var engine = this.getEngine();
  31333. var scene = this.getScene();
  31334. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31335. this.computeWorldMatrix();
  31336. var mat = this.material || scene.defaultMaterial;
  31337. if (mat) {
  31338. if (mat.storeEffectOnSubMeshes) {
  31339. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31340. var subMesh = _a[_i];
  31341. var effectiveMaterial = subMesh.getMaterial();
  31342. if (effectiveMaterial) {
  31343. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31344. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31345. return false;
  31346. }
  31347. }
  31348. else {
  31349. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31350. return false;
  31351. }
  31352. }
  31353. }
  31354. }
  31355. }
  31356. else {
  31357. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31358. return false;
  31359. }
  31360. }
  31361. }
  31362. // Shadows
  31363. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31364. var light = _c[_b];
  31365. var generator = light.getShadowGenerator();
  31366. if (generator) {
  31367. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31368. var subMesh = _e[_d];
  31369. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31370. return false;
  31371. }
  31372. }
  31373. }
  31374. }
  31375. // LOD
  31376. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31377. var lod = _g[_f];
  31378. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31379. return false;
  31380. }
  31381. }
  31382. return true;
  31383. };
  31384. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31385. /**
  31386. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  31387. */
  31388. get: function () {
  31389. return this._areNormalsFrozen;
  31390. },
  31391. enumerable: true,
  31392. configurable: true
  31393. });
  31394. /**
  31395. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  31396. * @returns the current mesh
  31397. */
  31398. Mesh.prototype.freezeNormals = function () {
  31399. this._areNormalsFrozen = true;
  31400. return this;
  31401. };
  31402. /**
  31403. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  31404. * @returns the current mesh
  31405. */
  31406. Mesh.prototype.unfreezeNormals = function () {
  31407. this._areNormalsFrozen = false;
  31408. return this;
  31409. };
  31410. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31411. /**
  31412. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31413. */
  31414. set: function (count) {
  31415. this._overridenInstanceCount = count;
  31416. },
  31417. enumerable: true,
  31418. configurable: true
  31419. });
  31420. // Methods
  31421. /** @hidden */
  31422. Mesh.prototype._preActivate = function () {
  31423. var sceneRenderId = this.getScene().getRenderId();
  31424. if (this._preActivateId === sceneRenderId) {
  31425. return this;
  31426. }
  31427. this._preActivateId = sceneRenderId;
  31428. this._visibleInstances = null;
  31429. return this;
  31430. };
  31431. /** @hidden */
  31432. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31433. if (this._visibleInstances) {
  31434. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31435. }
  31436. return this;
  31437. };
  31438. /** @hidden */
  31439. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31440. if (!this._visibleInstances) {
  31441. this._visibleInstances = {};
  31442. this._visibleInstances.defaultRenderId = renderId;
  31443. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31444. }
  31445. if (!this._visibleInstances[renderId]) {
  31446. this._visibleInstances[renderId] = new Array();
  31447. }
  31448. this._visibleInstances[renderId].push(instance);
  31449. return this;
  31450. };
  31451. /**
  31452. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31453. * This means the mesh underlying bounding box and sphere are recomputed.
  31454. * @returns the current mesh
  31455. */
  31456. Mesh.prototype.refreshBoundingInfo = function () {
  31457. return this._refreshBoundingInfo(false);
  31458. };
  31459. /** @hidden */
  31460. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31461. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31462. return this;
  31463. }
  31464. var data = this._getPositionData(applySkeleton);
  31465. if (data) {
  31466. var bias = this.geometry ? this.geometry.boundingBias : null;
  31467. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31468. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31469. }
  31470. if (this.subMeshes) {
  31471. for (var index = 0; index < this.subMeshes.length; index++) {
  31472. this.subMeshes[index].refreshBoundingInfo();
  31473. }
  31474. }
  31475. this._updateBoundingInfo();
  31476. return this;
  31477. };
  31478. Mesh.prototype._getPositionData = function (applySkeleton) {
  31479. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31480. if (data && applySkeleton && this.skeleton) {
  31481. data = BABYLON.Tools.Slice(data);
  31482. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31483. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31484. if (matricesWeightsData && matricesIndicesData) {
  31485. var needExtras = this.numBoneInfluencers > 4;
  31486. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31487. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31488. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31489. var tempVector = BABYLON.Tmp.Vector3[0];
  31490. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31491. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31492. var matWeightIdx = 0;
  31493. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31494. finalMatrix.reset();
  31495. var inf;
  31496. var weight;
  31497. for (inf = 0; inf < 4; inf++) {
  31498. weight = matricesWeightsData[matWeightIdx + inf];
  31499. if (weight > 0) {
  31500. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31501. finalMatrix.addToSelf(tempMatrix);
  31502. }
  31503. }
  31504. if (needExtras) {
  31505. for (inf = 0; inf < 4; inf++) {
  31506. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31507. if (weight > 0) {
  31508. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31509. finalMatrix.addToSelf(tempMatrix);
  31510. }
  31511. }
  31512. }
  31513. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31514. tempVector.toArray(data, index);
  31515. }
  31516. }
  31517. }
  31518. return data;
  31519. };
  31520. /** @hidden */
  31521. Mesh.prototype._createGlobalSubMesh = function (force) {
  31522. var totalVertices = this.getTotalVertices();
  31523. if (!totalVertices || !this.getIndices()) {
  31524. return null;
  31525. }
  31526. // Check if we need to recreate the submeshes
  31527. if (this.subMeshes && this.subMeshes.length > 0) {
  31528. var ib = this.getIndices();
  31529. if (!ib) {
  31530. return null;
  31531. }
  31532. var totalIndices = ib.length;
  31533. var needToRecreate = false;
  31534. if (force) {
  31535. needToRecreate = true;
  31536. }
  31537. else {
  31538. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31539. var submesh = _a[_i];
  31540. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31541. needToRecreate = true;
  31542. break;
  31543. }
  31544. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31545. needToRecreate = true;
  31546. break;
  31547. }
  31548. }
  31549. }
  31550. if (!needToRecreate) {
  31551. return this.subMeshes[0];
  31552. }
  31553. }
  31554. this.releaseSubMeshes();
  31555. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31556. };
  31557. /**
  31558. * This function will subdivide the mesh into multiple submeshes
  31559. * @param count defines the expected number of submeshes
  31560. */
  31561. Mesh.prototype.subdivide = function (count) {
  31562. if (count < 1) {
  31563. return;
  31564. }
  31565. var totalIndices = this.getTotalIndices();
  31566. var subdivisionSize = (totalIndices / count) | 0;
  31567. var offset = 0;
  31568. // Ensure that subdivisionSize is a multiple of 3
  31569. while (subdivisionSize % 3 !== 0) {
  31570. subdivisionSize++;
  31571. }
  31572. this.releaseSubMeshes();
  31573. for (var index = 0; index < count; index++) {
  31574. if (offset >= totalIndices) {
  31575. break;
  31576. }
  31577. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31578. offset += subdivisionSize;
  31579. }
  31580. this.synchronizeInstances();
  31581. };
  31582. /**
  31583. * Copy a FloatArray into a specific associated vertex buffer
  31584. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31585. * - BABYLON.VertexBuffer.PositionKind
  31586. * - BABYLON.VertexBuffer.UVKind
  31587. * - BABYLON.VertexBuffer.UV2Kind
  31588. * - BABYLON.VertexBuffer.UV3Kind
  31589. * - BABYLON.VertexBuffer.UV4Kind
  31590. * - BABYLON.VertexBuffer.UV5Kind
  31591. * - BABYLON.VertexBuffer.UV6Kind
  31592. * - BABYLON.VertexBuffer.ColorKind
  31593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31597. * @param data defines the data source
  31598. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31599. * @param stride defines the data stride size (can be null)
  31600. * @returns the current mesh
  31601. */
  31602. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31603. if (updatable === void 0) { updatable = false; }
  31604. if (!this._geometry) {
  31605. var vertexData = new BABYLON.VertexData();
  31606. vertexData.set(data, kind);
  31607. var scene = this.getScene();
  31608. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31609. }
  31610. else {
  31611. this._geometry.setVerticesData(kind, data, updatable, stride);
  31612. }
  31613. return this;
  31614. };
  31615. /**
  31616. * Flags an associated vertex buffer as updatable
  31617. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  31618. * - BABYLON.VertexBuffer.PositionKind
  31619. * - BABYLON.VertexBuffer.UVKind
  31620. * - BABYLON.VertexBuffer.UV2Kind
  31621. * - BABYLON.VertexBuffer.UV3Kind
  31622. * - BABYLON.VertexBuffer.UV4Kind
  31623. * - BABYLON.VertexBuffer.UV5Kind
  31624. * - BABYLON.VertexBuffer.UV6Kind
  31625. * - BABYLON.VertexBuffer.ColorKind
  31626. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31627. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31628. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31629. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31630. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31631. */
  31632. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31633. if (updatable === void 0) { updatable = true; }
  31634. var vb = this.getVertexBuffer(kind);
  31635. if (!vb || vb.isUpdatable() === updatable) {
  31636. return;
  31637. }
  31638. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31639. };
  31640. /**
  31641. * Sets the mesh global Vertex Buffer
  31642. * @param buffer defines the buffer to use
  31643. * @returns the current mesh
  31644. */
  31645. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31646. if (!this._geometry) {
  31647. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31648. }
  31649. this._geometry.setVerticesBuffer(buffer);
  31650. return this;
  31651. };
  31652. /**
  31653. * Update a specific associated vertex buffer
  31654. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31655. * - BABYLON.VertexBuffer.PositionKind
  31656. * - BABYLON.VertexBuffer.UVKind
  31657. * - BABYLON.VertexBuffer.UV2Kind
  31658. * - BABYLON.VertexBuffer.UV3Kind
  31659. * - BABYLON.VertexBuffer.UV4Kind
  31660. * - BABYLON.VertexBuffer.UV5Kind
  31661. * - BABYLON.VertexBuffer.UV6Kind
  31662. * - BABYLON.VertexBuffer.ColorKind
  31663. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31664. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31665. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31666. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31667. * @param data defines the data source
  31668. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  31669. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  31670. * @returns the current mesh
  31671. */
  31672. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31673. if (!this._geometry) {
  31674. return this;
  31675. }
  31676. if (!makeItUnique) {
  31677. this._geometry.updateVerticesData(kind, data, updateExtends);
  31678. }
  31679. else {
  31680. this.makeGeometryUnique();
  31681. this.updateVerticesData(kind, data, updateExtends, false);
  31682. }
  31683. return this;
  31684. };
  31685. /**
  31686. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31687. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31688. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  31689. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  31690. * @returns the current mesh
  31691. */
  31692. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31693. if (computeNormals === void 0) { computeNormals = true; }
  31694. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31695. if (!positions) {
  31696. return this;
  31697. }
  31698. positionFunction(positions);
  31699. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31700. if (computeNormals) {
  31701. var indices = this.getIndices();
  31702. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31703. if (!normals) {
  31704. return this;
  31705. }
  31706. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31707. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31708. }
  31709. return this;
  31710. };
  31711. /**
  31712. * Creates a un-shared specific occurence of the geometry for the mesh.
  31713. * @returns the current mesh
  31714. */
  31715. Mesh.prototype.makeGeometryUnique = function () {
  31716. if (!this._geometry) {
  31717. return this;
  31718. }
  31719. var oldGeometry = this._geometry;
  31720. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31721. oldGeometry.releaseForMesh(this, true);
  31722. geometry.applyToMesh(this);
  31723. return this;
  31724. };
  31725. /**
  31726. * Set the index buffer of this mesh
  31727. * @param indices defines the source data
  31728. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  31729. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  31730. * @returns the current mesh
  31731. */
  31732. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31733. if (totalVertices === void 0) { totalVertices = null; }
  31734. if (updatable === void 0) { updatable = false; }
  31735. if (!this._geometry) {
  31736. var vertexData = new BABYLON.VertexData();
  31737. vertexData.indices = indices;
  31738. var scene = this.getScene();
  31739. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31740. }
  31741. else {
  31742. this._geometry.setIndices(indices, totalVertices, updatable);
  31743. }
  31744. return this;
  31745. };
  31746. /**
  31747. * Update the current index buffer
  31748. * @param indices defines the source data
  31749. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  31750. * @returns the current mesh
  31751. */
  31752. Mesh.prototype.updateIndices = function (indices, offset) {
  31753. if (!this._geometry) {
  31754. return this;
  31755. }
  31756. this._geometry.updateIndices(indices, offset);
  31757. return this;
  31758. };
  31759. /**
  31760. * Invert the geometry to move from a right handed system to a left handed one.
  31761. * @returns the current mesh
  31762. */
  31763. Mesh.prototype.toLeftHanded = function () {
  31764. if (!this._geometry) {
  31765. return this;
  31766. }
  31767. this._geometry.toLeftHanded();
  31768. return this;
  31769. };
  31770. /** @hidden */
  31771. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31772. if (!this._geometry) {
  31773. return this;
  31774. }
  31775. var engine = this.getScene().getEngine();
  31776. // Wireframe
  31777. var indexToBind;
  31778. if (this._unIndexed) {
  31779. indexToBind = null;
  31780. }
  31781. else {
  31782. switch (fillMode) {
  31783. case BABYLON.Material.PointFillMode:
  31784. indexToBind = null;
  31785. break;
  31786. case BABYLON.Material.WireFrameFillMode:
  31787. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31788. break;
  31789. default:
  31790. case BABYLON.Material.TriangleFillMode:
  31791. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31792. break;
  31793. }
  31794. }
  31795. // VBOs
  31796. this._geometry._bind(effect, indexToBind);
  31797. return this;
  31798. };
  31799. /** @hidden */
  31800. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31801. if (alternate === void 0) { alternate = false; }
  31802. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31803. return this;
  31804. }
  31805. if (this._onBeforeDrawObservable) {
  31806. this._onBeforeDrawObservable.notifyObservers(this);
  31807. }
  31808. var scene = this.getScene();
  31809. var engine = scene.getEngine();
  31810. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31811. // or triangles as points
  31812. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31813. }
  31814. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31815. // Triangles as wireframe
  31816. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31817. }
  31818. else {
  31819. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31820. }
  31821. if (scene._isAlternateRenderingEnabled && !alternate) {
  31822. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31823. if (!effect || !scene.activeCamera) {
  31824. return this;
  31825. }
  31826. scene._switchToAlternateCameraConfiguration(true);
  31827. this._effectiveMaterial.bindView(effect);
  31828. this._effectiveMaterial.bindViewProjection(effect);
  31829. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31830. this._draw(subMesh, fillMode, instancesCount, true);
  31831. engine.setViewport(scene.activeCamera.viewport);
  31832. scene._switchToAlternateCameraConfiguration(false);
  31833. this._effectiveMaterial.bindView(effect);
  31834. this._effectiveMaterial.bindViewProjection(effect);
  31835. }
  31836. return this;
  31837. };
  31838. /**
  31839. * Registers for this mesh a javascript function called just before the rendering process
  31840. * @param func defines the function to call before rendering this mesh
  31841. * @returns the current mesh
  31842. */
  31843. Mesh.prototype.registerBeforeRender = function (func) {
  31844. this.onBeforeRenderObservable.add(func);
  31845. return this;
  31846. };
  31847. /**
  31848. * Disposes a previously registered javascript function called before the rendering
  31849. * @param func defines the function to remove
  31850. * @returns the current mesh
  31851. */
  31852. Mesh.prototype.unregisterBeforeRender = function (func) {
  31853. this.onBeforeRenderObservable.removeCallback(func);
  31854. return this;
  31855. };
  31856. /**
  31857. * Registers for this mesh a javascript function called just after the rendering is complete
  31858. * @param func defines the function to call after rendering this mesh
  31859. * @returns the current mesh
  31860. */
  31861. Mesh.prototype.registerAfterRender = function (func) {
  31862. this.onAfterRenderObservable.add(func);
  31863. return this;
  31864. };
  31865. /**
  31866. * Disposes a previously registered javascript function called after the rendering.
  31867. * @param func defines the function to remove
  31868. * @returns the current mesh
  31869. */
  31870. Mesh.prototype.unregisterAfterRender = function (func) {
  31871. this.onAfterRenderObservable.removeCallback(func);
  31872. return this;
  31873. };
  31874. /** @hidden */
  31875. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31876. var scene = this.getScene();
  31877. this._batchCache.mustReturn = false;
  31878. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31879. this._batchCache.visibleInstances[subMeshId] = null;
  31880. if (this._visibleInstances) {
  31881. var currentRenderId = scene.getRenderId();
  31882. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31883. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31884. var selfRenderId = this._renderId;
  31885. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31886. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31887. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31888. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31889. }
  31890. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31891. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31892. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31893. this._batchCache.mustReturn = true;
  31894. return this._batchCache;
  31895. }
  31896. if (currentRenderId !== selfRenderId) {
  31897. this._batchCache.renderSelf[subMeshId] = false;
  31898. }
  31899. }
  31900. this._renderIdForInstances[subMeshId] = currentRenderId;
  31901. }
  31902. return this._batchCache;
  31903. };
  31904. /** @hidden */
  31905. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31906. var visibleInstances = batch.visibleInstances[subMesh._id];
  31907. if (!visibleInstances) {
  31908. return this;
  31909. }
  31910. var matricesCount = visibleInstances.length + 1;
  31911. var bufferSize = matricesCount * 16 * 4;
  31912. var currentInstancesBufferSize = this._instancesBufferSize;
  31913. var instancesBuffer = this._instancesBuffer;
  31914. while (this._instancesBufferSize < bufferSize) {
  31915. this._instancesBufferSize *= 2;
  31916. }
  31917. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31918. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31919. }
  31920. var offset = 0;
  31921. var instancesCount = 0;
  31922. var world = this.getWorldMatrix();
  31923. if (batch.renderSelf[subMesh._id]) {
  31924. world.copyToArray(this._instancesData, offset);
  31925. offset += 16;
  31926. instancesCount++;
  31927. }
  31928. if (visibleInstances) {
  31929. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31930. var instance = visibleInstances[instanceIndex];
  31931. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31932. offset += 16;
  31933. instancesCount++;
  31934. }
  31935. }
  31936. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31937. if (instancesBuffer) {
  31938. instancesBuffer.dispose();
  31939. }
  31940. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31941. this._instancesBuffer = instancesBuffer;
  31942. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31943. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31944. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31945. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31946. }
  31947. else {
  31948. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31949. }
  31950. this._bind(subMesh, effect, fillMode);
  31951. this._draw(subMesh, fillMode, instancesCount);
  31952. engine.unbindInstanceAttributes();
  31953. return this;
  31954. };
  31955. /** @hidden */
  31956. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31957. var scene = this.getScene();
  31958. var engine = scene.getEngine();
  31959. if (hardwareInstancedRendering) {
  31960. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31961. }
  31962. else {
  31963. if (batch.renderSelf[subMesh._id]) {
  31964. // Draw
  31965. if (onBeforeDraw) {
  31966. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31967. }
  31968. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31969. }
  31970. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31971. if (visibleInstancesForSubMesh) {
  31972. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31973. var instance = visibleInstancesForSubMesh[instanceIndex];
  31974. // World
  31975. var world = instance.getWorldMatrix();
  31976. if (onBeforeDraw) {
  31977. onBeforeDraw(true, world, effectiveMaterial);
  31978. }
  31979. // Draw
  31980. this._draw(subMesh, fillMode);
  31981. }
  31982. }
  31983. }
  31984. return this;
  31985. };
  31986. /**
  31987. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  31988. * @param subMesh defines the subMesh to render
  31989. * @param enableAlphaMode defines if alpha mode can be changed
  31990. * @returns the current mesh
  31991. */
  31992. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31993. this._checkOcclusionQuery();
  31994. if (this._isOccluded) {
  31995. return this;
  31996. }
  31997. var scene = this.getScene();
  31998. // Managing instances
  31999. var batch = this._getInstancesRenderList(subMesh._id);
  32000. if (batch.mustReturn) {
  32001. return this;
  32002. }
  32003. // Checking geometry state
  32004. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32005. return this;
  32006. }
  32007. if (this._onBeforeRenderObservable) {
  32008. this._onBeforeRenderObservable.notifyObservers(this);
  32009. }
  32010. var engine = scene.getEngine();
  32011. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32012. // Material
  32013. var material = subMesh.getMaterial();
  32014. if (!material) {
  32015. return this;
  32016. }
  32017. this._effectiveMaterial = material;
  32018. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32019. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32020. return this;
  32021. }
  32022. }
  32023. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32024. return this;
  32025. }
  32026. // Alpha mode
  32027. if (enableAlphaMode) {
  32028. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32029. }
  32030. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32031. var step = _a[_i];
  32032. step.action(this, subMesh, batch);
  32033. }
  32034. var effect;
  32035. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32036. effect = subMesh.effect;
  32037. }
  32038. else {
  32039. effect = this._effectiveMaterial.getEffect();
  32040. }
  32041. if (!effect) {
  32042. return this;
  32043. }
  32044. var sideOrientation = this.overrideMaterialSideOrientation;
  32045. if (sideOrientation == null) {
  32046. sideOrientation = this._effectiveMaterial.sideOrientation;
  32047. if (this._getWorldMatrixDeterminant() < 0) {
  32048. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32049. }
  32050. }
  32051. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32052. if (this._effectiveMaterial.forceDepthWrite) {
  32053. engine.setDepthWrite(true);
  32054. }
  32055. // Bind
  32056. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32057. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32058. this._bind(subMesh, effect, fillMode);
  32059. }
  32060. var world = this.getWorldMatrix();
  32061. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32062. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32063. }
  32064. else {
  32065. this._effectiveMaterial.bind(world, this);
  32066. }
  32067. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32068. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32069. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32070. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32071. }
  32072. // Draw
  32073. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32074. // Unbind
  32075. this._effectiveMaterial.unbind();
  32076. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32077. var step = _c[_b];
  32078. step.action(this, subMesh, batch);
  32079. }
  32080. if (this._onAfterRenderObservable) {
  32081. this._onAfterRenderObservable.notifyObservers(this);
  32082. }
  32083. return this;
  32084. };
  32085. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32086. if (isInstance && effectiveMaterial) {
  32087. effectiveMaterial.bindOnlyWorldMatrix(world);
  32088. }
  32089. };
  32090. /**
  32091. * Normalize matrix weights so that all vertices have a total weight set to 1
  32092. */
  32093. Mesh.prototype.cleanMatrixWeights = function () {
  32094. var epsilon = 1e-3;
  32095. var noInfluenceBoneIndex = 0.0;
  32096. if (this.skeleton) {
  32097. noInfluenceBoneIndex = this.skeleton.bones.length;
  32098. }
  32099. else {
  32100. return;
  32101. }
  32102. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32103. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32104. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32105. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32106. var influencers = this.numBoneInfluencers;
  32107. var size = matricesWeights.length;
  32108. for (var i = 0; i < size; i += 4) {
  32109. var weight = 0.0;
  32110. var firstZeroWeight = -1;
  32111. for (var j = 0; j < 4; j++) {
  32112. var w = matricesWeights[i + j];
  32113. weight += w;
  32114. if (w < epsilon && firstZeroWeight < 0) {
  32115. firstZeroWeight = j;
  32116. }
  32117. }
  32118. if (matricesWeightsExtra) {
  32119. for (var j = 0; j < 4; j++) {
  32120. var w = matricesWeightsExtra[i + j];
  32121. weight += w;
  32122. if (w < epsilon && firstZeroWeight < 0) {
  32123. firstZeroWeight = j + 4;
  32124. }
  32125. }
  32126. }
  32127. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32128. firstZeroWeight = influencers - 1;
  32129. }
  32130. if (weight > epsilon) {
  32131. var mweight = 1.0 / weight;
  32132. for (var j = 0; j < 4; j++) {
  32133. matricesWeights[i + j] *= mweight;
  32134. }
  32135. if (matricesWeightsExtra) {
  32136. for (var j = 0; j < 4; j++) {
  32137. matricesWeightsExtra[i + j] *= mweight;
  32138. }
  32139. }
  32140. }
  32141. else {
  32142. if (firstZeroWeight >= 4) {
  32143. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32144. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32145. }
  32146. else {
  32147. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32148. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32149. }
  32150. }
  32151. }
  32152. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32153. if (matricesIndicesExtra) {
  32154. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32155. }
  32156. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32157. if (matricesWeightsExtra) {
  32158. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32159. }
  32160. };
  32161. /** @hidden */
  32162. Mesh.prototype._checkDelayState = function () {
  32163. var scene = this.getScene();
  32164. if (this._geometry) {
  32165. this._geometry.load(scene);
  32166. }
  32167. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32168. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32169. this._queueLoad(scene);
  32170. }
  32171. return this;
  32172. };
  32173. Mesh.prototype._queueLoad = function (scene) {
  32174. var _this = this;
  32175. scene._addPendingData(this);
  32176. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32177. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32178. if (data instanceof ArrayBuffer) {
  32179. _this._delayLoadingFunction(data, _this);
  32180. }
  32181. else {
  32182. _this._delayLoadingFunction(JSON.parse(data), _this);
  32183. }
  32184. _this.instances.forEach(function (instance) {
  32185. instance._syncSubMeshes();
  32186. });
  32187. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32188. scene._removePendingData(_this);
  32189. }, function () { }, scene.database, getBinaryData);
  32190. return this;
  32191. };
  32192. /**
  32193. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32194. * A mesh is in the frustum if its bounding box intersects the frustum
  32195. * @param frustumPlanes defines the frustum to test
  32196. * @returns true if the mesh is in the frustum planes
  32197. */
  32198. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32199. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32200. return false;
  32201. }
  32202. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32203. return false;
  32204. }
  32205. this._checkDelayState();
  32206. return true;
  32207. };
  32208. /**
  32209. * Sets the mesh material by the material or multiMaterial `id` property
  32210. * @param id is a string identifying the material or the multiMaterial
  32211. * @returns the current mesh
  32212. */
  32213. Mesh.prototype.setMaterialByID = function (id) {
  32214. var materials = this.getScene().materials;
  32215. var index;
  32216. for (index = materials.length - 1; index > -1; index--) {
  32217. if (materials[index].id === id) {
  32218. this.material = materials[index];
  32219. return this;
  32220. }
  32221. }
  32222. // Multi
  32223. var multiMaterials = this.getScene().multiMaterials;
  32224. for (index = multiMaterials.length - 1; index > -1; index--) {
  32225. if (multiMaterials[index].id === id) {
  32226. this.material = multiMaterials[index];
  32227. return this;
  32228. }
  32229. }
  32230. return this;
  32231. };
  32232. /**
  32233. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32234. * @returns an array of IAnimatable
  32235. */
  32236. Mesh.prototype.getAnimatables = function () {
  32237. var results = new Array();
  32238. if (this.material) {
  32239. results.push(this.material);
  32240. }
  32241. if (this.skeleton) {
  32242. results.push(this.skeleton);
  32243. }
  32244. return results;
  32245. };
  32246. /**
  32247. * Modifies the mesh geometry according to the passed transformation matrix.
  32248. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32249. * The mesh normals are modified using the same transformation.
  32250. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32251. * @param transform defines the transform matrix to use
  32252. * @see http://doc.babylonjs.com/resources/baking_transformations
  32253. * @returns the current mesh
  32254. */
  32255. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32256. // Position
  32257. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32258. return this;
  32259. }
  32260. var submeshes = this.subMeshes.splice(0);
  32261. this._resetPointsArrayCache();
  32262. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32263. var temp = new Array();
  32264. var index;
  32265. for (index = 0; index < data.length; index += 3) {
  32266. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32267. }
  32268. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32269. // Normals
  32270. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32271. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32272. temp = [];
  32273. for (index = 0; index < data.length; index += 3) {
  32274. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32275. }
  32276. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32277. }
  32278. // flip faces?
  32279. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32280. this.flipFaces();
  32281. }
  32282. // Restore submeshes
  32283. this.releaseSubMeshes();
  32284. this.subMeshes = submeshes;
  32285. return this;
  32286. };
  32287. /**
  32288. * Modifies the mesh geometry according to its own current World Matrix.
  32289. * The mesh World Matrix is then reset.
  32290. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32291. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32292. * @see http://doc.babylonjs.com/resources/baking_transformations
  32293. * @returns the current mesh
  32294. */
  32295. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32296. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32297. this.scaling.copyFromFloats(1, 1, 1);
  32298. this.position.copyFromFloats(0, 0, 0);
  32299. this.rotation.copyFromFloats(0, 0, 0);
  32300. //only if quaternion is already set
  32301. if (this.rotationQuaternion) {
  32302. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32303. }
  32304. this._worldMatrix = BABYLON.Matrix.Identity();
  32305. return this;
  32306. };
  32307. Object.defineProperty(Mesh.prototype, "_positions", {
  32308. // Cache
  32309. /** @hidden */
  32310. get: function () {
  32311. if (this._geometry) {
  32312. return this._geometry._positions;
  32313. }
  32314. return null;
  32315. },
  32316. enumerable: true,
  32317. configurable: true
  32318. });
  32319. /** @hidden */
  32320. Mesh.prototype._resetPointsArrayCache = function () {
  32321. if (this._geometry) {
  32322. this._geometry._resetPointsArrayCache();
  32323. }
  32324. return this;
  32325. };
  32326. /** @hidden */
  32327. Mesh.prototype._generatePointsArray = function () {
  32328. if (this._geometry) {
  32329. return this._geometry._generatePointsArray();
  32330. }
  32331. return false;
  32332. };
  32333. /**
  32334. * Returns a new Mesh object generated from the current mesh properties.
  32335. * This method must not get confused with createInstance()
  32336. * @param name is a string, the name given to the new mesh
  32337. * @param newParent can be any Node object (default `null`)
  32338. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32339. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32340. * @returns a new mesh
  32341. */
  32342. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32343. if (name === void 0) { name = ""; }
  32344. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32345. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32346. };
  32347. /**
  32348. * Releases resources associated with this mesh.
  32349. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32350. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32351. */
  32352. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32353. var _this = this;
  32354. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32355. this.morphTargetManager = null;
  32356. if (this._geometry) {
  32357. this._geometry.releaseForMesh(this, true);
  32358. }
  32359. if (this._onBeforeDrawObservable) {
  32360. this._onBeforeDrawObservable.clear();
  32361. }
  32362. if (this._onBeforeRenderObservable) {
  32363. this._onBeforeRenderObservable.clear();
  32364. }
  32365. if (this._onAfterRenderObservable) {
  32366. this._onAfterRenderObservable.clear();
  32367. }
  32368. // Sources
  32369. var meshes = this.getScene().meshes;
  32370. meshes.forEach(function (abstractMesh) {
  32371. var mesh = abstractMesh;
  32372. if (mesh._source && mesh._source === _this) {
  32373. mesh._source = null;
  32374. }
  32375. });
  32376. this._source = null;
  32377. // Instances
  32378. if (this._instancesBuffer) {
  32379. this._instancesBuffer.dispose();
  32380. this._instancesBuffer = null;
  32381. }
  32382. while (this.instances.length) {
  32383. this.instances[0].dispose();
  32384. }
  32385. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32386. };
  32387. /**
  32388. * Modifies the mesh geometry according to a displacement map.
  32389. * 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.
  32390. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32391. * @param url is a string, the URL from the image file is to be downloaded.
  32392. * @param minHeight is the lower limit of the displacement.
  32393. * @param maxHeight is the upper limit of the displacement.
  32394. * @param 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.
  32395. * @param uvOffset is an optional vector2 used to offset UV.
  32396. * @param uvScale is an optional vector2 used to scale UV.
  32397. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32398. * @returns the Mesh.
  32399. */
  32400. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32401. var _this = this;
  32402. if (forceUpdate === void 0) { forceUpdate = false; }
  32403. var scene = this.getScene();
  32404. var onload = function (img) {
  32405. // Getting height map data
  32406. var canvas = document.createElement("canvas");
  32407. var context = canvas.getContext("2d");
  32408. var heightMapWidth = img.width;
  32409. var heightMapHeight = img.height;
  32410. canvas.width = heightMapWidth;
  32411. canvas.height = heightMapHeight;
  32412. context.drawImage(img, 0, 0);
  32413. // Create VertexData from map data
  32414. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32415. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32416. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32417. //execute success callback, if set
  32418. if (onSuccess) {
  32419. onSuccess(_this);
  32420. }
  32421. };
  32422. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32423. return this;
  32424. };
  32425. /**
  32426. * Modifies the mesh geometry according to a displacementMap buffer.
  32427. * 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.
  32428. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32429. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32430. * @param heightMapWidth is the width of the buffer image.
  32431. * @param heightMapHeight is the height of the buffer image.
  32432. * @param minHeight is the lower limit of the displacement.
  32433. * @param maxHeight is the upper limit of the displacement.
  32434. * @param 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.
  32435. * @param uvOffset is an optional vector2 used to offset UV.
  32436. * @param uvScale is an optional vector2 used to scale UV.
  32437. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32438. * @returns the Mesh.
  32439. */
  32440. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32441. if (forceUpdate === void 0) { forceUpdate = false; }
  32442. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32443. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32444. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32445. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32446. return this;
  32447. }
  32448. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32449. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32450. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32451. var position = BABYLON.Vector3.Zero();
  32452. var normal = BABYLON.Vector3.Zero();
  32453. var uv = BABYLON.Vector2.Zero();
  32454. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32455. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32456. for (var index = 0; index < positions.length; index += 3) {
  32457. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32458. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32459. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32460. // Compute height
  32461. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32462. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32463. var pos = (u + v * heightMapWidth) * 4;
  32464. var r = buffer[pos] / 255.0;
  32465. var g = buffer[pos + 1] / 255.0;
  32466. var b = buffer[pos + 2] / 255.0;
  32467. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32468. normal.normalize();
  32469. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32470. position = position.add(normal);
  32471. position.toArray(positions, index);
  32472. }
  32473. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32474. if (forceUpdate) {
  32475. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32476. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32477. }
  32478. else {
  32479. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32480. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32481. }
  32482. return this;
  32483. };
  32484. /**
  32485. * Modify the mesh to get a flat shading rendering.
  32486. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32487. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32488. * @returns current mesh
  32489. */
  32490. Mesh.prototype.convertToFlatShadedMesh = function () {
  32491. var kinds = this.getVerticesDataKinds();
  32492. var vbs = {};
  32493. var data = {};
  32494. var newdata = {};
  32495. var updatableNormals = false;
  32496. var kindIndex;
  32497. var kind;
  32498. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32499. kind = kinds[kindIndex];
  32500. var vertexBuffer = this.getVertexBuffer(kind);
  32501. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32502. updatableNormals = vertexBuffer.isUpdatable();
  32503. kinds.splice(kindIndex, 1);
  32504. kindIndex--;
  32505. continue;
  32506. }
  32507. vbs[kind] = vertexBuffer;
  32508. data[kind] = vbs[kind].getData();
  32509. newdata[kind] = [];
  32510. }
  32511. // Save previous submeshes
  32512. var previousSubmeshes = this.subMeshes.slice(0);
  32513. var indices = this.getIndices();
  32514. var totalIndices = this.getTotalIndices();
  32515. // Generating unique vertices per face
  32516. var index;
  32517. for (index = 0; index < totalIndices; index++) {
  32518. var vertexIndex = indices[index];
  32519. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32520. kind = kinds[kindIndex];
  32521. var stride = vbs[kind].getStrideSize();
  32522. for (var offset = 0; offset < stride; offset++) {
  32523. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32524. }
  32525. }
  32526. }
  32527. // Updating faces & normal
  32528. var normals = [];
  32529. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32530. for (index = 0; index < totalIndices; index += 3) {
  32531. indices[index] = index;
  32532. indices[index + 1] = index + 1;
  32533. indices[index + 2] = index + 2;
  32534. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32535. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32536. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32537. var p1p2 = p1.subtract(p2);
  32538. var p3p2 = p3.subtract(p2);
  32539. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32540. // Store same normals for every vertex
  32541. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32542. normals.push(normal.x);
  32543. normals.push(normal.y);
  32544. normals.push(normal.z);
  32545. }
  32546. }
  32547. this.setIndices(indices);
  32548. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32549. // Updating vertex buffers
  32550. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32551. kind = kinds[kindIndex];
  32552. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32553. }
  32554. // Updating submeshes
  32555. this.releaseSubMeshes();
  32556. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32557. var previousOne = previousSubmeshes[submeshIndex];
  32558. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32559. }
  32560. this.synchronizeInstances();
  32561. return this;
  32562. };
  32563. /**
  32564. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32565. * In other words, more vertices, no more indices and a single bigger VBO.
  32566. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32567. * @returns current mesh
  32568. */
  32569. Mesh.prototype.convertToUnIndexedMesh = function () {
  32570. var kinds = this.getVerticesDataKinds();
  32571. var vbs = {};
  32572. var data = {};
  32573. var newdata = {};
  32574. var kindIndex;
  32575. var kind;
  32576. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32577. kind = kinds[kindIndex];
  32578. var vertexBuffer = this.getVertexBuffer(kind);
  32579. vbs[kind] = vertexBuffer;
  32580. data[kind] = vbs[kind].getData();
  32581. newdata[kind] = [];
  32582. }
  32583. // Save previous submeshes
  32584. var previousSubmeshes = this.subMeshes.slice(0);
  32585. var indices = this.getIndices();
  32586. var totalIndices = this.getTotalIndices();
  32587. // Generating unique vertices per face
  32588. var index;
  32589. for (index = 0; index < totalIndices; index++) {
  32590. var vertexIndex = indices[index];
  32591. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32592. kind = kinds[kindIndex];
  32593. var stride = vbs[kind].getStrideSize();
  32594. for (var offset = 0; offset < stride; offset++) {
  32595. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32596. }
  32597. }
  32598. }
  32599. // Updating indices
  32600. for (index = 0; index < totalIndices; index += 3) {
  32601. indices[index] = index;
  32602. indices[index + 1] = index + 1;
  32603. indices[index + 2] = index + 2;
  32604. }
  32605. this.setIndices(indices);
  32606. // Updating vertex buffers
  32607. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32608. kind = kinds[kindIndex];
  32609. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32610. }
  32611. // Updating submeshes
  32612. this.releaseSubMeshes();
  32613. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32614. var previousOne = previousSubmeshes[submeshIndex];
  32615. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32616. }
  32617. this._unIndexed = true;
  32618. this.synchronizeInstances();
  32619. return this;
  32620. };
  32621. /**
  32622. * Inverses facet orientations.
  32623. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32624. * @param flipNormals will also inverts the normals
  32625. * @returns current mesh
  32626. */
  32627. Mesh.prototype.flipFaces = function (flipNormals) {
  32628. if (flipNormals === void 0) { flipNormals = false; }
  32629. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32630. var i;
  32631. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32632. for (i = 0; i < vertex_data.normals.length; i++) {
  32633. vertex_data.normals[i] *= -1;
  32634. }
  32635. }
  32636. if (vertex_data.indices) {
  32637. var temp;
  32638. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32639. // reassign indices
  32640. temp = vertex_data.indices[i + 1];
  32641. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32642. vertex_data.indices[i + 2] = temp;
  32643. }
  32644. }
  32645. vertex_data.applyToMesh(this);
  32646. return this;
  32647. };
  32648. // Instances
  32649. /**
  32650. * Creates a new InstancedMesh object from the mesh model.
  32651. * Warning : this method is not supported for Line mesh and LineSystem
  32652. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32653. * @param name defines the name of the new instance
  32654. * @returns a new InstancedMesh
  32655. */
  32656. Mesh.prototype.createInstance = function (name) {
  32657. return new BABYLON.InstancedMesh(name, this);
  32658. };
  32659. /**
  32660. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32661. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32662. * @returns the current mesh
  32663. */
  32664. Mesh.prototype.synchronizeInstances = function () {
  32665. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32666. var instance = this.instances[instanceIndex];
  32667. instance._syncSubMeshes();
  32668. }
  32669. return this;
  32670. };
  32671. /**
  32672. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32673. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32674. * This should be used together with the simplification to avoid disappearing triangles.
  32675. * @param successCallback an optional success callback to be called after the optimization finished.
  32676. * @returns the current mesh
  32677. */
  32678. Mesh.prototype.optimizeIndices = function (successCallback) {
  32679. var _this = this;
  32680. var indices = this.getIndices();
  32681. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32682. if (!positions || !indices) {
  32683. return this;
  32684. }
  32685. var vectorPositions = new Array();
  32686. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32687. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32688. }
  32689. var dupes = new Array();
  32690. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32691. var realPos = vectorPositions.length - 1 - iteration;
  32692. var testedPosition = vectorPositions[realPos];
  32693. for (var j = 0; j < realPos; ++j) {
  32694. var againstPosition = vectorPositions[j];
  32695. if (testedPosition.equals(againstPosition)) {
  32696. dupes[realPos] = j;
  32697. break;
  32698. }
  32699. }
  32700. }, function () {
  32701. for (var i = 0; i < indices.length; ++i) {
  32702. indices[i] = dupes[indices[i]] || indices[i];
  32703. }
  32704. //indices are now reordered
  32705. var originalSubMeshes = _this.subMeshes.slice(0);
  32706. _this.setIndices(indices);
  32707. _this.subMeshes = originalSubMeshes;
  32708. if (successCallback) {
  32709. successCallback(_this);
  32710. }
  32711. });
  32712. return this;
  32713. };
  32714. /**
  32715. * Serialize current mesh
  32716. * @param serializationObject defines the object which will receive the serialization data
  32717. */
  32718. Mesh.prototype.serialize = function (serializationObject) {
  32719. serializationObject.name = this.name;
  32720. serializationObject.id = this.id;
  32721. serializationObject.type = this.getClassName();
  32722. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32723. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32724. }
  32725. serializationObject.position = this.position.asArray();
  32726. if (this.rotationQuaternion) {
  32727. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32728. }
  32729. else if (this.rotation) {
  32730. serializationObject.rotation = this.rotation.asArray();
  32731. }
  32732. serializationObject.scaling = this.scaling.asArray();
  32733. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32734. serializationObject.isEnabled = this.isEnabled(false);
  32735. serializationObject.isVisible = this.isVisible;
  32736. serializationObject.infiniteDistance = this.infiniteDistance;
  32737. serializationObject.pickable = this.isPickable;
  32738. serializationObject.receiveShadows = this.receiveShadows;
  32739. serializationObject.billboardMode = this.billboardMode;
  32740. serializationObject.visibility = this.visibility;
  32741. serializationObject.checkCollisions = this.checkCollisions;
  32742. serializationObject.isBlocker = this.isBlocker;
  32743. // Parent
  32744. if (this.parent) {
  32745. serializationObject.parentId = this.parent.id;
  32746. }
  32747. // Geometry
  32748. serializationObject.isUnIndexed = this.isUnIndexed;
  32749. var geometry = this._geometry;
  32750. if (geometry) {
  32751. var geometryId = geometry.id;
  32752. serializationObject.geometryId = geometryId;
  32753. // SubMeshes
  32754. serializationObject.subMeshes = [];
  32755. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32756. var subMesh = this.subMeshes[subIndex];
  32757. serializationObject.subMeshes.push({
  32758. materialIndex: subMesh.materialIndex,
  32759. verticesStart: subMesh.verticesStart,
  32760. verticesCount: subMesh.verticesCount,
  32761. indexStart: subMesh.indexStart,
  32762. indexCount: subMesh.indexCount
  32763. });
  32764. }
  32765. }
  32766. // Material
  32767. if (this.material) {
  32768. serializationObject.materialId = this.material.id;
  32769. }
  32770. else {
  32771. this.material = null;
  32772. }
  32773. // Morph targets
  32774. if (this.morphTargetManager) {
  32775. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32776. }
  32777. // Skeleton
  32778. if (this.skeleton) {
  32779. serializationObject.skeletonId = this.skeleton.id;
  32780. }
  32781. // Physics
  32782. //TODO implement correct serialization for physics impostors.
  32783. var impostor = this.getPhysicsImpostor();
  32784. if (impostor) {
  32785. serializationObject.physicsMass = impostor.getParam("mass");
  32786. serializationObject.physicsFriction = impostor.getParam("friction");
  32787. serializationObject.physicsRestitution = impostor.getParam("mass");
  32788. serializationObject.physicsImpostor = impostor.type;
  32789. }
  32790. // Metadata
  32791. if (this.metadata) {
  32792. serializationObject.metadata = this.metadata;
  32793. }
  32794. // Instances
  32795. serializationObject.instances = [];
  32796. for (var index = 0; index < this.instances.length; index++) {
  32797. var instance = this.instances[index];
  32798. if (instance.doNotSerialize) {
  32799. continue;
  32800. }
  32801. var serializationInstance = {
  32802. name: instance.name,
  32803. id: instance.id,
  32804. position: instance.position.asArray(),
  32805. scaling: instance.scaling.asArray()
  32806. };
  32807. if (instance.parent) {
  32808. serializationInstance.parentId = instance.parent.id;
  32809. }
  32810. if (instance.rotationQuaternion) {
  32811. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32812. }
  32813. else if (instance.rotation) {
  32814. serializationInstance.rotation = instance.rotation.asArray();
  32815. }
  32816. serializationObject.instances.push(serializationInstance);
  32817. // Animations
  32818. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32819. serializationInstance.ranges = instance.serializeAnimationRanges();
  32820. }
  32821. //
  32822. // Animations
  32823. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32824. serializationObject.ranges = this.serializeAnimationRanges();
  32825. // Layer mask
  32826. serializationObject.layerMask = this.layerMask;
  32827. // Alpha
  32828. serializationObject.alphaIndex = this.alphaIndex;
  32829. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32830. // Overlay
  32831. serializationObject.overlayAlpha = this.overlayAlpha;
  32832. serializationObject.overlayColor = this.overlayColor.asArray();
  32833. serializationObject.renderOverlay = this.renderOverlay;
  32834. // Fog
  32835. serializationObject.applyFog = this.applyFog;
  32836. // Action Manager
  32837. if (this.actionManager) {
  32838. serializationObject.actions = this.actionManager.serialize(this.name);
  32839. }
  32840. };
  32841. /** @hidden */
  32842. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32843. if (!this.geometry) {
  32844. return;
  32845. }
  32846. this._markSubMeshesAsAttributesDirty();
  32847. var morphTargetManager = this._morphTargetManager;
  32848. if (morphTargetManager && morphTargetManager.vertexCount) {
  32849. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32850. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32851. this.morphTargetManager = null;
  32852. return;
  32853. }
  32854. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32855. var morphTarget = morphTargetManager.getActiveTarget(index);
  32856. var positions = morphTarget.getPositions();
  32857. if (!positions) {
  32858. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32859. return;
  32860. }
  32861. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32862. var normals = morphTarget.getNormals();
  32863. if (normals) {
  32864. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32865. }
  32866. var tangents = morphTarget.getTangents();
  32867. if (tangents) {
  32868. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32869. }
  32870. }
  32871. }
  32872. else {
  32873. var index = 0;
  32874. // Positions
  32875. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32876. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32877. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32878. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32879. }
  32880. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32881. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32882. }
  32883. index++;
  32884. }
  32885. }
  32886. };
  32887. // Statics
  32888. /**
  32889. * Returns a new Mesh object parsed from the source provided.
  32890. * @param parsedMesh is the source
  32891. * @param scene defines the hosting scene
  32892. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  32893. * @returns a new Mesh
  32894. */
  32895. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32896. var mesh;
  32897. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32898. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32899. }
  32900. else {
  32901. mesh = new Mesh(parsedMesh.name, scene);
  32902. }
  32903. mesh.id = parsedMesh.id;
  32904. if (BABYLON.Tags) {
  32905. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32906. }
  32907. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32908. if (parsedMesh.metadata !== undefined) {
  32909. mesh.metadata = parsedMesh.metadata;
  32910. }
  32911. if (parsedMesh.rotationQuaternion) {
  32912. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32913. }
  32914. else if (parsedMesh.rotation) {
  32915. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32916. }
  32917. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32918. if (parsedMesh.localMatrix) {
  32919. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32920. }
  32921. else if (parsedMesh.pivotMatrix) {
  32922. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32923. }
  32924. mesh.setEnabled(parsedMesh.isEnabled);
  32925. mesh.isVisible = parsedMesh.isVisible;
  32926. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32927. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32928. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32929. if (parsedMesh.applyFog !== undefined) {
  32930. mesh.applyFog = parsedMesh.applyFog;
  32931. }
  32932. if (parsedMesh.pickable !== undefined) {
  32933. mesh.isPickable = parsedMesh.pickable;
  32934. }
  32935. if (parsedMesh.alphaIndex !== undefined) {
  32936. mesh.alphaIndex = parsedMesh.alphaIndex;
  32937. }
  32938. mesh.receiveShadows = parsedMesh.receiveShadows;
  32939. mesh.billboardMode = parsedMesh.billboardMode;
  32940. if (parsedMesh.visibility !== undefined) {
  32941. mesh.visibility = parsedMesh.visibility;
  32942. }
  32943. mesh.checkCollisions = parsedMesh.checkCollisions;
  32944. if (parsedMesh.isBlocker !== undefined) {
  32945. mesh.isBlocker = parsedMesh.isBlocker;
  32946. }
  32947. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32948. // freezeWorldMatrix
  32949. if (parsedMesh.freezeWorldMatrix) {
  32950. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32951. }
  32952. // Parent
  32953. if (parsedMesh.parentId) {
  32954. mesh._waitingParentId = parsedMesh.parentId;
  32955. }
  32956. // Actions
  32957. if (parsedMesh.actions !== undefined) {
  32958. mesh._waitingActions = parsedMesh.actions;
  32959. }
  32960. // Overlay
  32961. if (parsedMesh.overlayAlpha !== undefined) {
  32962. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32963. }
  32964. if (parsedMesh.overlayColor !== undefined) {
  32965. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32966. }
  32967. if (parsedMesh.renderOverlay !== undefined) {
  32968. mesh.renderOverlay = parsedMesh.renderOverlay;
  32969. }
  32970. // Geometry
  32971. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32972. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32973. if (parsedMesh.delayLoadingFile) {
  32974. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32975. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32976. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32977. if (parsedMesh._binaryInfo) {
  32978. mesh._binaryInfo = parsedMesh._binaryInfo;
  32979. }
  32980. mesh._delayInfo = [];
  32981. if (parsedMesh.hasUVs) {
  32982. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32983. }
  32984. if (parsedMesh.hasUVs2) {
  32985. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32986. }
  32987. if (parsedMesh.hasUVs3) {
  32988. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32989. }
  32990. if (parsedMesh.hasUVs4) {
  32991. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32992. }
  32993. if (parsedMesh.hasUVs5) {
  32994. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32995. }
  32996. if (parsedMesh.hasUVs6) {
  32997. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32998. }
  32999. if (parsedMesh.hasColors) {
  33000. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33001. }
  33002. if (parsedMesh.hasMatricesIndices) {
  33003. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33004. }
  33005. if (parsedMesh.hasMatricesWeights) {
  33006. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33007. }
  33008. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33009. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33010. mesh._checkDelayState();
  33011. }
  33012. }
  33013. else {
  33014. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33015. }
  33016. // Material
  33017. if (parsedMesh.materialId) {
  33018. mesh.setMaterialByID(parsedMesh.materialId);
  33019. }
  33020. else {
  33021. mesh.material = null;
  33022. }
  33023. // Morph targets
  33024. if (parsedMesh.morphTargetManagerId > -1) {
  33025. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33026. }
  33027. // Skeleton
  33028. if (parsedMesh.skeletonId > -1) {
  33029. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33030. if (parsedMesh.numBoneInfluencers) {
  33031. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33032. }
  33033. }
  33034. // Animations
  33035. if (parsedMesh.animations) {
  33036. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33037. var parsedAnimation = parsedMesh.animations[animationIndex];
  33038. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33039. }
  33040. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33041. }
  33042. if (parsedMesh.autoAnimate) {
  33043. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33044. }
  33045. // Layer Mask
  33046. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33047. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33048. }
  33049. else {
  33050. mesh.layerMask = 0x0FFFFFFF;
  33051. }
  33052. // Physics
  33053. if (parsedMesh.physicsImpostor) {
  33054. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33055. mass: parsedMesh.physicsMass,
  33056. friction: parsedMesh.physicsFriction,
  33057. restitution: parsedMesh.physicsRestitution
  33058. }, scene);
  33059. }
  33060. // Instances
  33061. if (parsedMesh.instances) {
  33062. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33063. var parsedInstance = parsedMesh.instances[index];
  33064. var instance = mesh.createInstance(parsedInstance.name);
  33065. if (parsedInstance.id) {
  33066. instance.id = parsedInstance.id;
  33067. }
  33068. if (BABYLON.Tags) {
  33069. if (parsedInstance.tags) {
  33070. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33071. }
  33072. else {
  33073. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33074. }
  33075. }
  33076. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33077. if (parsedInstance.parentId) {
  33078. instance._waitingParentId = parsedInstance.parentId;
  33079. }
  33080. if (parsedInstance.rotationQuaternion) {
  33081. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33082. }
  33083. else if (parsedInstance.rotation) {
  33084. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33085. }
  33086. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33087. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33088. instance.checkCollisions = parsedInstance.checkCollisions;
  33089. }
  33090. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33091. instance.isPickable = parsedInstance.pickable;
  33092. }
  33093. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33094. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33095. }
  33096. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33097. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33098. }
  33099. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33100. instance.alphaIndex = parsedInstance.alphaIndex;
  33101. }
  33102. // Physics
  33103. if (parsedInstance.physicsImpostor) {
  33104. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33105. mass: parsedInstance.physicsMass,
  33106. friction: parsedInstance.physicsFriction,
  33107. restitution: parsedInstance.physicsRestitution
  33108. }, scene);
  33109. }
  33110. // Animation
  33111. if (parsedInstance.animations) {
  33112. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33113. parsedAnimation = parsedInstance.animations[animationIndex];
  33114. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33115. }
  33116. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33117. if (parsedInstance.autoAnimate) {
  33118. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33119. }
  33120. }
  33121. }
  33122. }
  33123. return mesh;
  33124. };
  33125. /**
  33126. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33127. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33128. * @param name defines the name of the mesh to create
  33129. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33130. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33131. * @param closePath creates a seam between the first and the last points of each path of the path array
  33132. * @param offset is taken in account only if the `pathArray` is containing a single path
  33133. * @param scene defines the hosting scene
  33134. * @param updatable defines if the mesh must be flagged as updatable
  33135. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33136. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  33137. * @returns a new Mesh
  33138. */
  33139. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33140. if (closeArray === void 0) { closeArray = false; }
  33141. if (updatable === void 0) { updatable = false; }
  33142. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33143. pathArray: pathArray,
  33144. closeArray: closeArray,
  33145. closePath: closePath,
  33146. offset: offset,
  33147. updatable: updatable,
  33148. sideOrientation: sideOrientation,
  33149. instance: instance
  33150. }, scene);
  33151. };
  33152. /**
  33153. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33154. * @param name defines the name of the mesh to create
  33155. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33156. * @param 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
  33157. * @param scene defines the hosting scene
  33158. * @param updatable defines if the mesh must be flagged as updatable
  33159. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33160. * @returns a new Mesh
  33161. */
  33162. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33163. if (scene === void 0) { scene = null; }
  33164. var options = {
  33165. radius: radius,
  33166. tessellation: tessellation,
  33167. sideOrientation: sideOrientation,
  33168. updatable: updatable
  33169. };
  33170. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33171. };
  33172. /**
  33173. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33174. * @param name defines the name of the mesh to create
  33175. * @param size sets the size (float) of each box side (default 1)
  33176. * @param scene defines the hosting scene
  33177. * @param updatable defines if the mesh must be flagged as updatable
  33178. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33179. * @returns a new Mesh
  33180. */
  33181. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33182. if (scene === void 0) { scene = null; }
  33183. var options = {
  33184. size: size,
  33185. sideOrientation: sideOrientation,
  33186. updatable: updatable
  33187. };
  33188. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33189. };
  33190. /**
  33191. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33192. * @param name defines the name of the mesh to create
  33193. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33194. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33195. * @param scene defines the hosting scene
  33196. * @param updatable defines if the mesh must be flagged as updatable
  33197. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33198. * @returns a new Mesh
  33199. */
  33200. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33201. var options = {
  33202. segments: segments,
  33203. diameterX: diameter,
  33204. diameterY: diameter,
  33205. diameterZ: diameter,
  33206. sideOrientation: sideOrientation,
  33207. updatable: updatable
  33208. };
  33209. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33210. };
  33211. /**
  33212. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33213. * @param name defines the name of the mesh to create
  33214. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33215. * @param diameterTop set the top cap diameter (floats, default 1)
  33216. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33217. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33218. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33219. * @param scene defines the hosting scene
  33220. * @param updatable defines if the mesh must be flagged as updatable
  33221. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33222. * @returns a new Mesh
  33223. */
  33224. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33225. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33226. if (scene !== undefined) {
  33227. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33228. updatable = scene;
  33229. }
  33230. scene = subdivisions;
  33231. subdivisions = 1;
  33232. }
  33233. var options = {
  33234. height: height,
  33235. diameterTop: diameterTop,
  33236. diameterBottom: diameterBottom,
  33237. tessellation: tessellation,
  33238. subdivisions: subdivisions,
  33239. sideOrientation: sideOrientation,
  33240. updatable: updatable
  33241. };
  33242. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33243. };
  33244. // Torus (Code from SharpDX.org)
  33245. /**
  33246. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33247. * @param name defines the name of the mesh to create
  33248. * @param diameter sets the diameter size (float) of the torus (default 1)
  33249. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33250. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33251. * @param scene defines the hosting scene
  33252. * @param updatable defines if the mesh must be flagged as updatable
  33253. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33254. * @returns a new Mesh
  33255. */
  33256. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33257. var options = {
  33258. diameter: diameter,
  33259. thickness: thickness,
  33260. tessellation: tessellation,
  33261. sideOrientation: sideOrientation,
  33262. updatable: updatable
  33263. };
  33264. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33265. };
  33266. /**
  33267. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33268. * @param name defines the name of the mesh to create
  33269. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33270. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33271. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33272. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33273. * @param p the number of windings on X axis (positive integers, default 2)
  33274. * @param q the number of windings on Y axis (positive integers, default 3)
  33275. * @param scene defines the hosting scene
  33276. * @param updatable defines if the mesh must be flagged as updatable
  33277. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33278. * @returns a new Mesh
  33279. */
  33280. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33281. var options = {
  33282. radius: radius,
  33283. tube: tube,
  33284. radialSegments: radialSegments,
  33285. tubularSegments: tubularSegments,
  33286. p: p,
  33287. q: q,
  33288. sideOrientation: sideOrientation,
  33289. updatable: updatable
  33290. };
  33291. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33292. };
  33293. /**
  33294. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33295. * @param name defines the name of the mesh to create
  33296. * @param points is an array successive Vector3
  33297. * @param scene defines the hosting scene
  33298. * @param updatable defines if the mesh must be flagged as updatable
  33299. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  33300. * @returns a new Mesh
  33301. */
  33302. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33303. if (scene === void 0) { scene = null; }
  33304. if (updatable === void 0) { updatable = false; }
  33305. if (instance === void 0) { instance = null; }
  33306. var options = {
  33307. points: points,
  33308. updatable: updatable,
  33309. instance: instance
  33310. };
  33311. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33312. };
  33313. /**
  33314. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33315. * @param name defines the name of the mesh to create
  33316. * @param points is an array successive Vector3
  33317. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33318. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33319. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33320. * @param scene defines the hosting scene
  33321. * @param updatable defines if the mesh must be flagged as updatable
  33322. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  33323. * @returns a new Mesh
  33324. */
  33325. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33326. if (scene === void 0) { scene = null; }
  33327. var options = {
  33328. points: points,
  33329. dashSize: dashSize,
  33330. gapSize: gapSize,
  33331. dashNb: dashNb,
  33332. updatable: updatable,
  33333. instance: instance
  33334. };
  33335. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33336. };
  33337. /**
  33338. * Creates a polygon mesh.
  33339. * Please consider using the same method from the MeshBuilder class instead.
  33340. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33341. * 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.
  33342. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33344. * Remember you can only change the shape positions, not their number when updating a polygon.
  33345. */
  33346. /**
  33347. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33348. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33349. * @param name defines the name of the mesh to create
  33350. * @param 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
  33351. * @param scene defines the hosting scene
  33352. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33353. * @param updatable defines if the mesh must be flagged as updatable
  33354. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33355. * @returns a new Mesh
  33356. */
  33357. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33358. var options = {
  33359. shape: shape,
  33360. holes: holes,
  33361. updatable: updatable,
  33362. sideOrientation: sideOrientation
  33363. };
  33364. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33365. };
  33366. /**
  33367. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33368. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33369. * @param name defines the name of the mesh to create
  33370. * @param 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
  33371. * @param depth defines the height of extrusion
  33372. * @param scene defines the hosting scene
  33373. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33374. * @param updatable defines if the mesh must be flagged as updatable
  33375. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33376. * @returns a new Mesh
  33377. */
  33378. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33379. var options = {
  33380. shape: shape,
  33381. holes: holes,
  33382. depth: depth,
  33383. updatable: updatable,
  33384. sideOrientation: sideOrientation
  33385. };
  33386. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33387. };
  33388. /**
  33389. * Creates an extruded shape mesh.
  33390. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  33391. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33392. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33393. * @param name defines the name of the mesh to create
  33394. * @param 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 extruded along the Z axis
  33395. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33396. * @param scale is the value to scale the shape
  33397. * @param rotation 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
  33398. * @param 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
  33399. * @param scene defines the hosting scene
  33400. * @param updatable defines if the mesh must be flagged as updatable
  33401. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33402. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  33403. * @returns a new Mesh
  33404. */
  33405. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33406. if (scene === void 0) { scene = null; }
  33407. var options = {
  33408. shape: shape,
  33409. path: path,
  33410. scale: scale,
  33411. rotation: rotation,
  33412. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33413. sideOrientation: sideOrientation,
  33414. instance: instance,
  33415. updatable: updatable
  33416. };
  33417. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33418. };
  33419. /**
  33420. * Creates an custom extruded shape mesh.
  33421. * The custom extrusion is a parametric shape.
  33422. * It has no predefined shape. Its final shape will depend on the input parameters.
  33423. * Please consider using the same method from the MeshBuilder class instead
  33424. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33425. * @param name defines the name of the mesh to create
  33426. * @param 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 extruded along the Z axis
  33427. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33428. * @param scaleFunction is a custom Javascript function called on each path point
  33429. * @param rotationFunction is a custom Javascript function called on each path point
  33430. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33431. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33432. * @param 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
  33433. * @param scene defines the hosting scene
  33434. * @param updatable defines if the mesh must be flagged as updatable
  33435. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33436. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  33437. * @returns a new Mesh
  33438. */
  33439. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33440. var options = {
  33441. shape: shape,
  33442. path: path,
  33443. scaleFunction: scaleFunction,
  33444. rotationFunction: rotationFunction,
  33445. ribbonCloseArray: ribbonCloseArray,
  33446. ribbonClosePath: ribbonClosePath,
  33447. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33448. sideOrientation: sideOrientation,
  33449. instance: instance,
  33450. updatable: updatable
  33451. };
  33452. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33453. };
  33454. /**
  33455. * Creates lathe mesh.
  33456. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33457. * Please consider using the same method from the MeshBuilder class instead
  33458. * @param name defines the name of the mesh to create
  33459. * @param 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  33460. * @param radius is the radius value of the lathe
  33461. * @param tessellation is the side number of the lathe.
  33462. * @param scene defines the hosting scene
  33463. * @param updatable defines if the mesh must be flagged as updatable
  33464. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33465. * @returns a new Mesh
  33466. */
  33467. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33468. var options = {
  33469. shape: shape,
  33470. radius: radius,
  33471. tessellation: tessellation,
  33472. sideOrientation: sideOrientation,
  33473. updatable: updatable
  33474. };
  33475. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33476. };
  33477. /**
  33478. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33479. * @param name defines the name of the mesh to create
  33480. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33481. * @param scene defines the hosting scene
  33482. * @param updatable defines if the mesh must be flagged as updatable
  33483. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33484. * @returns a new Mesh
  33485. */
  33486. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33487. var options = {
  33488. size: size,
  33489. width: size,
  33490. height: size,
  33491. sideOrientation: sideOrientation,
  33492. updatable: updatable
  33493. };
  33494. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33495. };
  33496. /**
  33497. * Creates a ground mesh.
  33498. * Please consider using the same method from the MeshBuilder class instead
  33499. * @param name defines the name of the mesh to create
  33500. * @param width set the width of the ground
  33501. * @param height set the height of the ground
  33502. * @param subdivisions sets the number of subdivisions per side
  33503. * @param scene defines the hosting scene
  33504. * @param updatable defines if the mesh must be flagged as updatable
  33505. * @returns a new Mesh
  33506. */
  33507. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33508. var options = {
  33509. width: width,
  33510. height: height,
  33511. subdivisions: subdivisions,
  33512. updatable: updatable
  33513. };
  33514. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33515. };
  33516. /**
  33517. * Creates a tiled ground mesh.
  33518. * Please consider using the same method from the MeshBuilder class instead
  33519. * @param name defines the name of the mesh to create
  33520. * @param xmin set the ground minimum X coordinate
  33521. * @param zmin set the ground minimum Y coordinate
  33522. * @param xmax set the ground maximum X coordinate
  33523. * @param zmax set the ground maximum Z coordinate
  33524. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  33525. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  33526. * @param scene defines the hosting scene
  33527. * @param updatable defines if the mesh must be flagged as updatable
  33528. * @returns a new Mesh
  33529. */
  33530. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33531. var options = {
  33532. xmin: xmin,
  33533. zmin: zmin,
  33534. xmax: xmax,
  33535. zmax: zmax,
  33536. subdivisions: subdivisions,
  33537. precision: precision,
  33538. updatable: updatable
  33539. };
  33540. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33541. };
  33542. /**
  33543. * Creates a ground mesh from a height map.
  33544. * Please consider using the same method from the MeshBuilder class instead
  33545. * @see http://doc.babylonjs.com/babylon101/height_map
  33546. * @param name defines the name of the mesh to create
  33547. * @param url sets the URL of the height map image resource
  33548. * @param width set the ground width size
  33549. * @param height set the ground height size
  33550. * @param subdivisions sets the number of subdivision per side
  33551. * @param minHeight is the minimum altitude on the ground
  33552. * @param maxHeight is the maximum altitude on the ground
  33553. * @param scene defines the hosting scene
  33554. * @param updatable defines if the mesh must be flagged as updatable
  33555. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33556. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33557. * @returns a new Mesh
  33558. */
  33559. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33560. var options = {
  33561. width: width,
  33562. height: height,
  33563. subdivisions: subdivisions,
  33564. minHeight: minHeight,
  33565. maxHeight: maxHeight,
  33566. updatable: updatable,
  33567. onReady: onReady,
  33568. alphaFilter: alphaFilter
  33569. };
  33570. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33571. };
  33572. /**
  33573. * Creates a tube mesh.
  33574. * The tube is a parametric shape.
  33575. * It has no predefined shape. Its final shape will depend on the input parameters.
  33576. * Please consider using the same method from the MeshBuilder class instead
  33577. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33578. * @param name defines the name of the mesh to create
  33579. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33580. * @param radius sets the tube radius size
  33581. * @param tessellation is the number of sides on the tubular surface
  33582. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  33583. * @param 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
  33584. * @param scene defines the hosting scene
  33585. * @param updatable defines if the mesh must be flagged as updatable
  33586. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33587. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  33588. * @returns a new Mesh
  33589. */
  33590. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33591. var options = {
  33592. path: path,
  33593. radius: radius,
  33594. tessellation: tessellation,
  33595. radiusFunction: radiusFunction,
  33596. arc: 1,
  33597. cap: cap,
  33598. updatable: updatable,
  33599. sideOrientation: sideOrientation,
  33600. instance: instance
  33601. };
  33602. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33603. };
  33604. /**
  33605. * Creates a polyhedron mesh.
  33606. * Please consider using the same method from the MeshBuilder class instead.
  33607. * * 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 to choose the wanted type
  33608. * * The parameter `size` (positive float, default 1) sets the polygon size
  33609. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  33610. * * 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`
  33611. * * 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
  33612. * * 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)`)
  33613. * * 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
  33614. * * 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
  33615. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33616. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33617. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33618. * @param name defines the name of the mesh to create
  33619. * @param options defines the options used to create the mesh
  33620. * @param scene defines the hosting scene
  33621. * @returns a new Mesh
  33622. */
  33623. Mesh.CreatePolyhedron = function (name, options, scene) {
  33624. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33625. };
  33626. /**
  33627. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  33628. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  33629. * * 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`)
  33630. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  33631. * * 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
  33632. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33633. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33634. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33635. * @param name defines the name of the mesh
  33636. * @param options defines the options used to create the mesh
  33637. * @param scene defines the hosting scene
  33638. * @returns a new Mesh
  33639. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  33640. */
  33641. Mesh.CreateIcoSphere = function (name, options, scene) {
  33642. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33643. };
  33644. /**
  33645. * Creates a decal mesh.
  33646. * Please consider using the same method from the MeshBuilder class instead.
  33647. * A decal is a mesh usually applied as a model onto the surface of another mesh
  33648. * @param name defines the name of the mesh
  33649. * @param sourceMesh defines the mesh receiving the decal
  33650. * @param position sets the position of the decal in world coordinates
  33651. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  33652. * @param size sets the decal scaling
  33653. * @param angle sets the angle to rotate the decal
  33654. * @returns a new Mesh
  33655. */
  33656. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33657. var options = {
  33658. position: position,
  33659. normal: normal,
  33660. size: size,
  33661. angle: angle
  33662. };
  33663. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33664. };
  33665. // Skeletons
  33666. /**
  33667. * Prepare internal position array for software CPU skinning
  33668. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  33669. */
  33670. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33671. if (!this._sourcePositions) {
  33672. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33673. if (!source) {
  33674. return this._sourcePositions;
  33675. }
  33676. this._sourcePositions = new Float32Array(source);
  33677. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33678. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33679. }
  33680. }
  33681. return this._sourcePositions;
  33682. };
  33683. /**
  33684. * Prepare internal normal array for software CPU skinning
  33685. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33686. */
  33687. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33688. if (!this._sourceNormals) {
  33689. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33690. if (!source) {
  33691. return this._sourceNormals;
  33692. }
  33693. this._sourceNormals = new Float32Array(source);
  33694. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33695. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33696. }
  33697. }
  33698. return this._sourceNormals;
  33699. };
  33700. /**
  33701. * Updates the vertex buffer by applying transformation from the bones
  33702. * @param skeleton defines the skeleton to apply to current mesh
  33703. * @returns the current mesh
  33704. */
  33705. Mesh.prototype.applySkeleton = function (skeleton) {
  33706. if (!this.geometry) {
  33707. return this;
  33708. }
  33709. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33710. return this;
  33711. }
  33712. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33713. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33714. return this;
  33715. }
  33716. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33717. return this;
  33718. }
  33719. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33720. return this;
  33721. }
  33722. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33723. return this;
  33724. }
  33725. if (!this._sourcePositions) {
  33726. var submeshes = this.subMeshes.slice();
  33727. this.setPositionsForCPUSkinning();
  33728. this.subMeshes = submeshes;
  33729. }
  33730. if (!this._sourceNormals) {
  33731. this.setNormalsForCPUSkinning();
  33732. }
  33733. // positionsData checks for not being Float32Array will only pass at most once
  33734. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33735. if (!positionsData) {
  33736. return this;
  33737. }
  33738. if (!(positionsData instanceof Float32Array)) {
  33739. positionsData = new Float32Array(positionsData);
  33740. }
  33741. // normalsData checks for not being Float32Array will only pass at most once
  33742. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33743. if (!normalsData) {
  33744. return this;
  33745. }
  33746. if (!(normalsData instanceof Float32Array)) {
  33747. normalsData = new Float32Array(normalsData);
  33748. }
  33749. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33750. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33751. if (!matricesWeightsData || !matricesIndicesData) {
  33752. return this;
  33753. }
  33754. var needExtras = this.numBoneInfluencers > 4;
  33755. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33756. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33757. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33758. var tempVector3 = BABYLON.Vector3.Zero();
  33759. var finalMatrix = new BABYLON.Matrix();
  33760. var tempMatrix = new BABYLON.Matrix();
  33761. var matWeightIdx = 0;
  33762. var inf;
  33763. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33764. var weight;
  33765. for (inf = 0; inf < 4; inf++) {
  33766. weight = matricesWeightsData[matWeightIdx + inf];
  33767. if (weight > 0) {
  33768. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33769. finalMatrix.addToSelf(tempMatrix);
  33770. }
  33771. }
  33772. if (needExtras) {
  33773. for (inf = 0; inf < 4; inf++) {
  33774. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33775. if (weight > 0) {
  33776. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33777. finalMatrix.addToSelf(tempMatrix);
  33778. }
  33779. }
  33780. }
  33781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33782. tempVector3.toArray(positionsData, index);
  33783. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33784. tempVector3.toArray(normalsData, index);
  33785. finalMatrix.reset();
  33786. }
  33787. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33788. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33789. return this;
  33790. };
  33791. // Tools
  33792. /**
  33793. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  33794. * @param meshes defines the list of meshes to scan
  33795. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  33796. */
  33797. Mesh.MinMax = function (meshes) {
  33798. var minVector = null;
  33799. var maxVector = null;
  33800. meshes.forEach(function (mesh, index, array) {
  33801. var boundingInfo = mesh.getBoundingInfo();
  33802. var boundingBox = boundingInfo.boundingBox;
  33803. if (!minVector || !maxVector) {
  33804. minVector = boundingBox.minimumWorld;
  33805. maxVector = boundingBox.maximumWorld;
  33806. }
  33807. else {
  33808. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33809. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33810. }
  33811. });
  33812. if (!minVector || !maxVector) {
  33813. return {
  33814. min: BABYLON.Vector3.Zero(),
  33815. max: BABYLON.Vector3.Zero()
  33816. };
  33817. }
  33818. return {
  33819. min: minVector,
  33820. max: maxVector
  33821. };
  33822. };
  33823. /**
  33824. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  33825. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  33826. * @returns a vector3
  33827. */
  33828. Mesh.Center = function (meshesOrMinMaxVector) {
  33829. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33830. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33831. };
  33832. /**
  33833. * Merge the array of meshes into a single mesh for performance reasons.
  33834. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  33835. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  33836. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  33837. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33838. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  33839. * @returns a new mesh
  33840. */
  33841. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33842. if (disposeSource === void 0) { disposeSource = true; }
  33843. var index;
  33844. if (!allow32BitsIndices) {
  33845. var totalVertices = 0;
  33846. // Counting vertices
  33847. for (index = 0; index < meshes.length; index++) {
  33848. if (meshes[index]) {
  33849. totalVertices += meshes[index].getTotalVertices();
  33850. if (totalVertices > 65536) {
  33851. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33852. return null;
  33853. }
  33854. }
  33855. }
  33856. }
  33857. // Merge
  33858. var vertexData = null;
  33859. var otherVertexData;
  33860. var indiceArray = new Array();
  33861. var source = null;
  33862. for (index = 0; index < meshes.length; index++) {
  33863. if (meshes[index]) {
  33864. var wm = meshes[index].computeWorldMatrix(true);
  33865. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33866. otherVertexData.transform(wm);
  33867. if (vertexData) {
  33868. vertexData.merge(otherVertexData, allow32BitsIndices);
  33869. }
  33870. else {
  33871. vertexData = otherVertexData;
  33872. source = meshes[index];
  33873. }
  33874. if (subdivideWithSubMeshes) {
  33875. indiceArray.push(meshes[index].getTotalIndices());
  33876. }
  33877. }
  33878. }
  33879. source = source;
  33880. if (!meshSubclass) {
  33881. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33882. }
  33883. vertexData.applyToMesh(meshSubclass);
  33884. // Setting properties
  33885. meshSubclass.material = source.material;
  33886. meshSubclass.checkCollisions = source.checkCollisions;
  33887. // Cleaning
  33888. if (disposeSource) {
  33889. for (index = 0; index < meshes.length; index++) {
  33890. if (meshes[index]) {
  33891. meshes[index].dispose();
  33892. }
  33893. }
  33894. }
  33895. // Subdivide
  33896. if (subdivideWithSubMeshes) {
  33897. //-- removal of global submesh
  33898. meshSubclass.releaseSubMeshes();
  33899. index = 0;
  33900. var offset = 0;
  33901. //-- apply subdivision according to index table
  33902. while (index < indiceArray.length) {
  33903. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33904. offset += indiceArray[index];
  33905. index++;
  33906. }
  33907. }
  33908. return meshSubclass;
  33909. };
  33910. // Consts
  33911. /**
  33912. * Mesh side orientation : usually the external or front surface
  33913. */
  33914. Mesh.FRONTSIDE = 0;
  33915. /**
  33916. * Mesh side orientation : usually the internal or back surface
  33917. */
  33918. Mesh.BACKSIDE = 1;
  33919. /**
  33920. * Mesh side orientation : both internal and external or front and back surfaces
  33921. */
  33922. Mesh.DOUBLESIDE = 2;
  33923. /**
  33924. * Mesh side orientation : by default, `FRONTSIDE`
  33925. */
  33926. Mesh.DEFAULTSIDE = 0;
  33927. /**
  33928. * Mesh cap setting : no cap
  33929. */
  33930. Mesh.NO_CAP = 0;
  33931. /**
  33932. * Mesh cap setting : one cap at the beginning of the mesh
  33933. */
  33934. Mesh.CAP_START = 1;
  33935. /**
  33936. * Mesh cap setting : one cap at the end of the mesh
  33937. */
  33938. Mesh.CAP_END = 2;
  33939. /**
  33940. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  33941. */
  33942. Mesh.CAP_ALL = 3;
  33943. return Mesh;
  33944. }(BABYLON.AbstractMesh));
  33945. BABYLON.Mesh = Mesh;
  33946. })(BABYLON || (BABYLON = {}));
  33947. //# sourceMappingURL=babylon.mesh.js.map
  33948. var BABYLON;
  33949. (function (BABYLON) {
  33950. var BaseSubMesh = /** @class */ (function () {
  33951. function BaseSubMesh() {
  33952. }
  33953. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33954. get: function () {
  33955. return this._materialEffect;
  33956. },
  33957. enumerable: true,
  33958. configurable: true
  33959. });
  33960. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33961. if (defines === void 0) { defines = null; }
  33962. if (this._materialEffect === effect) {
  33963. if (!effect) {
  33964. this._materialDefines = null;
  33965. }
  33966. return;
  33967. }
  33968. this._materialDefines = defines;
  33969. this._materialEffect = effect;
  33970. };
  33971. return BaseSubMesh;
  33972. }());
  33973. BABYLON.BaseSubMesh = BaseSubMesh;
  33974. var SubMesh = /** @class */ (function (_super) {
  33975. __extends(SubMesh, _super);
  33976. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33977. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33978. var _this = _super.call(this) || this;
  33979. _this.materialIndex = materialIndex;
  33980. _this.verticesStart = verticesStart;
  33981. _this.verticesCount = verticesCount;
  33982. _this.indexStart = indexStart;
  33983. _this.indexCount = indexCount;
  33984. /** @hidden */
  33985. _this._renderId = 0;
  33986. _this._mesh = mesh;
  33987. _this._renderingMesh = renderingMesh || mesh;
  33988. mesh.subMeshes.push(_this);
  33989. _this._trianglePlanes = [];
  33990. _this._id = mesh.subMeshes.length - 1;
  33991. if (createBoundingBox) {
  33992. _this.refreshBoundingInfo();
  33993. mesh.computeWorldMatrix(true);
  33994. }
  33995. return _this;
  33996. }
  33997. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33998. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33999. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34000. };
  34001. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34002. get: function () {
  34003. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34004. },
  34005. enumerable: true,
  34006. configurable: true
  34007. });
  34008. /**
  34009. * Returns the submesh BoudingInfo object.
  34010. */
  34011. SubMesh.prototype.getBoundingInfo = function () {
  34012. if (this.IsGlobal) {
  34013. return this._mesh.getBoundingInfo();
  34014. }
  34015. return this._boundingInfo;
  34016. };
  34017. /**
  34018. * Sets the submesh BoundingInfo.
  34019. * Return the SubMesh.
  34020. */
  34021. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34022. this._boundingInfo = boundingInfo;
  34023. return this;
  34024. };
  34025. /**
  34026. * Returns the mesh of the current submesh.
  34027. */
  34028. SubMesh.prototype.getMesh = function () {
  34029. return this._mesh;
  34030. };
  34031. /**
  34032. * Returns the rendering mesh of the submesh.
  34033. */
  34034. SubMesh.prototype.getRenderingMesh = function () {
  34035. return this._renderingMesh;
  34036. };
  34037. /**
  34038. * Returns the submesh material.
  34039. */
  34040. SubMesh.prototype.getMaterial = function () {
  34041. var rootMaterial = this._renderingMesh.material;
  34042. if (rootMaterial === null || rootMaterial === undefined) {
  34043. return this._mesh.getScene().defaultMaterial;
  34044. }
  34045. else if (rootMaterial.getSubMaterial) {
  34046. var multiMaterial = rootMaterial;
  34047. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34048. if (this._currentMaterial !== effectiveMaterial) {
  34049. this._currentMaterial = effectiveMaterial;
  34050. this._materialDefines = null;
  34051. }
  34052. return effectiveMaterial;
  34053. }
  34054. return rootMaterial;
  34055. };
  34056. // Methods
  34057. /**
  34058. * Sets a new updated BoundingInfo object to the submesh.
  34059. * Returns the SubMesh.
  34060. */
  34061. SubMesh.prototype.refreshBoundingInfo = function () {
  34062. this._lastColliderWorldVertices = null;
  34063. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34064. return this;
  34065. }
  34066. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34067. if (!data) {
  34068. this._boundingInfo = this._mesh.getBoundingInfo();
  34069. return this;
  34070. }
  34071. var indices = this._renderingMesh.getIndices();
  34072. var extend;
  34073. //is this the only submesh?
  34074. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34075. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34076. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34077. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34078. }
  34079. else {
  34080. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34081. }
  34082. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34083. return this;
  34084. };
  34085. /** @hidden */
  34086. SubMesh.prototype._checkCollision = function (collider) {
  34087. var boundingInfo = this.getBoundingInfo();
  34088. return boundingInfo._checkCollision(collider);
  34089. };
  34090. /**
  34091. * Updates the submesh BoundingInfo.
  34092. * Returns the Submesh.
  34093. */
  34094. SubMesh.prototype.updateBoundingInfo = function (world) {
  34095. var boundingInfo = this.getBoundingInfo();
  34096. if (!boundingInfo) {
  34097. this.refreshBoundingInfo();
  34098. boundingInfo = this.getBoundingInfo();
  34099. }
  34100. boundingInfo.update(world);
  34101. return this;
  34102. };
  34103. /**
  34104. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34105. * Boolean returned.
  34106. */
  34107. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34108. var boundingInfo = this.getBoundingInfo();
  34109. if (!boundingInfo) {
  34110. return false;
  34111. }
  34112. return boundingInfo.isInFrustum(frustumPlanes);
  34113. };
  34114. /**
  34115. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34116. * Boolean returned.
  34117. */
  34118. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34119. var boundingInfo = this.getBoundingInfo();
  34120. if (!boundingInfo) {
  34121. return false;
  34122. }
  34123. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34124. };
  34125. /**
  34126. * Renders the submesh.
  34127. * Returns it.
  34128. */
  34129. SubMesh.prototype.render = function (enableAlphaMode) {
  34130. this._renderingMesh.render(this, enableAlphaMode);
  34131. return this;
  34132. };
  34133. /**
  34134. * Returns a new Index Buffer.
  34135. * Type returned : WebGLBuffer.
  34136. */
  34137. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34138. if (!this._linesIndexBuffer) {
  34139. var linesIndices = [];
  34140. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34141. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34142. }
  34143. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34144. this.linesIndexCount = linesIndices.length;
  34145. }
  34146. return this._linesIndexBuffer;
  34147. };
  34148. /**
  34149. * True is the passed Ray intersects the submesh bounding box.
  34150. * Boolean returned.
  34151. */
  34152. SubMesh.prototype.canIntersects = function (ray) {
  34153. var boundingInfo = this.getBoundingInfo();
  34154. if (!boundingInfo) {
  34155. return false;
  34156. }
  34157. return ray.intersectsBox(boundingInfo.boundingBox);
  34158. };
  34159. /**
  34160. * Returns an object IntersectionInfo.
  34161. */
  34162. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34163. var intersectInfo = null;
  34164. var material = this.getMaterial();
  34165. if (!material) {
  34166. return null;
  34167. }
  34168. switch (material.fillMode) {
  34169. case BABYLON.Material.PointListDrawMode:
  34170. case BABYLON.Material.LineListDrawMode:
  34171. case BABYLON.Material.LineLoopDrawMode:
  34172. case BABYLON.Material.LineStripDrawMode:
  34173. case BABYLON.Material.TriangleFanDrawMode:
  34174. case BABYLON.Material.TriangleStripDrawMode:
  34175. return null;
  34176. }
  34177. // LineMesh first as it's also a Mesh...
  34178. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34179. var lineMesh = this._mesh;
  34180. // Line test
  34181. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34182. var p0 = positions[indices[index]];
  34183. var p1 = positions[indices[index + 1]];
  34184. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34185. if (length < 0) {
  34186. continue;
  34187. }
  34188. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34189. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34190. if (fastCheck) {
  34191. break;
  34192. }
  34193. }
  34194. }
  34195. }
  34196. else {
  34197. // Triangles test
  34198. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34199. var p0 = positions[indices[index]];
  34200. var p1 = positions[indices[index + 1]];
  34201. var p2 = positions[indices[index + 2]];
  34202. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34203. if (currentIntersectInfo) {
  34204. if (currentIntersectInfo.distance < 0) {
  34205. continue;
  34206. }
  34207. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34208. intersectInfo = currentIntersectInfo;
  34209. intersectInfo.faceId = index / 3;
  34210. if (fastCheck) {
  34211. break;
  34212. }
  34213. }
  34214. }
  34215. }
  34216. }
  34217. return intersectInfo;
  34218. };
  34219. /** @hidden */
  34220. SubMesh.prototype._rebuild = function () {
  34221. if (this._linesIndexBuffer) {
  34222. this._linesIndexBuffer = null;
  34223. }
  34224. };
  34225. // Clone
  34226. /**
  34227. * Creates a new Submesh from the passed Mesh.
  34228. */
  34229. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34230. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34231. if (!this.IsGlobal) {
  34232. var boundingInfo = this.getBoundingInfo();
  34233. if (!boundingInfo) {
  34234. return result;
  34235. }
  34236. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34237. }
  34238. return result;
  34239. };
  34240. // Dispose
  34241. /**
  34242. * Disposes the Submesh.
  34243. * Returns nothing.
  34244. */
  34245. SubMesh.prototype.dispose = function () {
  34246. if (this._linesIndexBuffer) {
  34247. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34248. this._linesIndexBuffer = null;
  34249. }
  34250. // Remove from mesh
  34251. var index = this._mesh.subMeshes.indexOf(this);
  34252. this._mesh.subMeshes.splice(index, 1);
  34253. };
  34254. // Statics
  34255. /**
  34256. * Creates a new Submesh from the passed parameters :
  34257. * - materialIndex (integer) : the index of the main mesh material.
  34258. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34259. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34260. * - mesh (Mesh) : the main mesh to create the submesh from.
  34261. * - renderingMesh (optional Mesh) : rendering mesh.
  34262. */
  34263. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34264. var minVertexIndex = Number.MAX_VALUE;
  34265. var maxVertexIndex = -Number.MAX_VALUE;
  34266. renderingMesh = (renderingMesh || mesh);
  34267. var indices = renderingMesh.getIndices();
  34268. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34269. var vertexIndex = indices[index];
  34270. if (vertexIndex < minVertexIndex)
  34271. minVertexIndex = vertexIndex;
  34272. if (vertexIndex > maxVertexIndex)
  34273. maxVertexIndex = vertexIndex;
  34274. }
  34275. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34276. };
  34277. return SubMesh;
  34278. }(BaseSubMesh));
  34279. BABYLON.SubMesh = SubMesh;
  34280. })(BABYLON || (BABYLON = {}));
  34281. //# sourceMappingURL=babylon.subMesh.js.map
  34282. var __assign = (this && this.__assign) || function () {
  34283. __assign = Object.assign || function(t) {
  34284. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34285. s = arguments[i];
  34286. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34287. t[p] = s[p];
  34288. }
  34289. return t;
  34290. };
  34291. return __assign.apply(this, arguments);
  34292. };
  34293. var BABYLON;
  34294. (function (BABYLON) {
  34295. /**
  34296. * Manages the defines for the Material
  34297. */
  34298. var MaterialDefines = /** @class */ (function () {
  34299. function MaterialDefines() {
  34300. this._isDirty = true;
  34301. /** @hidden */
  34302. this._areLightsDirty = true;
  34303. /** @hidden */
  34304. this._areAttributesDirty = true;
  34305. /** @hidden */
  34306. this._areTexturesDirty = true;
  34307. /** @hidden */
  34308. this._areFresnelDirty = true;
  34309. /** @hidden */
  34310. this._areMiscDirty = true;
  34311. /** @hidden */
  34312. this._areImageProcessingDirty = true;
  34313. /** @hidden */
  34314. this._normals = false;
  34315. /** @hidden */
  34316. this._uvs = false;
  34317. /** @hidden */
  34318. this._needNormals = false;
  34319. /** @hidden */
  34320. this._needUVs = false;
  34321. }
  34322. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34323. /**
  34324. * Specifies if the material needs to be re-calculated
  34325. */
  34326. get: function () {
  34327. return this._isDirty;
  34328. },
  34329. enumerable: true,
  34330. configurable: true
  34331. });
  34332. /**
  34333. * Marks the material to indicate that it has been re-calculated
  34334. */
  34335. MaterialDefines.prototype.markAsProcessed = function () {
  34336. this._isDirty = false;
  34337. this._areAttributesDirty = false;
  34338. this._areTexturesDirty = false;
  34339. this._areFresnelDirty = false;
  34340. this._areLightsDirty = false;
  34341. this._areMiscDirty = false;
  34342. this._areImageProcessingDirty = false;
  34343. };
  34344. /**
  34345. * Marks the material to indicate that it needs to be re-calculated
  34346. */
  34347. MaterialDefines.prototype.markAsUnprocessed = function () {
  34348. this._isDirty = true;
  34349. };
  34350. /**
  34351. * Marks the material to indicate all of its defines need to be re-calculated
  34352. */
  34353. MaterialDefines.prototype.markAllAsDirty = function () {
  34354. this._areTexturesDirty = true;
  34355. this._areAttributesDirty = true;
  34356. this._areLightsDirty = true;
  34357. this._areFresnelDirty = true;
  34358. this._areMiscDirty = true;
  34359. this._areImageProcessingDirty = true;
  34360. this._isDirty = true;
  34361. };
  34362. /**
  34363. * Marks the material to indicate that image processing needs to be re-calculated
  34364. */
  34365. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34366. this._areImageProcessingDirty = true;
  34367. this._isDirty = true;
  34368. };
  34369. /**
  34370. * Marks the material to indicate the lights need to be re-calculated
  34371. */
  34372. MaterialDefines.prototype.markAsLightDirty = function () {
  34373. this._areLightsDirty = true;
  34374. this._isDirty = true;
  34375. };
  34376. /**
  34377. * Marks the attribute state as changed
  34378. */
  34379. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34380. this._areAttributesDirty = true;
  34381. this._isDirty = true;
  34382. };
  34383. /**
  34384. * Marks the texture state as changed
  34385. */
  34386. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34387. this._areTexturesDirty = true;
  34388. this._isDirty = true;
  34389. };
  34390. /**
  34391. * Marks the fresnel state as changed
  34392. */
  34393. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34394. this._areFresnelDirty = true;
  34395. this._isDirty = true;
  34396. };
  34397. /**
  34398. * Marks the misc state as changed
  34399. */
  34400. MaterialDefines.prototype.markAsMiscDirty = function () {
  34401. this._areMiscDirty = true;
  34402. this._isDirty = true;
  34403. };
  34404. /**
  34405. * Rebuilds the material defines
  34406. */
  34407. MaterialDefines.prototype.rebuild = function () {
  34408. if (this._keys) {
  34409. delete this._keys;
  34410. }
  34411. this._keys = [];
  34412. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34413. var key = _a[_i];
  34414. if (key[0] === "_") {
  34415. continue;
  34416. }
  34417. this._keys.push(key);
  34418. }
  34419. };
  34420. /**
  34421. * Specifies if two material defines are equal
  34422. * @param other - A material define instance to compare to
  34423. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34424. */
  34425. MaterialDefines.prototype.isEqual = function (other) {
  34426. if (this._keys.length !== other._keys.length) {
  34427. return false;
  34428. }
  34429. for (var index = 0; index < this._keys.length; index++) {
  34430. var prop = this._keys[index];
  34431. if (this[prop] !== other[prop]) {
  34432. return false;
  34433. }
  34434. }
  34435. return true;
  34436. };
  34437. /**
  34438. * Clones this instance's defines to another instance
  34439. * @param other - material defines to clone values to
  34440. */
  34441. MaterialDefines.prototype.cloneTo = function (other) {
  34442. if (this._keys.length !== other._keys.length) {
  34443. other._keys = this._keys.slice(0);
  34444. }
  34445. for (var index = 0; index < this._keys.length; index++) {
  34446. var prop = this._keys[index];
  34447. other[prop] = this[prop];
  34448. }
  34449. };
  34450. /**
  34451. * Resets the material define values
  34452. */
  34453. MaterialDefines.prototype.reset = function () {
  34454. for (var index = 0; index < this._keys.length; index++) {
  34455. var prop = this._keys[index];
  34456. var type = typeof this[prop];
  34457. switch (type) {
  34458. case "number":
  34459. this[prop] = 0;
  34460. break;
  34461. case "string":
  34462. this[prop] = "";
  34463. break;
  34464. default:
  34465. this[prop] = false;
  34466. break;
  34467. }
  34468. }
  34469. };
  34470. /**
  34471. * Converts the material define values to a string
  34472. * @returns - String of material define information
  34473. */
  34474. MaterialDefines.prototype.toString = function () {
  34475. var result = "";
  34476. for (var index = 0; index < this._keys.length; index++) {
  34477. var prop = this._keys[index];
  34478. var value = this[prop];
  34479. var type = typeof value;
  34480. switch (type) {
  34481. case "number":
  34482. case "string":
  34483. result += "#define " + prop + " " + value + "\n";
  34484. break;
  34485. default:
  34486. if (value) {
  34487. result += "#define " + prop + "\n";
  34488. }
  34489. break;
  34490. }
  34491. }
  34492. return result;
  34493. };
  34494. return MaterialDefines;
  34495. }());
  34496. BABYLON.MaterialDefines = MaterialDefines;
  34497. /**
  34498. * Base class for the main features of a material in Babylon.js
  34499. */
  34500. var Material = /** @class */ (function () {
  34501. /**
  34502. * Creates a material instance
  34503. * @param name defines the name of the material
  34504. * @param scene defines the scene to reference
  34505. * @param doNotAdd specifies if the material should be added to the scene
  34506. */
  34507. function Material(name, scene, doNotAdd) {
  34508. /**
  34509. * Specifies if the ready state should be checked on each call
  34510. */
  34511. this.checkReadyOnEveryCall = false;
  34512. /**
  34513. * Specifies if the ready state should be checked once
  34514. */
  34515. this.checkReadyOnlyOnce = false;
  34516. /**
  34517. * The state of the material
  34518. */
  34519. this.state = "";
  34520. /**
  34521. * The alpha value of the material
  34522. */
  34523. this._alpha = 1.0;
  34524. /**
  34525. * Specifies if back face culling is enabled
  34526. */
  34527. this._backFaceCulling = true;
  34528. /**
  34529. * Gets a boolean indicating that current material needs to register RTT
  34530. */
  34531. this.hasRenderTargetTextures = false;
  34532. /**
  34533. * Specifies if the material should be serialized
  34534. */
  34535. this.doNotSerialize = false;
  34536. /**
  34537. * Specifies if the effect should be stored on sub meshes
  34538. */
  34539. this.storeEffectOnSubMeshes = false;
  34540. /**
  34541. * An event triggered when the material is disposed
  34542. */
  34543. this.onDisposeObservable = new BABYLON.Observable();
  34544. /**
  34545. * Stores the value of the alpha mode
  34546. */
  34547. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34548. /**
  34549. * Stores the state of the need depth pre-pass value
  34550. */
  34551. this._needDepthPrePass = false;
  34552. /**
  34553. * Specifies if depth writing should be disabled
  34554. */
  34555. this.disableDepthWrite = false;
  34556. /**
  34557. * Specifies if depth writing should be forced
  34558. */
  34559. this.forceDepthWrite = false;
  34560. /**
  34561. * Specifies if there should be a separate pass for culling
  34562. */
  34563. this.separateCullingPass = false;
  34564. /**
  34565. * Stores the state specifing if fog should be enabled
  34566. */
  34567. this._fogEnabled = true;
  34568. /**
  34569. * Stores the size of points
  34570. */
  34571. this.pointSize = 1.0;
  34572. /**
  34573. * Stores the z offset value
  34574. */
  34575. this.zOffset = 0;
  34576. /**
  34577. * @hidden
  34578. * Specifies if the material was previously ready
  34579. */
  34580. this._wasPreviouslyReady = false;
  34581. /**
  34582. * Stores the fill mode state
  34583. */
  34584. this._fillMode = Material.TriangleFillMode;
  34585. this.name = name;
  34586. this.id = name || BABYLON.Tools.RandomId();
  34587. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34588. this.uniqueId = this._scene.getUniqueId();
  34589. if (this._scene.useRightHandedSystem) {
  34590. this.sideOrientation = Material.ClockWiseSideOrientation;
  34591. }
  34592. else {
  34593. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34594. }
  34595. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34596. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34597. if (!doNotAdd) {
  34598. this._scene.materials.push(this);
  34599. }
  34600. }
  34601. Object.defineProperty(Material, "TriangleFillMode", {
  34602. /**
  34603. * Returns the triangle fill mode
  34604. */
  34605. get: function () {
  34606. return Material._TriangleFillMode;
  34607. },
  34608. enumerable: true,
  34609. configurable: true
  34610. });
  34611. Object.defineProperty(Material, "WireFrameFillMode", {
  34612. /**
  34613. * Returns the wireframe mode
  34614. */
  34615. get: function () {
  34616. return Material._WireFrameFillMode;
  34617. },
  34618. enumerable: true,
  34619. configurable: true
  34620. });
  34621. Object.defineProperty(Material, "PointFillMode", {
  34622. /**
  34623. * Returns the point fill mode
  34624. */
  34625. get: function () {
  34626. return Material._PointFillMode;
  34627. },
  34628. enumerable: true,
  34629. configurable: true
  34630. });
  34631. Object.defineProperty(Material, "PointListDrawMode", {
  34632. /**
  34633. * Returns the point list draw mode
  34634. */
  34635. get: function () {
  34636. return Material._PointListDrawMode;
  34637. },
  34638. enumerable: true,
  34639. configurable: true
  34640. });
  34641. Object.defineProperty(Material, "LineListDrawMode", {
  34642. /**
  34643. * Returns the line list draw mode
  34644. */
  34645. get: function () {
  34646. return Material._LineListDrawMode;
  34647. },
  34648. enumerable: true,
  34649. configurable: true
  34650. });
  34651. Object.defineProperty(Material, "LineLoopDrawMode", {
  34652. /**
  34653. * Returns the line loop draw mode
  34654. */
  34655. get: function () {
  34656. return Material._LineLoopDrawMode;
  34657. },
  34658. enumerable: true,
  34659. configurable: true
  34660. });
  34661. Object.defineProperty(Material, "LineStripDrawMode", {
  34662. /**
  34663. * Returns the line strip draw mode
  34664. */
  34665. get: function () {
  34666. return Material._LineStripDrawMode;
  34667. },
  34668. enumerable: true,
  34669. configurable: true
  34670. });
  34671. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34672. /**
  34673. * Returns the triangle strip draw mode
  34674. */
  34675. get: function () {
  34676. return Material._TriangleStripDrawMode;
  34677. },
  34678. enumerable: true,
  34679. configurable: true
  34680. });
  34681. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34682. /**
  34683. * Returns the triangle fan draw mode
  34684. */
  34685. get: function () {
  34686. return Material._TriangleFanDrawMode;
  34687. },
  34688. enumerable: true,
  34689. configurable: true
  34690. });
  34691. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34692. /**
  34693. * Returns the clock-wise side orientation
  34694. */
  34695. get: function () {
  34696. return Material._ClockWiseSideOrientation;
  34697. },
  34698. enumerable: true,
  34699. configurable: true
  34700. });
  34701. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34702. /**
  34703. * Returns the counter clock-wise side orientation
  34704. */
  34705. get: function () {
  34706. return Material._CounterClockWiseSideOrientation;
  34707. },
  34708. enumerable: true,
  34709. configurable: true
  34710. });
  34711. Object.defineProperty(Material, "TextureDirtyFlag", {
  34712. /**
  34713. * Returns the dirty texture flag value
  34714. */
  34715. get: function () {
  34716. return Material._TextureDirtyFlag;
  34717. },
  34718. enumerable: true,
  34719. configurable: true
  34720. });
  34721. Object.defineProperty(Material, "LightDirtyFlag", {
  34722. /**
  34723. * Returns the dirty light flag value
  34724. */
  34725. get: function () {
  34726. return Material._LightDirtyFlag;
  34727. },
  34728. enumerable: true,
  34729. configurable: true
  34730. });
  34731. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34732. /**
  34733. * Returns the dirty fresnel flag value
  34734. */
  34735. get: function () {
  34736. return Material._FresnelDirtyFlag;
  34737. },
  34738. enumerable: true,
  34739. configurable: true
  34740. });
  34741. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34742. /**
  34743. * Returns the dirty attributes flag value
  34744. */
  34745. get: function () {
  34746. return Material._AttributesDirtyFlag;
  34747. },
  34748. enumerable: true,
  34749. configurable: true
  34750. });
  34751. Object.defineProperty(Material, "MiscDirtyFlag", {
  34752. /**
  34753. * Returns the dirty misc flag value
  34754. */
  34755. get: function () {
  34756. return Material._MiscDirtyFlag;
  34757. },
  34758. enumerable: true,
  34759. configurable: true
  34760. });
  34761. Object.defineProperty(Material.prototype, "alpha", {
  34762. /**
  34763. * Gets the alpha value of the material
  34764. */
  34765. get: function () {
  34766. return this._alpha;
  34767. },
  34768. /**
  34769. * Sets the alpha value of the material
  34770. */
  34771. set: function (value) {
  34772. if (this._alpha === value) {
  34773. return;
  34774. }
  34775. this._alpha = value;
  34776. this.markAsDirty(Material.MiscDirtyFlag);
  34777. },
  34778. enumerable: true,
  34779. configurable: true
  34780. });
  34781. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34782. /**
  34783. * Gets the back-face culling state
  34784. */
  34785. get: function () {
  34786. return this._backFaceCulling;
  34787. },
  34788. /**
  34789. * Sets the back-face culling state
  34790. */
  34791. set: function (value) {
  34792. if (this._backFaceCulling === value) {
  34793. return;
  34794. }
  34795. this._backFaceCulling = value;
  34796. this.markAsDirty(Material.TextureDirtyFlag);
  34797. },
  34798. enumerable: true,
  34799. configurable: true
  34800. });
  34801. Object.defineProperty(Material.prototype, "onDispose", {
  34802. /**
  34803. * Called during a dispose event
  34804. */
  34805. set: function (callback) {
  34806. if (this._onDisposeObserver) {
  34807. this.onDisposeObservable.remove(this._onDisposeObserver);
  34808. }
  34809. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34810. },
  34811. enumerable: true,
  34812. configurable: true
  34813. });
  34814. Object.defineProperty(Material.prototype, "onBindObservable", {
  34815. /**
  34816. * An event triggered when the material is bound
  34817. */
  34818. get: function () {
  34819. if (!this._onBindObservable) {
  34820. this._onBindObservable = new BABYLON.Observable();
  34821. }
  34822. return this._onBindObservable;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. Object.defineProperty(Material.prototype, "onBind", {
  34828. /**
  34829. * Called during a bind event
  34830. */
  34831. set: function (callback) {
  34832. if (this._onBindObserver) {
  34833. this.onBindObservable.remove(this._onBindObserver);
  34834. }
  34835. this._onBindObserver = this.onBindObservable.add(callback);
  34836. },
  34837. enumerable: true,
  34838. configurable: true
  34839. });
  34840. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34841. /**
  34842. * An event triggered when the material is unbound
  34843. */
  34844. get: function () {
  34845. if (!this._onUnBindObservable) {
  34846. this._onUnBindObservable = new BABYLON.Observable();
  34847. }
  34848. return this._onUnBindObservable;
  34849. },
  34850. enumerable: true,
  34851. configurable: true
  34852. });
  34853. Object.defineProperty(Material.prototype, "alphaMode", {
  34854. /**
  34855. * Gets the value of the alpha mode
  34856. */
  34857. get: function () {
  34858. return this._alphaMode;
  34859. },
  34860. /**
  34861. * Sets the value of the alpha mode.
  34862. *
  34863. * | Value | Type | Description |
  34864. * | --- | --- | --- |
  34865. * | 0 | ALPHA_DISABLE | |
  34866. * | 1 | ALPHA_ADD | |
  34867. * | 2 | ALPHA_COMBINE | |
  34868. * | 3 | ALPHA_SUBTRACT | |
  34869. * | 4 | ALPHA_MULTIPLY | |
  34870. * | 5 | ALPHA_MAXIMIZED | |
  34871. * | 6 | ALPHA_ONEONE | |
  34872. * | 7 | ALPHA_PREMULTIPLIED | |
  34873. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34874. * | 9 | ALPHA_INTERPOLATE | |
  34875. * | 10 | ALPHA_SCREENMODE | |
  34876. *
  34877. */
  34878. set: function (value) {
  34879. if (this._alphaMode === value) {
  34880. return;
  34881. }
  34882. this._alphaMode = value;
  34883. this.markAsDirty(Material.TextureDirtyFlag);
  34884. },
  34885. enumerable: true,
  34886. configurable: true
  34887. });
  34888. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34889. /**
  34890. * Gets the depth pre-pass value
  34891. */
  34892. get: function () {
  34893. return this._needDepthPrePass;
  34894. },
  34895. /**
  34896. * Sets the need depth pre-pass value
  34897. */
  34898. set: function (value) {
  34899. if (this._needDepthPrePass === value) {
  34900. return;
  34901. }
  34902. this._needDepthPrePass = value;
  34903. if (this._needDepthPrePass) {
  34904. this.checkReadyOnEveryCall = true;
  34905. }
  34906. },
  34907. enumerable: true,
  34908. configurable: true
  34909. });
  34910. Object.defineProperty(Material.prototype, "fogEnabled", {
  34911. /**
  34912. * Gets the value of the fog enabled state
  34913. */
  34914. get: function () {
  34915. return this._fogEnabled;
  34916. },
  34917. /**
  34918. * Sets the state for enabling fog
  34919. */
  34920. set: function (value) {
  34921. if (this._fogEnabled === value) {
  34922. return;
  34923. }
  34924. this._fogEnabled = value;
  34925. this.markAsDirty(Material.MiscDirtyFlag);
  34926. },
  34927. enumerable: true,
  34928. configurable: true
  34929. });
  34930. Object.defineProperty(Material.prototype, "wireframe", {
  34931. /**
  34932. * Gets a value specifying if wireframe mode is enabled
  34933. */
  34934. get: function () {
  34935. switch (this._fillMode) {
  34936. case Material.WireFrameFillMode:
  34937. case Material.LineListDrawMode:
  34938. case Material.LineLoopDrawMode:
  34939. case Material.LineStripDrawMode:
  34940. return true;
  34941. }
  34942. return this._scene.forceWireframe;
  34943. },
  34944. /**
  34945. * Sets the state of wireframe mode
  34946. */
  34947. set: function (value) {
  34948. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34949. },
  34950. enumerable: true,
  34951. configurable: true
  34952. });
  34953. Object.defineProperty(Material.prototype, "pointsCloud", {
  34954. /**
  34955. * Gets the value specifying if point clouds are enabled
  34956. */
  34957. get: function () {
  34958. switch (this._fillMode) {
  34959. case Material.PointFillMode:
  34960. case Material.PointListDrawMode:
  34961. return true;
  34962. }
  34963. return this._scene.forcePointsCloud;
  34964. },
  34965. /**
  34966. * Sets the state of point cloud mode
  34967. */
  34968. set: function (value) {
  34969. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34970. },
  34971. enumerable: true,
  34972. configurable: true
  34973. });
  34974. Object.defineProperty(Material.prototype, "fillMode", {
  34975. /**
  34976. * Gets the material fill mode
  34977. */
  34978. get: function () {
  34979. return this._fillMode;
  34980. },
  34981. /**
  34982. * Sets the material fill mode
  34983. */
  34984. set: function (value) {
  34985. if (this._fillMode === value) {
  34986. return;
  34987. }
  34988. this._fillMode = value;
  34989. this.markAsDirty(Material.MiscDirtyFlag);
  34990. },
  34991. enumerable: true,
  34992. configurable: true
  34993. });
  34994. /**
  34995. * Returns a string representation of the current material
  34996. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34997. * @returns a string with material information
  34998. */
  34999. Material.prototype.toString = function (fullDetails) {
  35000. var ret = "Name: " + this.name;
  35001. if (fullDetails) {
  35002. }
  35003. return ret;
  35004. };
  35005. /**
  35006. * Gets the class name of the material
  35007. * @returns a string with the class name of the material
  35008. */
  35009. Material.prototype.getClassName = function () {
  35010. return "Material";
  35011. };
  35012. Object.defineProperty(Material.prototype, "isFrozen", {
  35013. /**
  35014. * Specifies if updates for the material been locked
  35015. */
  35016. get: function () {
  35017. return this.checkReadyOnlyOnce;
  35018. },
  35019. enumerable: true,
  35020. configurable: true
  35021. });
  35022. /**
  35023. * Locks updates for the material
  35024. */
  35025. Material.prototype.freeze = function () {
  35026. this.checkReadyOnlyOnce = true;
  35027. };
  35028. /**
  35029. * Unlocks updates for the material
  35030. */
  35031. Material.prototype.unfreeze = function () {
  35032. this.checkReadyOnlyOnce = false;
  35033. };
  35034. /**
  35035. * Specifies if the material is ready to be used
  35036. * @param mesh defines the mesh to check
  35037. * @param useInstances specifies if instances should be used
  35038. * @returns a boolean indicating if the material is ready to be used
  35039. */
  35040. Material.prototype.isReady = function (mesh, useInstances) {
  35041. return true;
  35042. };
  35043. /**
  35044. * Specifies that the submesh is ready to be used
  35045. * @param mesh defines the mesh to check
  35046. * @param subMesh defines which submesh to check
  35047. * @param useInstances specifies that instances should be used
  35048. * @returns a boolean indicating that the submesh is ready or not
  35049. */
  35050. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35051. return false;
  35052. };
  35053. /**
  35054. * Returns the material effect
  35055. * @returns the effect associated with the material
  35056. */
  35057. Material.prototype.getEffect = function () {
  35058. return this._effect;
  35059. };
  35060. /**
  35061. * Returns the current scene
  35062. * @returns a Scene
  35063. */
  35064. Material.prototype.getScene = function () {
  35065. return this._scene;
  35066. };
  35067. /**
  35068. * Specifies if the material will require alpha blending
  35069. * @returns a boolean specifying if alpha blending is needed
  35070. */
  35071. Material.prototype.needAlphaBlending = function () {
  35072. return (this.alpha < 1.0);
  35073. };
  35074. /**
  35075. * Specifies if the mesh will require alpha blending
  35076. * @param mesh defines the mesh to check
  35077. * @returns a boolean specifying if alpha blending is needed for the mesh
  35078. */
  35079. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35080. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35081. };
  35082. /**
  35083. * Specifies if this material should be rendered in alpha test mode
  35084. * @returns a boolean specifying if an alpha test is needed.
  35085. */
  35086. Material.prototype.needAlphaTesting = function () {
  35087. return false;
  35088. };
  35089. /**
  35090. * Gets the texture used for the alpha test
  35091. * @returns the texture to use for alpha testing
  35092. */
  35093. Material.prototype.getAlphaTestTexture = function () {
  35094. return null;
  35095. };
  35096. /**
  35097. * Marks the material to indicate that it needs to be re-calculated
  35098. */
  35099. Material.prototype.markDirty = function () {
  35100. this._wasPreviouslyReady = false;
  35101. };
  35102. /** @hidden */
  35103. Material.prototype._preBind = function (effect, overrideOrientation) {
  35104. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35105. var engine = this._scene.getEngine();
  35106. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35107. var reverse = orientation === Material.ClockWiseSideOrientation;
  35108. engine.enableEffect(effect ? effect : this._effect);
  35109. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35110. return reverse;
  35111. };
  35112. /**
  35113. * Binds the material to the mesh
  35114. * @param world defines the world transformation matrix
  35115. * @param mesh defines the mesh to bind the material to
  35116. */
  35117. Material.prototype.bind = function (world, mesh) {
  35118. };
  35119. /**
  35120. * Binds the submesh to the material
  35121. * @param world defines the world transformation matrix
  35122. * @param mesh defines the mesh containing the submesh
  35123. * @param subMesh defines the submesh to bind the material to
  35124. */
  35125. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35126. };
  35127. /**
  35128. * Binds the world matrix to the material
  35129. * @param world defines the world transformation matrix
  35130. */
  35131. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35132. };
  35133. /**
  35134. * Binds the scene's uniform buffer to the effect.
  35135. * @param effect defines the effect to bind to the scene uniform buffer
  35136. * @param sceneUbo defines the uniform buffer storing scene data
  35137. */
  35138. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35139. sceneUbo.bindToEffect(effect, "Scene");
  35140. };
  35141. /**
  35142. * Binds the view matrix to the effect
  35143. * @param effect defines the effect to bind the view matrix to
  35144. */
  35145. Material.prototype.bindView = function (effect) {
  35146. if (!this._useUBO) {
  35147. effect.setMatrix("view", this.getScene().getViewMatrix());
  35148. }
  35149. else {
  35150. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35151. }
  35152. };
  35153. /**
  35154. * Binds the view projection matrix to the effect
  35155. * @param effect defines the effect to bind the view projection matrix to
  35156. */
  35157. Material.prototype.bindViewProjection = function (effect) {
  35158. if (!this._useUBO) {
  35159. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35160. }
  35161. else {
  35162. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35163. }
  35164. };
  35165. /**
  35166. * Specifies if material alpha testing should be turned on for the mesh
  35167. * @param mesh defines the mesh to check
  35168. */
  35169. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35170. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35171. };
  35172. /**
  35173. * Processes to execute after binding the material to a mesh
  35174. * @param mesh defines the rendered mesh
  35175. */
  35176. Material.prototype._afterBind = function (mesh) {
  35177. this._scene._cachedMaterial = this;
  35178. if (mesh) {
  35179. this._scene._cachedVisibility = mesh.visibility;
  35180. }
  35181. else {
  35182. this._scene._cachedVisibility = 1;
  35183. }
  35184. if (this._onBindObservable && mesh) {
  35185. this._onBindObservable.notifyObservers(mesh);
  35186. }
  35187. if (this.disableDepthWrite) {
  35188. var engine = this._scene.getEngine();
  35189. this._cachedDepthWriteState = engine.getDepthWrite();
  35190. engine.setDepthWrite(false);
  35191. }
  35192. };
  35193. /**
  35194. * Unbinds the material from the mesh
  35195. */
  35196. Material.prototype.unbind = function () {
  35197. if (this._onUnBindObservable) {
  35198. this._onUnBindObservable.notifyObservers(this);
  35199. }
  35200. if (this.disableDepthWrite) {
  35201. var engine = this._scene.getEngine();
  35202. engine.setDepthWrite(this._cachedDepthWriteState);
  35203. }
  35204. };
  35205. /**
  35206. * Gets the active textures from the material
  35207. * @returns an array of textures
  35208. */
  35209. Material.prototype.getActiveTextures = function () {
  35210. return [];
  35211. };
  35212. /**
  35213. * Specifies if the material uses a texture
  35214. * @param texture defines the texture to check against the material
  35215. * @returns a boolean specifying if the material uses the texture
  35216. */
  35217. Material.prototype.hasTexture = function (texture) {
  35218. return false;
  35219. };
  35220. /**
  35221. * Makes a duplicate of the material, and gives it a new name
  35222. * @param name defines the new name for the duplicated material
  35223. * @returns the cloned material
  35224. */
  35225. Material.prototype.clone = function (name) {
  35226. return null;
  35227. };
  35228. /**
  35229. * Gets the meshes bound to the material
  35230. * @returns an array of meshes bound to the material
  35231. */
  35232. Material.prototype.getBindedMeshes = function () {
  35233. var result = new Array();
  35234. for (var index = 0; index < this._scene.meshes.length; index++) {
  35235. var mesh = this._scene.meshes[index];
  35236. if (mesh.material === this) {
  35237. result.push(mesh);
  35238. }
  35239. }
  35240. return result;
  35241. };
  35242. /**
  35243. * Force shader compilation
  35244. * @param mesh defines the mesh associated with this material
  35245. * @param onCompiled defines a function to execute once the material is compiled
  35246. * @param options defines the options to configure the compilation
  35247. */
  35248. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35249. var _this = this;
  35250. var localOptions = __assign({ clipPlane: false }, options);
  35251. var subMesh = new BABYLON.BaseSubMesh();
  35252. var scene = this.getScene();
  35253. var checkReady = function () {
  35254. if (!_this._scene || !_this._scene.getEngine()) {
  35255. return;
  35256. }
  35257. if (subMesh._materialDefines) {
  35258. subMesh._materialDefines._renderId = -1;
  35259. }
  35260. var clipPlaneState = scene.clipPlane;
  35261. if (localOptions.clipPlane) {
  35262. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35263. }
  35264. if (_this.storeEffectOnSubMeshes) {
  35265. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35266. if (onCompiled) {
  35267. onCompiled(_this);
  35268. }
  35269. }
  35270. else {
  35271. setTimeout(checkReady, 16);
  35272. }
  35273. }
  35274. else {
  35275. if (_this.isReady(mesh)) {
  35276. if (onCompiled) {
  35277. onCompiled(_this);
  35278. }
  35279. }
  35280. else {
  35281. setTimeout(checkReady, 16);
  35282. }
  35283. }
  35284. if (localOptions.clipPlane) {
  35285. scene.clipPlane = clipPlaneState;
  35286. }
  35287. };
  35288. checkReady();
  35289. };
  35290. /**
  35291. * Force shader compilation
  35292. * @param mesh defines the mesh that will use this material
  35293. * @param options defines additional options for compiling the shaders
  35294. * @returns a promise that resolves when the compilation completes
  35295. */
  35296. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35297. var _this = this;
  35298. return new Promise(function (resolve) {
  35299. _this.forceCompilation(mesh, function () {
  35300. resolve();
  35301. }, options);
  35302. });
  35303. };
  35304. /**
  35305. * Marks a define in the material to indicate that it needs to be re-computed
  35306. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35307. */
  35308. Material.prototype.markAsDirty = function (flag) {
  35309. if (flag & Material.TextureDirtyFlag) {
  35310. this._markAllSubMeshesAsTexturesDirty();
  35311. }
  35312. if (flag & Material.LightDirtyFlag) {
  35313. this._markAllSubMeshesAsLightsDirty();
  35314. }
  35315. if (flag & Material.FresnelDirtyFlag) {
  35316. this._markAllSubMeshesAsFresnelDirty();
  35317. }
  35318. if (flag & Material.AttributesDirtyFlag) {
  35319. this._markAllSubMeshesAsAttributesDirty();
  35320. }
  35321. if (flag & Material.MiscDirtyFlag) {
  35322. this._markAllSubMeshesAsMiscDirty();
  35323. }
  35324. this.getScene().resetCachedMaterial();
  35325. };
  35326. /**
  35327. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35328. * @param func defines a function which checks material defines against the submeshes
  35329. */
  35330. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35331. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35332. var mesh = _a[_i];
  35333. if (!mesh.subMeshes) {
  35334. continue;
  35335. }
  35336. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35337. var subMesh = _c[_b];
  35338. if (subMesh.getMaterial() !== this) {
  35339. continue;
  35340. }
  35341. if (!subMesh._materialDefines) {
  35342. continue;
  35343. }
  35344. func(subMesh._materialDefines);
  35345. }
  35346. }
  35347. };
  35348. /**
  35349. * Indicates that image processing needs to be re-calculated for all submeshes
  35350. */
  35351. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35352. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35353. };
  35354. /**
  35355. * Indicates that textures need to be re-calculated for all submeshes
  35356. */
  35357. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35358. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35359. };
  35360. /**
  35361. * Indicates that fresnel needs to be re-calculated for all submeshes
  35362. */
  35363. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35364. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35365. };
  35366. /**
  35367. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35368. */
  35369. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35370. this._markAllSubMeshesAsDirty(function (defines) {
  35371. defines.markAsFresnelDirty();
  35372. defines.markAsMiscDirty();
  35373. });
  35374. };
  35375. /**
  35376. * Indicates that lights need to be re-calculated for all submeshes
  35377. */
  35378. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35379. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35380. };
  35381. /**
  35382. * Indicates that attributes need to be re-calculated for all submeshes
  35383. */
  35384. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35385. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35386. };
  35387. /**
  35388. * Indicates that misc needs to be re-calculated for all submeshes
  35389. */
  35390. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35391. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35392. };
  35393. /**
  35394. * Indicates that textures and misc need to be re-calculated for all submeshes
  35395. */
  35396. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35397. this._markAllSubMeshesAsDirty(function (defines) {
  35398. defines.markAsTexturesDirty();
  35399. defines.markAsMiscDirty();
  35400. });
  35401. };
  35402. /**
  35403. * Disposes the material
  35404. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35405. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35406. */
  35407. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35408. // Animations
  35409. this.getScene().stopAnimation(this);
  35410. this.getScene().freeProcessedMaterials();
  35411. // Remove from scene
  35412. var index = this._scene.materials.indexOf(this);
  35413. if (index >= 0) {
  35414. this._scene.materials.splice(index, 1);
  35415. }
  35416. // Remove from meshes
  35417. for (index = 0; index < this._scene.meshes.length; index++) {
  35418. var mesh = this._scene.meshes[index];
  35419. if (mesh.material === this) {
  35420. mesh.material = null;
  35421. if (mesh.geometry) {
  35422. var geometry = (mesh.geometry);
  35423. if (this.storeEffectOnSubMeshes) {
  35424. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35425. var subMesh = _a[_i];
  35426. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35427. if (forceDisposeEffect && subMesh._materialEffect) {
  35428. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35429. }
  35430. }
  35431. }
  35432. else {
  35433. geometry._releaseVertexArrayObject(this._effect);
  35434. }
  35435. }
  35436. }
  35437. }
  35438. this._uniformBuffer.dispose();
  35439. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35440. if (forceDisposeEffect && this._effect) {
  35441. if (!this.storeEffectOnSubMeshes) {
  35442. this._scene.getEngine()._releaseEffect(this._effect);
  35443. }
  35444. this._effect = null;
  35445. }
  35446. // Callback
  35447. this.onDisposeObservable.notifyObservers(this);
  35448. this.onDisposeObservable.clear();
  35449. if (this._onBindObservable) {
  35450. this._onBindObservable.clear();
  35451. }
  35452. if (this._onUnBindObservable) {
  35453. this._onUnBindObservable.clear();
  35454. }
  35455. };
  35456. /**
  35457. * Serializes this material
  35458. * @returns the serialized material object
  35459. */
  35460. Material.prototype.serialize = function () {
  35461. return BABYLON.SerializationHelper.Serialize(this);
  35462. };
  35463. /**
  35464. * Creates a MultiMaterial from parsed MultiMaterial data.
  35465. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35466. * @param scene defines the hosting scene
  35467. * @returns a new MultiMaterial
  35468. */
  35469. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35470. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35471. multiMaterial.id = parsedMultiMaterial.id;
  35472. if (BABYLON.Tags) {
  35473. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35474. }
  35475. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35476. var subMatId = parsedMultiMaterial.materials[matIndex];
  35477. if (subMatId) {
  35478. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35479. }
  35480. else {
  35481. multiMaterial.subMaterials.push(null);
  35482. }
  35483. }
  35484. return multiMaterial;
  35485. };
  35486. /**
  35487. * Creates a material from parsed material data
  35488. * @param parsedMaterial defines parsed material data
  35489. * @param scene defines the hosting scene
  35490. * @param rootUrl defines the root URL to use to load textures
  35491. * @returns a new material
  35492. */
  35493. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35494. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35495. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35496. }
  35497. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35498. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35499. if (!BABYLON.LegacyPBRMaterial) {
  35500. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35501. return;
  35502. }
  35503. }
  35504. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35505. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35506. };
  35507. // Triangle views
  35508. Material._TriangleFillMode = 0;
  35509. Material._WireFrameFillMode = 1;
  35510. Material._PointFillMode = 2;
  35511. // Draw modes
  35512. Material._PointListDrawMode = 3;
  35513. Material._LineListDrawMode = 4;
  35514. Material._LineLoopDrawMode = 5;
  35515. Material._LineStripDrawMode = 6;
  35516. Material._TriangleStripDrawMode = 7;
  35517. Material._TriangleFanDrawMode = 8;
  35518. /**
  35519. * Stores the clock-wise side orientation
  35520. */
  35521. Material._ClockWiseSideOrientation = 0;
  35522. /**
  35523. * Stores the counter clock-wise side orientation
  35524. */
  35525. Material._CounterClockWiseSideOrientation = 1;
  35526. /**
  35527. * The dirty texture flag value
  35528. */
  35529. Material._TextureDirtyFlag = 1;
  35530. /**
  35531. * The dirty light flag value
  35532. */
  35533. Material._LightDirtyFlag = 2;
  35534. /**
  35535. * The dirty fresnel flag value
  35536. */
  35537. Material._FresnelDirtyFlag = 4;
  35538. /**
  35539. * The dirty attribute flag value
  35540. */
  35541. Material._AttributesDirtyFlag = 8;
  35542. /**
  35543. * The dirty misc flag value
  35544. */
  35545. Material._MiscDirtyFlag = 16;
  35546. __decorate([
  35547. BABYLON.serialize()
  35548. ], Material.prototype, "id", void 0);
  35549. __decorate([
  35550. BABYLON.serialize()
  35551. ], Material.prototype, "uniqueId", void 0);
  35552. __decorate([
  35553. BABYLON.serialize()
  35554. ], Material.prototype, "name", void 0);
  35555. __decorate([
  35556. BABYLON.serialize()
  35557. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35558. __decorate([
  35559. BABYLON.serialize()
  35560. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35561. __decorate([
  35562. BABYLON.serialize()
  35563. ], Material.prototype, "state", void 0);
  35564. __decorate([
  35565. BABYLON.serialize("alpha")
  35566. ], Material.prototype, "_alpha", void 0);
  35567. __decorate([
  35568. BABYLON.serialize("backFaceCulling")
  35569. ], Material.prototype, "_backFaceCulling", void 0);
  35570. __decorate([
  35571. BABYLON.serialize()
  35572. ], Material.prototype, "sideOrientation", void 0);
  35573. __decorate([
  35574. BABYLON.serialize("alphaMode")
  35575. ], Material.prototype, "_alphaMode", void 0);
  35576. __decorate([
  35577. BABYLON.serialize()
  35578. ], Material.prototype, "_needDepthPrePass", void 0);
  35579. __decorate([
  35580. BABYLON.serialize()
  35581. ], Material.prototype, "disableDepthWrite", void 0);
  35582. __decorate([
  35583. BABYLON.serialize()
  35584. ], Material.prototype, "forceDepthWrite", void 0);
  35585. __decorate([
  35586. BABYLON.serialize()
  35587. ], Material.prototype, "separateCullingPass", void 0);
  35588. __decorate([
  35589. BABYLON.serialize("fogEnabled")
  35590. ], Material.prototype, "_fogEnabled", void 0);
  35591. __decorate([
  35592. BABYLON.serialize()
  35593. ], Material.prototype, "pointSize", void 0);
  35594. __decorate([
  35595. BABYLON.serialize()
  35596. ], Material.prototype, "zOffset", void 0);
  35597. __decorate([
  35598. BABYLON.serialize()
  35599. ], Material.prototype, "wireframe", null);
  35600. __decorate([
  35601. BABYLON.serialize()
  35602. ], Material.prototype, "pointsCloud", null);
  35603. __decorate([
  35604. BABYLON.serialize()
  35605. ], Material.prototype, "fillMode", null);
  35606. return Material;
  35607. }());
  35608. BABYLON.Material = Material;
  35609. })(BABYLON || (BABYLON = {}));
  35610. //# sourceMappingURL=babylon.material.js.map
  35611. var BABYLON;
  35612. (function (BABYLON) {
  35613. var UniformBuffer = /** @class */ (function () {
  35614. /**
  35615. * Uniform buffer objects.
  35616. *
  35617. * Handles blocks of uniform on the GPU.
  35618. *
  35619. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35620. *
  35621. * For more information, please refer to :
  35622. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35623. */
  35624. function UniformBuffer(engine, data, dynamic) {
  35625. this._engine = engine;
  35626. this._noUBO = !engine.supportsUniformBuffers;
  35627. this._dynamic = dynamic;
  35628. this._data = data || [];
  35629. this._uniformLocations = {};
  35630. this._uniformSizes = {};
  35631. this._uniformLocationPointer = 0;
  35632. this._needSync = false;
  35633. if (this._noUBO) {
  35634. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35635. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35636. this.updateFloat = this._updateFloatForEffect;
  35637. this.updateFloat2 = this._updateFloat2ForEffect;
  35638. this.updateFloat3 = this._updateFloat3ForEffect;
  35639. this.updateFloat4 = this._updateFloat4ForEffect;
  35640. this.updateMatrix = this._updateMatrixForEffect;
  35641. this.updateVector3 = this._updateVector3ForEffect;
  35642. this.updateVector4 = this._updateVector4ForEffect;
  35643. this.updateColor3 = this._updateColor3ForEffect;
  35644. this.updateColor4 = this._updateColor4ForEffect;
  35645. }
  35646. else {
  35647. this._engine._uniformBuffers.push(this);
  35648. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35649. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35650. this.updateFloat = this._updateFloatForUniform;
  35651. this.updateFloat2 = this._updateFloat2ForUniform;
  35652. this.updateFloat3 = this._updateFloat3ForUniform;
  35653. this.updateFloat4 = this._updateFloat4ForUniform;
  35654. this.updateMatrix = this._updateMatrixForUniform;
  35655. this.updateVector3 = this._updateVector3ForUniform;
  35656. this.updateVector4 = this._updateVector4ForUniform;
  35657. this.updateColor3 = this._updateColor3ForUniform;
  35658. this.updateColor4 = this._updateColor4ForUniform;
  35659. }
  35660. }
  35661. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35662. // Properties
  35663. /**
  35664. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35665. * or just falling back on setUniformXXX calls.
  35666. */
  35667. get: function () {
  35668. return !this._noUBO;
  35669. },
  35670. enumerable: true,
  35671. configurable: true
  35672. });
  35673. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35674. /**
  35675. * Indicates if the WebGL underlying uniform buffer is in sync
  35676. * with the javascript cache data.
  35677. */
  35678. get: function () {
  35679. return !this._needSync;
  35680. },
  35681. enumerable: true,
  35682. configurable: true
  35683. });
  35684. /**
  35685. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35686. * Also, a dynamic UniformBuffer will disable cache verification and always
  35687. * update the underlying WebGL uniform buffer to the GPU.
  35688. */
  35689. UniformBuffer.prototype.isDynamic = function () {
  35690. return this._dynamic !== undefined;
  35691. };
  35692. /**
  35693. * The data cache on JS side.
  35694. */
  35695. UniformBuffer.prototype.getData = function () {
  35696. return this._bufferData;
  35697. };
  35698. /**
  35699. * The underlying WebGL Uniform buffer.
  35700. */
  35701. UniformBuffer.prototype.getBuffer = function () {
  35702. return this._buffer;
  35703. };
  35704. /**
  35705. * std140 layout specifies how to align data within an UBO structure.
  35706. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35707. * for specs.
  35708. */
  35709. UniformBuffer.prototype._fillAlignment = function (size) {
  35710. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35711. // and 4x4 matrices
  35712. // TODO : change if other types are used
  35713. var alignment;
  35714. if (size <= 2) {
  35715. alignment = size;
  35716. }
  35717. else {
  35718. alignment = 4;
  35719. }
  35720. if ((this._uniformLocationPointer % alignment) !== 0) {
  35721. var oldPointer = this._uniformLocationPointer;
  35722. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35723. var diff = this._uniformLocationPointer - oldPointer;
  35724. for (var i = 0; i < diff; i++) {
  35725. this._data.push(0);
  35726. }
  35727. }
  35728. };
  35729. /**
  35730. * Adds an uniform in the buffer.
  35731. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35732. * for the layout to be correct !
  35733. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35734. * @param {number|number[]} size Data size, or data directly.
  35735. */
  35736. UniformBuffer.prototype.addUniform = function (name, size) {
  35737. if (this._noUBO) {
  35738. return;
  35739. }
  35740. if (this._uniformLocations[name] !== undefined) {
  35741. // Already existing uniform
  35742. return;
  35743. }
  35744. // This function must be called in the order of the shader layout !
  35745. // size can be the size of the uniform, or data directly
  35746. var data;
  35747. if (size instanceof Array) {
  35748. data = size;
  35749. size = data.length;
  35750. }
  35751. else {
  35752. size = size;
  35753. data = [];
  35754. // Fill with zeros
  35755. for (var i = 0; i < size; i++) {
  35756. data.push(0);
  35757. }
  35758. }
  35759. this._fillAlignment(size);
  35760. this._uniformSizes[name] = size;
  35761. this._uniformLocations[name] = this._uniformLocationPointer;
  35762. this._uniformLocationPointer += size;
  35763. for (var i = 0; i < size; i++) {
  35764. this._data.push(data[i]);
  35765. }
  35766. this._needSync = true;
  35767. };
  35768. /**
  35769. * Wrapper for addUniform.
  35770. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35771. * @param {Matrix} mat A 4x4 matrix.
  35772. */
  35773. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35774. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35775. };
  35776. /**
  35777. * Wrapper for addUniform.
  35778. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35779. * @param {number} x
  35780. * @param {number} y
  35781. */
  35782. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35783. var temp = [x, y];
  35784. this.addUniform(name, temp);
  35785. };
  35786. /**
  35787. * Wrapper for addUniform.
  35788. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35789. * @param {number} x
  35790. * @param {number} y
  35791. * @param {number} z
  35792. */
  35793. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35794. var temp = [x, y, z];
  35795. this.addUniform(name, temp);
  35796. };
  35797. /**
  35798. * Wrapper for addUniform.
  35799. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35800. * @param {Color3} color
  35801. */
  35802. UniformBuffer.prototype.addColor3 = function (name, color) {
  35803. var temp = new Array();
  35804. color.toArray(temp);
  35805. this.addUniform(name, temp);
  35806. };
  35807. /**
  35808. * Wrapper for addUniform.
  35809. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35810. * @param {Color3} color
  35811. * @param {number} alpha
  35812. */
  35813. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35814. var temp = new Array();
  35815. color.toArray(temp);
  35816. temp.push(alpha);
  35817. this.addUniform(name, temp);
  35818. };
  35819. /**
  35820. * Wrapper for addUniform.
  35821. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35822. * @param {Vector3} vector
  35823. */
  35824. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35825. var temp = new Array();
  35826. vector.toArray(temp);
  35827. this.addUniform(name, temp);
  35828. };
  35829. /**
  35830. * Wrapper for addUniform.
  35831. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35832. */
  35833. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35834. this.addUniform(name, 12);
  35835. };
  35836. /**
  35837. * Wrapper for addUniform.
  35838. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35839. */
  35840. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35841. this.addUniform(name, 8);
  35842. };
  35843. /**
  35844. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35845. */
  35846. UniformBuffer.prototype.create = function () {
  35847. if (this._noUBO) {
  35848. return;
  35849. }
  35850. if (this._buffer) {
  35851. return; // nothing to do
  35852. }
  35853. // See spec, alignment must be filled as a vec4
  35854. this._fillAlignment(4);
  35855. this._bufferData = new Float32Array(this._data);
  35856. this._rebuild();
  35857. this._needSync = true;
  35858. };
  35859. /** @hidden */
  35860. UniformBuffer.prototype._rebuild = function () {
  35861. if (this._noUBO) {
  35862. return;
  35863. }
  35864. if (this._dynamic) {
  35865. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35866. }
  35867. else {
  35868. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35869. }
  35870. };
  35871. /**
  35872. * Updates the WebGL Uniform Buffer on the GPU.
  35873. * If the `dynamic` flag is set to true, no cache comparison is done.
  35874. * Otherwise, the buffer will be updated only if the cache differs.
  35875. */
  35876. UniformBuffer.prototype.update = function () {
  35877. if (!this._buffer) {
  35878. this.create();
  35879. return;
  35880. }
  35881. if (!this._dynamic && !this._needSync) {
  35882. return;
  35883. }
  35884. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35885. this._needSync = false;
  35886. };
  35887. /**
  35888. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35889. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35890. * @param {number[]|Float32Array} data Flattened data
  35891. * @param {number} size Size of the data.
  35892. */
  35893. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35894. var location = this._uniformLocations[uniformName];
  35895. if (location === undefined) {
  35896. if (this._buffer) {
  35897. // Cannot add an uniform if the buffer is already created
  35898. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35899. return;
  35900. }
  35901. this.addUniform(uniformName, size);
  35902. location = this._uniformLocations[uniformName];
  35903. }
  35904. if (!this._buffer) {
  35905. this.create();
  35906. }
  35907. if (!this._dynamic) {
  35908. // Cache for static uniform buffers
  35909. var changed = false;
  35910. for (var i = 0; i < size; i++) {
  35911. if (this._bufferData[location + i] !== data[i]) {
  35912. changed = true;
  35913. this._bufferData[location + i] = data[i];
  35914. }
  35915. }
  35916. this._needSync = this._needSync || changed;
  35917. }
  35918. else {
  35919. // No cache for dynamic
  35920. for (var i = 0; i < size; i++) {
  35921. this._bufferData[location + i] = data[i];
  35922. }
  35923. }
  35924. };
  35925. // Update methods
  35926. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35927. // To match std140, matrix must be realigned
  35928. for (var i = 0; i < 3; i++) {
  35929. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35930. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35931. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35932. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35933. }
  35934. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35935. };
  35936. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35937. this._currentEffect.setMatrix3x3(name, matrix);
  35938. };
  35939. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35940. this._currentEffect.setMatrix2x2(name, matrix);
  35941. };
  35942. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35943. // To match std140, matrix must be realigned
  35944. for (var i = 0; i < 2; i++) {
  35945. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35946. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35947. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35948. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35949. }
  35950. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35951. };
  35952. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35953. this._currentEffect.setFloat(name, x);
  35954. };
  35955. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35956. UniformBuffer._tempBuffer[0] = x;
  35957. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35958. };
  35959. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35960. if (suffix === void 0) { suffix = ""; }
  35961. this._currentEffect.setFloat2(name + suffix, x, y);
  35962. };
  35963. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35964. if (suffix === void 0) { suffix = ""; }
  35965. UniformBuffer._tempBuffer[0] = x;
  35966. UniformBuffer._tempBuffer[1] = y;
  35967. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35968. };
  35969. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35970. if (suffix === void 0) { suffix = ""; }
  35971. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35972. };
  35973. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35974. if (suffix === void 0) { suffix = ""; }
  35975. UniformBuffer._tempBuffer[0] = x;
  35976. UniformBuffer._tempBuffer[1] = y;
  35977. UniformBuffer._tempBuffer[2] = z;
  35978. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35979. };
  35980. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35981. if (suffix === void 0) { suffix = ""; }
  35982. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35983. };
  35984. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35985. if (suffix === void 0) { suffix = ""; }
  35986. UniformBuffer._tempBuffer[0] = x;
  35987. UniformBuffer._tempBuffer[1] = y;
  35988. UniformBuffer._tempBuffer[2] = z;
  35989. UniformBuffer._tempBuffer[3] = w;
  35990. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35991. };
  35992. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35993. this._currentEffect.setMatrix(name, mat);
  35994. };
  35995. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35996. this.updateUniform(name, mat.toArray(), 16);
  35997. };
  35998. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35999. this._currentEffect.setVector3(name, vector);
  36000. };
  36001. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36002. vector.toArray(UniformBuffer._tempBuffer);
  36003. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36004. };
  36005. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36006. this._currentEffect.setVector4(name, vector);
  36007. };
  36008. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36009. vector.toArray(UniformBuffer._tempBuffer);
  36010. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36011. };
  36012. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36013. if (suffix === void 0) { suffix = ""; }
  36014. this._currentEffect.setColor3(name + suffix, color);
  36015. };
  36016. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36017. if (suffix === void 0) { suffix = ""; }
  36018. color.toArray(UniformBuffer._tempBuffer);
  36019. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36020. };
  36021. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36022. if (suffix === void 0) { suffix = ""; }
  36023. this._currentEffect.setColor4(name + suffix, color, alpha);
  36024. };
  36025. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36026. if (suffix === void 0) { suffix = ""; }
  36027. color.toArray(UniformBuffer._tempBuffer);
  36028. UniformBuffer._tempBuffer[3] = alpha;
  36029. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36030. };
  36031. /**
  36032. * Sets a sampler uniform on the effect.
  36033. * @param {string} name Name of the sampler.
  36034. * @param {Texture} texture
  36035. */
  36036. UniformBuffer.prototype.setTexture = function (name, texture) {
  36037. this._currentEffect.setTexture(name, texture);
  36038. };
  36039. /**
  36040. * Directly updates the value of the uniform in the cache AND on the GPU.
  36041. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36042. * @param {number[]|Float32Array} data Flattened data
  36043. */
  36044. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36045. this.updateUniform(uniformName, data, data.length);
  36046. this.update();
  36047. };
  36048. /**
  36049. * Binds this uniform buffer to an effect.
  36050. * @param {Effect} effect
  36051. * @param {string} name Name of the uniform block in the shader.
  36052. */
  36053. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36054. this._currentEffect = effect;
  36055. if (this._noUBO || !this._buffer) {
  36056. return;
  36057. }
  36058. effect.bindUniformBuffer(this._buffer, name);
  36059. };
  36060. /**
  36061. * Disposes the uniform buffer.
  36062. */
  36063. UniformBuffer.prototype.dispose = function () {
  36064. if (this._noUBO) {
  36065. return;
  36066. }
  36067. var index = this._engine._uniformBuffers.indexOf(this);
  36068. if (index !== -1) {
  36069. this._engine._uniformBuffers.splice(index, 1);
  36070. }
  36071. if (!this._buffer) {
  36072. return;
  36073. }
  36074. if (this._engine._releaseBuffer(this._buffer)) {
  36075. this._buffer = null;
  36076. }
  36077. };
  36078. // Pool for avoiding memory leaks
  36079. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36080. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36081. return UniformBuffer;
  36082. }());
  36083. BABYLON.UniformBuffer = UniformBuffer;
  36084. })(BABYLON || (BABYLON = {}));
  36085. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36086. var BABYLON;
  36087. (function (BABYLON) {
  36088. /**
  36089. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36090. */
  36091. var VertexData = /** @class */ (function () {
  36092. function VertexData() {
  36093. }
  36094. /**
  36095. * Uses the passed data array to set the set the values for the specified kind of data
  36096. * @param data a linear array of floating numbers
  36097. * @param kind the type of data that is being set, eg positions, colors etc
  36098. */
  36099. VertexData.prototype.set = function (data, kind) {
  36100. switch (kind) {
  36101. case BABYLON.VertexBuffer.PositionKind:
  36102. this.positions = data;
  36103. break;
  36104. case BABYLON.VertexBuffer.NormalKind:
  36105. this.normals = data;
  36106. break;
  36107. case BABYLON.VertexBuffer.TangentKind:
  36108. this.tangents = data;
  36109. break;
  36110. case BABYLON.VertexBuffer.UVKind:
  36111. this.uvs = data;
  36112. break;
  36113. case BABYLON.VertexBuffer.UV2Kind:
  36114. this.uvs2 = data;
  36115. break;
  36116. case BABYLON.VertexBuffer.UV3Kind:
  36117. this.uvs3 = data;
  36118. break;
  36119. case BABYLON.VertexBuffer.UV4Kind:
  36120. this.uvs4 = data;
  36121. break;
  36122. case BABYLON.VertexBuffer.UV5Kind:
  36123. this.uvs5 = data;
  36124. break;
  36125. case BABYLON.VertexBuffer.UV6Kind:
  36126. this.uvs6 = data;
  36127. break;
  36128. case BABYLON.VertexBuffer.ColorKind:
  36129. this.colors = data;
  36130. break;
  36131. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36132. this.matricesIndices = data;
  36133. break;
  36134. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36135. this.matricesWeights = data;
  36136. break;
  36137. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36138. this.matricesIndicesExtra = data;
  36139. break;
  36140. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36141. this.matricesWeightsExtra = data;
  36142. break;
  36143. }
  36144. };
  36145. /**
  36146. * Associates the vertexData to the passed Mesh.
  36147. * Sets it as updatable or not (default `false`)
  36148. * @param mesh the mesh the vertexData is applied to
  36149. * @param updatable when used and having the value true allows new data to update the vertexData
  36150. * @returns the VertexData
  36151. */
  36152. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36153. this._applyTo(mesh, updatable);
  36154. return this;
  36155. };
  36156. /**
  36157. * Associates the vertexData to the passed Geometry.
  36158. * Sets it as updatable or not (default `false`)
  36159. * @param geometry the geometry the vertexData is applied to
  36160. * @param updatable when used and having the value true allows new data to update the vertexData
  36161. * @returns VertexData
  36162. */
  36163. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36164. this._applyTo(geometry, updatable);
  36165. return this;
  36166. };
  36167. /**
  36168. * Updates the associated mesh
  36169. * @param mesh the mesh to be updated
  36170. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36171. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36172. * @returns VertexData
  36173. */
  36174. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36175. this._update(mesh);
  36176. return this;
  36177. };
  36178. /**
  36179. * Updates the associated geometry
  36180. * @param geometry the geometry to be updated
  36181. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36182. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36183. * @returns VertexData.
  36184. */
  36185. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36186. this._update(geometry);
  36187. return this;
  36188. };
  36189. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36190. if (updatable === void 0) { updatable = false; }
  36191. if (this.positions) {
  36192. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36193. }
  36194. if (this.normals) {
  36195. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36196. }
  36197. if (this.tangents) {
  36198. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36199. }
  36200. if (this.uvs) {
  36201. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36202. }
  36203. if (this.uvs2) {
  36204. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36205. }
  36206. if (this.uvs3) {
  36207. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36208. }
  36209. if (this.uvs4) {
  36210. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36211. }
  36212. if (this.uvs5) {
  36213. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36214. }
  36215. if (this.uvs6) {
  36216. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36217. }
  36218. if (this.colors) {
  36219. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36220. }
  36221. if (this.matricesIndices) {
  36222. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36223. }
  36224. if (this.matricesWeights) {
  36225. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36226. }
  36227. if (this.matricesIndicesExtra) {
  36228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36229. }
  36230. if (this.matricesWeightsExtra) {
  36231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36232. }
  36233. if (this.indices) {
  36234. meshOrGeometry.setIndices(this.indices, null, updatable);
  36235. }
  36236. else {
  36237. meshOrGeometry.setIndices([], null);
  36238. }
  36239. return this;
  36240. };
  36241. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36242. if (this.positions) {
  36243. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36244. }
  36245. if (this.normals) {
  36246. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36247. }
  36248. if (this.tangents) {
  36249. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36250. }
  36251. if (this.uvs) {
  36252. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36253. }
  36254. if (this.uvs2) {
  36255. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36256. }
  36257. if (this.uvs3) {
  36258. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36259. }
  36260. if (this.uvs4) {
  36261. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36262. }
  36263. if (this.uvs5) {
  36264. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36265. }
  36266. if (this.uvs6) {
  36267. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36268. }
  36269. if (this.colors) {
  36270. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36271. }
  36272. if (this.matricesIndices) {
  36273. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36274. }
  36275. if (this.matricesWeights) {
  36276. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36277. }
  36278. if (this.matricesIndicesExtra) {
  36279. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36280. }
  36281. if (this.matricesWeightsExtra) {
  36282. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36283. }
  36284. if (this.indices) {
  36285. meshOrGeometry.setIndices(this.indices, null);
  36286. }
  36287. return this;
  36288. };
  36289. /**
  36290. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36291. * @param matrix the transforming matrix
  36292. * @returns the VertexData
  36293. */
  36294. VertexData.prototype.transform = function (matrix) {
  36295. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36296. var transformed = BABYLON.Vector3.Zero();
  36297. var index;
  36298. if (this.positions) {
  36299. var position = BABYLON.Vector3.Zero();
  36300. for (index = 0; index < this.positions.length; index += 3) {
  36301. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36302. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36303. this.positions[index] = transformed.x;
  36304. this.positions[index + 1] = transformed.y;
  36305. this.positions[index + 2] = transformed.z;
  36306. }
  36307. }
  36308. if (this.normals) {
  36309. var normal = BABYLON.Vector3.Zero();
  36310. for (index = 0; index < this.normals.length; index += 3) {
  36311. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36312. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36313. this.normals[index] = transformed.x;
  36314. this.normals[index + 1] = transformed.y;
  36315. this.normals[index + 2] = transformed.z;
  36316. }
  36317. }
  36318. if (this.tangents) {
  36319. var tangent = BABYLON.Vector4.Zero();
  36320. var tangentTransformed = BABYLON.Vector4.Zero();
  36321. for (index = 0; index < this.tangents.length; index += 4) {
  36322. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36323. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36324. this.tangents[index] = tangentTransformed.x;
  36325. this.tangents[index + 1] = tangentTransformed.y;
  36326. this.tangents[index + 2] = tangentTransformed.z;
  36327. this.tangents[index + 3] = tangentTransformed.w;
  36328. }
  36329. }
  36330. if (flip && this.indices) {
  36331. for (index = 0; index < this.indices.length; index += 3) {
  36332. var tmp = this.indices[index + 1];
  36333. this.indices[index + 1] = this.indices[index + 2];
  36334. this.indices[index + 2] = tmp;
  36335. }
  36336. }
  36337. return this;
  36338. };
  36339. /**
  36340. * Merges the passed VertexData into the current one
  36341. * @param other the VertexData to be merged into the current one
  36342. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36343. * @returns the modified VertexData
  36344. */
  36345. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36346. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36347. this._validate();
  36348. other._validate();
  36349. if (!this.normals !== !other.normals ||
  36350. !this.tangents !== !other.tangents ||
  36351. !this.uvs !== !other.uvs ||
  36352. !this.uvs2 !== !other.uvs2 ||
  36353. !this.uvs3 !== !other.uvs3 ||
  36354. !this.uvs4 !== !other.uvs4 ||
  36355. !this.uvs5 !== !other.uvs5 ||
  36356. !this.uvs6 !== !other.uvs6 ||
  36357. !this.colors !== !other.colors ||
  36358. !this.matricesIndices !== !other.matricesIndices ||
  36359. !this.matricesWeights !== !other.matricesWeights ||
  36360. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36361. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36362. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36363. }
  36364. if (other.indices) {
  36365. if (!this.indices) {
  36366. this.indices = [];
  36367. }
  36368. var offset = this.positions ? this.positions.length / 3 : 0;
  36369. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36370. if (isSrcTypedArray) {
  36371. var len = this.indices.length + other.indices.length;
  36372. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36373. temp.set(this.indices);
  36374. var decal = this.indices.length;
  36375. for (var index = 0; index < other.indices.length; index++) {
  36376. temp[decal + index] = other.indices[index] + offset;
  36377. }
  36378. this.indices = temp;
  36379. }
  36380. else {
  36381. for (var index = 0; index < other.indices.length; index++) {
  36382. this.indices.push(other.indices[index] + offset);
  36383. }
  36384. }
  36385. }
  36386. this.positions = this._mergeElement(this.positions, other.positions);
  36387. this.normals = this._mergeElement(this.normals, other.normals);
  36388. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36389. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36390. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36391. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36392. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36393. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36394. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36395. this.colors = this._mergeElement(this.colors, other.colors);
  36396. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36397. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36398. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36399. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36400. return this;
  36401. };
  36402. VertexData.prototype._mergeElement = function (source, other) {
  36403. if (!source) {
  36404. return other;
  36405. }
  36406. if (!other) {
  36407. return source;
  36408. }
  36409. var len = other.length + source.length;
  36410. var isSrcTypedArray = source instanceof Float32Array;
  36411. var isOthTypedArray = other instanceof Float32Array;
  36412. // use non-loop method when the source is Float32Array
  36413. if (isSrcTypedArray) {
  36414. var ret32 = new Float32Array(len);
  36415. ret32.set(source);
  36416. ret32.set(other, source.length);
  36417. return ret32;
  36418. // source is number[], when other is also use concat
  36419. }
  36420. else if (!isOthTypedArray) {
  36421. return source.concat(other);
  36422. // source is a number[], but other is a Float32Array, loop required
  36423. }
  36424. else {
  36425. var ret = source.slice(0); // copy source to a separate array
  36426. for (var i = 0, len = other.length; i < len; i++) {
  36427. ret.push(other[i]);
  36428. }
  36429. return ret;
  36430. }
  36431. };
  36432. VertexData.prototype._validate = function () {
  36433. if (!this.positions) {
  36434. throw new Error("Positions are required");
  36435. }
  36436. var getElementCount = function (kind, values) {
  36437. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36438. if ((values.length % stride) !== 0) {
  36439. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36440. }
  36441. return values.length / stride;
  36442. };
  36443. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36444. var validateElementCount = function (kind, values) {
  36445. var elementCount = getElementCount(kind, values);
  36446. if (elementCount !== positionsElementCount) {
  36447. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36448. }
  36449. };
  36450. if (this.normals)
  36451. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36452. if (this.tangents)
  36453. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36454. if (this.uvs)
  36455. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36456. if (this.uvs2)
  36457. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36458. if (this.uvs3)
  36459. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36460. if (this.uvs4)
  36461. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36462. if (this.uvs5)
  36463. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36464. if (this.uvs6)
  36465. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36466. if (this.colors)
  36467. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36468. if (this.matricesIndices)
  36469. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36470. if (this.matricesWeights)
  36471. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36472. if (this.matricesIndicesExtra)
  36473. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36474. if (this.matricesWeightsExtra)
  36475. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36476. };
  36477. /**
  36478. * Serializes the VertexData
  36479. * @returns a serialized object
  36480. */
  36481. VertexData.prototype.serialize = function () {
  36482. var serializationObject = this.serialize();
  36483. if (this.positions) {
  36484. serializationObject.positions = this.positions;
  36485. }
  36486. if (this.normals) {
  36487. serializationObject.normals = this.normals;
  36488. }
  36489. if (this.tangents) {
  36490. serializationObject.tangents = this.tangents;
  36491. }
  36492. if (this.uvs) {
  36493. serializationObject.uvs = this.uvs;
  36494. }
  36495. if (this.uvs2) {
  36496. serializationObject.uvs2 = this.uvs2;
  36497. }
  36498. if (this.uvs3) {
  36499. serializationObject.uvs3 = this.uvs3;
  36500. }
  36501. if (this.uvs4) {
  36502. serializationObject.uvs4 = this.uvs4;
  36503. }
  36504. if (this.uvs5) {
  36505. serializationObject.uvs5 = this.uvs5;
  36506. }
  36507. if (this.uvs6) {
  36508. serializationObject.uvs6 = this.uvs6;
  36509. }
  36510. if (this.colors) {
  36511. serializationObject.colors = this.colors;
  36512. }
  36513. if (this.matricesIndices) {
  36514. serializationObject.matricesIndices = this.matricesIndices;
  36515. serializationObject.matricesIndices._isExpanded = true;
  36516. }
  36517. if (this.matricesWeights) {
  36518. serializationObject.matricesWeights = this.matricesWeights;
  36519. }
  36520. if (this.matricesIndicesExtra) {
  36521. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36522. serializationObject.matricesIndicesExtra._isExpanded = true;
  36523. }
  36524. if (this.matricesWeightsExtra) {
  36525. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36526. }
  36527. serializationObject.indices = this.indices;
  36528. return serializationObject;
  36529. };
  36530. // Statics
  36531. /**
  36532. * Extracts the vertexData from a mesh
  36533. * @param mesh the mesh from which to extract the VertexData
  36534. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36535. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36536. * @returns the object VertexData associated to the passed mesh
  36537. */
  36538. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36539. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36540. };
  36541. /**
  36542. * Extracts the vertexData from the geometry
  36543. * @param geometry the geometry from which to extract the VertexData
  36544. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36545. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36546. * @returns the object VertexData associated to the passed mesh
  36547. */
  36548. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36549. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36550. };
  36551. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36552. var result = new VertexData();
  36553. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36554. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36555. }
  36556. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36557. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36558. }
  36559. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36560. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36561. }
  36562. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36563. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36564. }
  36565. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36566. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36567. }
  36568. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36569. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36570. }
  36571. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36572. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36573. }
  36574. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36575. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36576. }
  36577. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36578. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36579. }
  36580. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36581. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36582. }
  36583. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36584. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36585. }
  36586. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36587. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36588. }
  36589. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36590. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36591. }
  36592. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36593. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36594. }
  36595. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36596. return result;
  36597. };
  36598. /**
  36599. * Creates the VertexData for a Ribbon
  36600. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36601. * * pathArray array of paths, each of which an array of successive Vector3
  36602. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36603. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36604. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36605. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36606. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36607. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36608. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36609. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36610. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36611. * @returns the VertexData of the ribbon
  36612. */
  36613. VertexData.CreateRibbon = function (options) {
  36614. var pathArray = options.pathArray;
  36615. var closeArray = options.closeArray || false;
  36616. var closePath = options.closePath || false;
  36617. var invertUV = options.invertUV || false;
  36618. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36619. var offset = options.offset || defaultOffset;
  36620. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36621. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36622. var customUV = options.uvs;
  36623. var customColors = options.colors;
  36624. var positions = [];
  36625. var indices = [];
  36626. var normals = [];
  36627. var uvs = [];
  36628. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36629. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36630. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36631. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36632. var minlg; // minimal length among all paths from pathArray
  36633. var lg = []; // array of path lengths : nb of vertex per path
  36634. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36635. var p; // path iterator
  36636. var i; // point iterator
  36637. var j; // point iterator
  36638. // if single path in pathArray
  36639. if (pathArray.length < 2) {
  36640. var ar1 = [];
  36641. var ar2 = [];
  36642. for (i = 0; i < pathArray[0].length - offset; i++) {
  36643. ar1.push(pathArray[0][i]);
  36644. ar2.push(pathArray[0][i + offset]);
  36645. }
  36646. pathArray = [ar1, ar2];
  36647. }
  36648. // positions and horizontal distances (u)
  36649. var idc = 0;
  36650. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36651. var path;
  36652. var l;
  36653. minlg = pathArray[0].length;
  36654. var vectlg;
  36655. var dist;
  36656. for (p = 0; p < pathArray.length; p++) {
  36657. uTotalDistance[p] = 0;
  36658. us[p] = [0];
  36659. path = pathArray[p];
  36660. l = path.length;
  36661. minlg = (minlg < l) ? minlg : l;
  36662. j = 0;
  36663. while (j < l) {
  36664. positions.push(path[j].x, path[j].y, path[j].z);
  36665. if (j > 0) {
  36666. vectlg = path[j].subtract(path[j - 1]).length();
  36667. dist = vectlg + uTotalDistance[p];
  36668. us[p].push(dist);
  36669. uTotalDistance[p] = dist;
  36670. }
  36671. j++;
  36672. }
  36673. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36674. j--;
  36675. positions.push(path[0].x, path[0].y, path[0].z);
  36676. vectlg = path[j].subtract(path[0]).length();
  36677. dist = vectlg + uTotalDistance[p];
  36678. us[p].push(dist);
  36679. uTotalDistance[p] = dist;
  36680. }
  36681. lg[p] = l + closePathCorr;
  36682. idx[p] = idc;
  36683. idc += (l + closePathCorr);
  36684. }
  36685. // vertical distances (v)
  36686. var path1;
  36687. var path2;
  36688. var vertex1 = null;
  36689. var vertex2 = null;
  36690. for (i = 0; i < minlg + closePathCorr; i++) {
  36691. vTotalDistance[i] = 0;
  36692. vs[i] = [0];
  36693. for (p = 0; p < pathArray.length - 1; p++) {
  36694. path1 = pathArray[p];
  36695. path2 = pathArray[p + 1];
  36696. if (i === minlg) { // closePath
  36697. vertex1 = path1[0];
  36698. vertex2 = path2[0];
  36699. }
  36700. else {
  36701. vertex1 = path1[i];
  36702. vertex2 = path2[i];
  36703. }
  36704. vectlg = vertex2.subtract(vertex1).length();
  36705. dist = vectlg + vTotalDistance[i];
  36706. vs[i].push(dist);
  36707. vTotalDistance[i] = dist;
  36708. }
  36709. if (closeArray && vertex2 && vertex1) {
  36710. path1 = pathArray[p];
  36711. path2 = pathArray[0];
  36712. if (i === minlg) { // closePath
  36713. vertex2 = path2[0];
  36714. }
  36715. vectlg = vertex2.subtract(vertex1).length();
  36716. dist = vectlg + vTotalDistance[i];
  36717. vTotalDistance[i] = dist;
  36718. }
  36719. }
  36720. // uvs
  36721. var u;
  36722. var v;
  36723. if (customUV) {
  36724. for (p = 0; p < customUV.length; p++) {
  36725. uvs.push(customUV[p].x, customUV[p].y);
  36726. }
  36727. }
  36728. else {
  36729. for (p = 0; p < pathArray.length; p++) {
  36730. for (i = 0; i < minlg + closePathCorr; i++) {
  36731. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36732. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36733. if (invertUV) {
  36734. uvs.push(v, u);
  36735. }
  36736. else {
  36737. uvs.push(u, v);
  36738. }
  36739. }
  36740. }
  36741. }
  36742. // indices
  36743. p = 0; // path index
  36744. var pi = 0; // positions array index
  36745. var l1 = lg[p] - 1; // path1 length
  36746. var l2 = lg[p + 1] - 1; // path2 length
  36747. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36748. var shft = idx[1] - idx[0]; // shift
  36749. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36750. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36751. // 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
  36752. indices.push(pi, pi + shft, pi + 1);
  36753. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36754. pi += 1;
  36755. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36756. p++;
  36757. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36758. shft = idx[0] - idx[p];
  36759. l1 = lg[p] - 1;
  36760. l2 = lg[0] - 1;
  36761. }
  36762. else {
  36763. shft = idx[p + 1] - idx[p];
  36764. l1 = lg[p] - 1;
  36765. l2 = lg[p + 1] - 1;
  36766. }
  36767. pi = idx[p];
  36768. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36769. }
  36770. }
  36771. // normals
  36772. VertexData.ComputeNormals(positions, indices, normals);
  36773. if (closePath) { // update both the first and last vertex normals to their average value
  36774. var indexFirst = 0;
  36775. var indexLast = 0;
  36776. for (p = 0; p < pathArray.length; p++) {
  36777. indexFirst = idx[p] * 3;
  36778. if (p + 1 < pathArray.length) {
  36779. indexLast = (idx[p + 1] - 1) * 3;
  36780. }
  36781. else {
  36782. indexLast = normals.length - 3;
  36783. }
  36784. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36785. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36786. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36787. normals[indexLast] = normals[indexFirst];
  36788. normals[indexLast + 1] = normals[indexFirst + 1];
  36789. normals[indexLast + 2] = normals[indexFirst + 2];
  36790. }
  36791. }
  36792. // sides
  36793. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36794. // Colors
  36795. var colors = null;
  36796. if (customColors) {
  36797. colors = new Float32Array(customColors.length * 4);
  36798. for (var c = 0; c < customColors.length; c++) {
  36799. colors[c * 4] = customColors[c].r;
  36800. colors[c * 4 + 1] = customColors[c].g;
  36801. colors[c * 4 + 2] = customColors[c].b;
  36802. colors[c * 4 + 3] = customColors[c].a;
  36803. }
  36804. }
  36805. // Result
  36806. var vertexData = new VertexData();
  36807. var positions32 = new Float32Array(positions);
  36808. var normals32 = new Float32Array(normals);
  36809. var uvs32 = new Float32Array(uvs);
  36810. vertexData.indices = indices;
  36811. vertexData.positions = positions32;
  36812. vertexData.normals = normals32;
  36813. vertexData.uvs = uvs32;
  36814. if (colors) {
  36815. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36816. }
  36817. if (closePath) {
  36818. vertexData._idx = idx;
  36819. }
  36820. return vertexData;
  36821. };
  36822. /**
  36823. * Creates the VertexData for a box
  36824. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36825. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36826. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36827. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36828. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36829. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36830. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36831. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36832. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36833. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36834. * @returns the VertexData of the box
  36835. */
  36836. VertexData.CreateBox = function (options) {
  36837. var normalsSource = [
  36838. new BABYLON.Vector3(0, 0, 1),
  36839. new BABYLON.Vector3(0, 0, -1),
  36840. new BABYLON.Vector3(1, 0, 0),
  36841. new BABYLON.Vector3(-1, 0, 0),
  36842. new BABYLON.Vector3(0, 1, 0),
  36843. new BABYLON.Vector3(0, -1, 0)
  36844. ];
  36845. var indices = [];
  36846. var positions = [];
  36847. var normals = [];
  36848. var uvs = [];
  36849. var width = options.width || options.size || 1;
  36850. var height = options.height || options.size || 1;
  36851. var depth = options.depth || options.size || 1;
  36852. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36853. var faceUV = options.faceUV || new Array(6);
  36854. var faceColors = options.faceColors;
  36855. var colors = [];
  36856. // default face colors and UV if undefined
  36857. for (var f = 0; f < 6; f++) {
  36858. if (faceUV[f] === undefined) {
  36859. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36860. }
  36861. if (faceColors && faceColors[f] === undefined) {
  36862. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36863. }
  36864. }
  36865. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36866. // Create each face in turn.
  36867. for (var index = 0; index < normalsSource.length; index++) {
  36868. var normal = normalsSource[index];
  36869. // Get two vectors perpendicular to the face normal and to each other.
  36870. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36871. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36872. // Six indices (two triangles) per face.
  36873. var verticesLength = positions.length / 3;
  36874. indices.push(verticesLength);
  36875. indices.push(verticesLength + 1);
  36876. indices.push(verticesLength + 2);
  36877. indices.push(verticesLength);
  36878. indices.push(verticesLength + 2);
  36879. indices.push(verticesLength + 3);
  36880. // Four vertices per face.
  36881. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36882. positions.push(vertex.x, vertex.y, vertex.z);
  36883. normals.push(normal.x, normal.y, normal.z);
  36884. uvs.push(faceUV[index].z, faceUV[index].w);
  36885. if (faceColors) {
  36886. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36887. }
  36888. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36889. positions.push(vertex.x, vertex.y, vertex.z);
  36890. normals.push(normal.x, normal.y, normal.z);
  36891. uvs.push(faceUV[index].x, faceUV[index].w);
  36892. if (faceColors) {
  36893. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36894. }
  36895. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36896. positions.push(vertex.x, vertex.y, vertex.z);
  36897. normals.push(normal.x, normal.y, normal.z);
  36898. uvs.push(faceUV[index].x, faceUV[index].y);
  36899. if (faceColors) {
  36900. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36901. }
  36902. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36903. positions.push(vertex.x, vertex.y, vertex.z);
  36904. normals.push(normal.x, normal.y, normal.z);
  36905. uvs.push(faceUV[index].z, faceUV[index].y);
  36906. if (faceColors) {
  36907. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36908. }
  36909. }
  36910. // sides
  36911. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36912. // Result
  36913. var vertexData = new VertexData();
  36914. vertexData.indices = indices;
  36915. vertexData.positions = positions;
  36916. vertexData.normals = normals;
  36917. vertexData.uvs = uvs;
  36918. if (faceColors) {
  36919. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36920. vertexData.colors = totalColors;
  36921. }
  36922. return vertexData;
  36923. };
  36924. /**
  36925. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36926. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36927. * * segments sets the number of horizontal strips optional, default 32
  36928. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36929. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36930. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36931. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36932. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36933. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36934. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36935. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36936. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36937. * @returns the VertexData of the ellipsoid
  36938. */
  36939. VertexData.CreateSphere = function (options) {
  36940. var segments = options.segments || 32;
  36941. var diameterX = options.diameterX || options.diameter || 1;
  36942. var diameterY = options.diameterY || options.diameter || 1;
  36943. var diameterZ = options.diameterZ || options.diameter || 1;
  36944. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36945. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36946. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36947. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36948. var totalZRotationSteps = 2 + segments;
  36949. var totalYRotationSteps = 2 * totalZRotationSteps;
  36950. var indices = [];
  36951. var positions = [];
  36952. var normals = [];
  36953. var uvs = [];
  36954. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36955. var normalizedZ = zRotationStep / totalZRotationSteps;
  36956. var angleZ = normalizedZ * Math.PI * slice;
  36957. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36958. var normalizedY = yRotationStep / totalYRotationSteps;
  36959. var angleY = normalizedY * Math.PI * 2 * arc;
  36960. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36961. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36962. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36963. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36964. var vertex = complete.multiply(radius);
  36965. var normal = complete.divide(radius).normalize();
  36966. positions.push(vertex.x, vertex.y, vertex.z);
  36967. normals.push(normal.x, normal.y, normal.z);
  36968. uvs.push(normalizedY, normalizedZ);
  36969. }
  36970. if (zRotationStep > 0) {
  36971. var verticesCount = positions.length / 3;
  36972. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36973. indices.push((firstIndex));
  36974. indices.push((firstIndex + 1));
  36975. indices.push(firstIndex + totalYRotationSteps + 1);
  36976. indices.push((firstIndex + totalYRotationSteps + 1));
  36977. indices.push((firstIndex + 1));
  36978. indices.push((firstIndex + totalYRotationSteps + 2));
  36979. }
  36980. }
  36981. }
  36982. // Sides
  36983. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36984. // Result
  36985. var vertexData = new VertexData();
  36986. vertexData.indices = indices;
  36987. vertexData.positions = positions;
  36988. vertexData.normals = normals;
  36989. vertexData.uvs = uvs;
  36990. return vertexData;
  36991. };
  36992. /**
  36993. * Creates the VertexData for a cylinder, cone or prism
  36994. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36995. * * height sets the height (y direction) of the cylinder, optional, default 2
  36996. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36997. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36998. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36999. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37000. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37001. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37002. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37003. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37004. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37005. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37006. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37007. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37008. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37009. * @returns the VertexData of the cylinder, cone or prism
  37010. */
  37011. VertexData.CreateCylinder = function (options) {
  37012. var height = options.height || 2;
  37013. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37014. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37015. var tessellation = options.tessellation || 24;
  37016. var subdivisions = options.subdivisions || 1;
  37017. var hasRings = options.hasRings ? true : false;
  37018. var enclose = options.enclose ? true : false;
  37019. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37020. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37021. var faceUV = options.faceUV || new Array(3);
  37022. var faceColors = options.faceColors;
  37023. // default face colors and UV if undefined
  37024. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37025. var ringNb = (hasRings) ? subdivisions : 1;
  37026. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37027. var f;
  37028. for (f = 0; f < surfaceNb; f++) {
  37029. if (faceColors && faceColors[f] === undefined) {
  37030. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37031. }
  37032. }
  37033. for (f = 0; f < surfaceNb; f++) {
  37034. if (faceUV && faceUV[f] === undefined) {
  37035. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37036. }
  37037. }
  37038. var indices = new Array();
  37039. var positions = new Array();
  37040. var normals = new Array();
  37041. var uvs = new Array();
  37042. var colors = new Array();
  37043. var angle_step = Math.PI * 2 * arc / tessellation;
  37044. var angle;
  37045. var h;
  37046. var radius;
  37047. var tan = (diameterBottom - diameterTop) / 2 / height;
  37048. var ringVertex = BABYLON.Vector3.Zero();
  37049. var ringNormal = BABYLON.Vector3.Zero();
  37050. var ringFirstVertex = BABYLON.Vector3.Zero();
  37051. var ringFirstNormal = BABYLON.Vector3.Zero();
  37052. var quadNormal = BABYLON.Vector3.Zero();
  37053. var Y = BABYLON.Axis.Y;
  37054. // positions, normals, uvs
  37055. var i;
  37056. var j;
  37057. var r;
  37058. var ringIdx = 1;
  37059. var s = 1; // surface index
  37060. var cs = 0;
  37061. var v = 0;
  37062. for (i = 0; i <= subdivisions; i++) {
  37063. h = i / subdivisions;
  37064. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37065. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37066. for (r = 0; r < ringIdx; r++) {
  37067. if (hasRings) {
  37068. s += r;
  37069. }
  37070. if (enclose) {
  37071. s += 2 * r;
  37072. }
  37073. for (j = 0; j <= tessellation; j++) {
  37074. angle = j * angle_step;
  37075. // position
  37076. ringVertex.x = Math.cos(-angle) * radius;
  37077. ringVertex.y = -height / 2 + h * height;
  37078. ringVertex.z = Math.sin(-angle) * radius;
  37079. // normal
  37080. if (diameterTop === 0 && i === subdivisions) {
  37081. // if no top cap, reuse former normals
  37082. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37083. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37084. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37085. }
  37086. else {
  37087. ringNormal.x = ringVertex.x;
  37088. ringNormal.z = ringVertex.z;
  37089. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37090. ringNormal.normalize();
  37091. }
  37092. // keep first ring vertex values for enclose
  37093. if (j === 0) {
  37094. ringFirstVertex.copyFrom(ringVertex);
  37095. ringFirstNormal.copyFrom(ringNormal);
  37096. }
  37097. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37098. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37099. if (hasRings) {
  37100. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37101. }
  37102. else {
  37103. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37104. }
  37105. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37106. if (faceColors) {
  37107. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37108. }
  37109. }
  37110. // if enclose, add four vertices and their dedicated normals
  37111. if (arc !== 1 && enclose) {
  37112. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37113. positions.push(0, ringVertex.y, 0);
  37114. positions.push(0, ringVertex.y, 0);
  37115. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37116. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37117. quadNormal.normalize();
  37118. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37119. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37120. quadNormal.normalize();
  37121. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37122. if (hasRings) {
  37123. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37124. }
  37125. else {
  37126. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37127. }
  37128. uvs.push(faceUV[s + 1].x, v);
  37129. uvs.push(faceUV[s + 1].z, v);
  37130. if (hasRings) {
  37131. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37132. }
  37133. else {
  37134. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37135. }
  37136. uvs.push(faceUV[s + 2].x, v);
  37137. uvs.push(faceUV[s + 2].z, v);
  37138. if (faceColors) {
  37139. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37140. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37141. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37142. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37143. }
  37144. }
  37145. if (cs !== s) {
  37146. cs = s;
  37147. }
  37148. }
  37149. }
  37150. // indices
  37151. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37152. var s;
  37153. i = 0;
  37154. for (s = 0; s < subdivisions; s++) {
  37155. var i0 = 0;
  37156. var i1 = 0;
  37157. var i2 = 0;
  37158. var i3 = 0;
  37159. for (j = 0; j < tessellation; j++) {
  37160. i0 = i * (e + 1) + j;
  37161. i1 = (i + 1) * (e + 1) + j;
  37162. i2 = i * (e + 1) + (j + 1);
  37163. i3 = (i + 1) * (e + 1) + (j + 1);
  37164. indices.push(i0, i1, i2);
  37165. indices.push(i3, i2, i1);
  37166. }
  37167. if (arc !== 1 && enclose) { // if enclose, add two quads
  37168. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37169. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37170. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37171. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37172. }
  37173. i = (hasRings) ? (i + 2) : (i + 1);
  37174. }
  37175. // Caps
  37176. var createCylinderCap = function (isTop) {
  37177. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37178. if (radius === 0) {
  37179. return;
  37180. }
  37181. // Cap positions, normals & uvs
  37182. var angle;
  37183. var circleVector;
  37184. var i;
  37185. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37186. var c = null;
  37187. if (faceColors) {
  37188. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37189. }
  37190. // cap center
  37191. var vbase = positions.length / 3;
  37192. var offset = isTop ? height / 2 : -height / 2;
  37193. var center = new BABYLON.Vector3(0, offset, 0);
  37194. positions.push(center.x, center.y, center.z);
  37195. normals.push(0, isTop ? 1 : -1, 0);
  37196. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37197. if (c) {
  37198. colors.push(c.r, c.g, c.b, c.a);
  37199. }
  37200. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37201. for (i = 0; i <= tessellation; i++) {
  37202. angle = Math.PI * 2 * i * arc / tessellation;
  37203. var cos = Math.cos(-angle);
  37204. var sin = Math.sin(-angle);
  37205. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37206. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37207. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37208. normals.push(0, isTop ? 1 : -1, 0);
  37209. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37210. if (c) {
  37211. colors.push(c.r, c.g, c.b, c.a);
  37212. }
  37213. }
  37214. // Cap indices
  37215. for (i = 0; i < tessellation; i++) {
  37216. if (!isTop) {
  37217. indices.push(vbase);
  37218. indices.push(vbase + (i + 1));
  37219. indices.push(vbase + (i + 2));
  37220. }
  37221. else {
  37222. indices.push(vbase);
  37223. indices.push(vbase + (i + 2));
  37224. indices.push(vbase + (i + 1));
  37225. }
  37226. }
  37227. };
  37228. // add caps to geometry
  37229. createCylinderCap(false);
  37230. createCylinderCap(true);
  37231. // Sides
  37232. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37233. var vertexData = new VertexData();
  37234. vertexData.indices = indices;
  37235. vertexData.positions = positions;
  37236. vertexData.normals = normals;
  37237. vertexData.uvs = uvs;
  37238. if (faceColors) {
  37239. vertexData.colors = colors;
  37240. }
  37241. return vertexData;
  37242. };
  37243. /**
  37244. * Creates the VertexData for a torus
  37245. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37246. * * diameter the diameter of the torus, optional default 1
  37247. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37248. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37249. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37250. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37251. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37252. * @returns the VertexData of the torus
  37253. */
  37254. VertexData.CreateTorus = function (options) {
  37255. var indices = [];
  37256. var positions = [];
  37257. var normals = [];
  37258. var uvs = [];
  37259. var diameter = options.diameter || 1;
  37260. var thickness = options.thickness || 0.5;
  37261. var tessellation = options.tessellation || 16;
  37262. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37263. var stride = tessellation + 1;
  37264. for (var i = 0; i <= tessellation; i++) {
  37265. var u = i / tessellation;
  37266. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37267. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37268. for (var j = 0; j <= tessellation; j++) {
  37269. var v = 1 - j / tessellation;
  37270. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37271. var dx = Math.cos(innerAngle);
  37272. var dy = Math.sin(innerAngle);
  37273. // Create a vertex.
  37274. var normal = new BABYLON.Vector3(dx, dy, 0);
  37275. var position = normal.scale(thickness / 2);
  37276. var textureCoordinate = new BABYLON.Vector2(u, v);
  37277. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37278. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37279. positions.push(position.x, position.y, position.z);
  37280. normals.push(normal.x, normal.y, normal.z);
  37281. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37282. // And create indices for two triangles.
  37283. var nextI = (i + 1) % stride;
  37284. var nextJ = (j + 1) % stride;
  37285. indices.push(i * stride + j);
  37286. indices.push(i * stride + nextJ);
  37287. indices.push(nextI * stride + j);
  37288. indices.push(i * stride + nextJ);
  37289. indices.push(nextI * stride + nextJ);
  37290. indices.push(nextI * stride + j);
  37291. }
  37292. }
  37293. // Sides
  37294. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37295. // Result
  37296. var vertexData = new VertexData();
  37297. vertexData.indices = indices;
  37298. vertexData.positions = positions;
  37299. vertexData.normals = normals;
  37300. vertexData.uvs = uvs;
  37301. return vertexData;
  37302. };
  37303. /**
  37304. * Creates the VertexData of the LineSystem
  37305. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37306. * - lines an array of lines, each line being an array of successive Vector3
  37307. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37308. * @returns the VertexData of the LineSystem
  37309. */
  37310. VertexData.CreateLineSystem = function (options) {
  37311. var indices = [];
  37312. var positions = [];
  37313. var lines = options.lines;
  37314. var colors = options.colors;
  37315. var vertexColors = [];
  37316. var idx = 0;
  37317. for (var l = 0; l < lines.length; l++) {
  37318. var points = lines[l];
  37319. for (var index = 0; index < points.length; index++) {
  37320. positions.push(points[index].x, points[index].y, points[index].z);
  37321. if (colors) {
  37322. var color = colors[l];
  37323. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37324. }
  37325. if (index > 0) {
  37326. indices.push(idx - 1);
  37327. indices.push(idx);
  37328. }
  37329. idx++;
  37330. }
  37331. }
  37332. var vertexData = new VertexData();
  37333. vertexData.indices = indices;
  37334. vertexData.positions = positions;
  37335. if (colors) {
  37336. vertexData.colors = vertexColors;
  37337. }
  37338. return vertexData;
  37339. };
  37340. /**
  37341. * Create the VertexData for a DashedLines
  37342. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37343. * - points an array successive Vector3
  37344. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37345. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37346. * - dashNb the intended total number of dashes, optional, default 200
  37347. * @returns the VertexData for the DashedLines
  37348. */
  37349. VertexData.CreateDashedLines = function (options) {
  37350. var dashSize = options.dashSize || 3;
  37351. var gapSize = options.gapSize || 1;
  37352. var dashNb = options.dashNb || 200;
  37353. var points = options.points;
  37354. var positions = new Array();
  37355. var indices = new Array();
  37356. var curvect = BABYLON.Vector3.Zero();
  37357. var lg = 0;
  37358. var nb = 0;
  37359. var shft = 0;
  37360. var dashshft = 0;
  37361. var curshft = 0;
  37362. var idx = 0;
  37363. var i = 0;
  37364. for (i = 0; i < points.length - 1; i++) {
  37365. points[i + 1].subtractToRef(points[i], curvect);
  37366. lg += curvect.length();
  37367. }
  37368. shft = lg / dashNb;
  37369. dashshft = dashSize * shft / (dashSize + gapSize);
  37370. for (i = 0; i < points.length - 1; i++) {
  37371. points[i + 1].subtractToRef(points[i], curvect);
  37372. nb = Math.floor(curvect.length() / shft);
  37373. curvect.normalize();
  37374. for (var j = 0; j < nb; j++) {
  37375. curshft = shft * j;
  37376. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37377. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37378. indices.push(idx, idx + 1);
  37379. idx += 2;
  37380. }
  37381. }
  37382. // Result
  37383. var vertexData = new VertexData();
  37384. vertexData.positions = positions;
  37385. vertexData.indices = indices;
  37386. return vertexData;
  37387. };
  37388. /**
  37389. * Creates the VertexData for a Ground
  37390. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37391. * - width the width (x direction) of the ground, optional, default 1
  37392. * - height the height (z direction) of the ground, optional, default 1
  37393. * - subdivisions the number of subdivisions per side, optional, default 1
  37394. * @returns the VertexData of the Ground
  37395. */
  37396. VertexData.CreateGround = function (options) {
  37397. var indices = [];
  37398. var positions = [];
  37399. var normals = [];
  37400. var uvs = [];
  37401. var row, col;
  37402. var width = options.width || 1;
  37403. var height = options.height || 1;
  37404. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37405. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37406. for (row = 0; row <= subdivisionsY; row++) {
  37407. for (col = 0; col <= subdivisionsX; col++) {
  37408. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37409. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37410. positions.push(position.x, position.y, position.z);
  37411. normals.push(normal.x, normal.y, normal.z);
  37412. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37413. }
  37414. }
  37415. for (row = 0; row < subdivisionsY; row++) {
  37416. for (col = 0; col < subdivisionsX; col++) {
  37417. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37418. indices.push(col + 1 + row * (subdivisionsX + 1));
  37419. indices.push(col + row * (subdivisionsX + 1));
  37420. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37421. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37422. indices.push(col + row * (subdivisionsX + 1));
  37423. }
  37424. }
  37425. // Result
  37426. var vertexData = new VertexData();
  37427. vertexData.indices = indices;
  37428. vertexData.positions = positions;
  37429. vertexData.normals = normals;
  37430. vertexData.uvs = uvs;
  37431. return vertexData;
  37432. };
  37433. /**
  37434. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37435. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37436. * * xmin the ground minimum X coordinate, optional, default -1
  37437. * * zmin the ground minimum Z coordinate, optional, default -1
  37438. * * xmax the ground maximum X coordinate, optional, default 1
  37439. * * zmax the ground maximum Z coordinate, optional, default 1
  37440. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37441. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37442. * @returns the VertexData of the TiledGround
  37443. */
  37444. VertexData.CreateTiledGround = function (options) {
  37445. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37446. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37447. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37448. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37449. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37450. var precision = options.precision || { w: 1, h: 1 };
  37451. var indices = new Array();
  37452. var positions = new Array();
  37453. var normals = new Array();
  37454. var uvs = new Array();
  37455. var row, col, tileRow, tileCol;
  37456. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37457. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37458. precision.w = (precision.w < 1) ? 1 : precision.w;
  37459. precision.h = (precision.h < 1) ? 1 : precision.h;
  37460. var tileSize = {
  37461. 'w': (xmax - xmin) / subdivisions.w,
  37462. 'h': (zmax - zmin) / subdivisions.h
  37463. };
  37464. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37465. // Indices
  37466. var base = positions.length / 3;
  37467. var rowLength = precision.w + 1;
  37468. for (row = 0; row < precision.h; row++) {
  37469. for (col = 0; col < precision.w; col++) {
  37470. var square = [
  37471. base + col + row * rowLength,
  37472. base + (col + 1) + row * rowLength,
  37473. base + (col + 1) + (row + 1) * rowLength,
  37474. base + col + (row + 1) * rowLength
  37475. ];
  37476. indices.push(square[1]);
  37477. indices.push(square[2]);
  37478. indices.push(square[3]);
  37479. indices.push(square[0]);
  37480. indices.push(square[1]);
  37481. indices.push(square[3]);
  37482. }
  37483. }
  37484. // Position, normals and uvs
  37485. var position = BABYLON.Vector3.Zero();
  37486. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37487. for (row = 0; row <= precision.h; row++) {
  37488. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37489. for (col = 0; col <= precision.w; col++) {
  37490. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37491. position.y = 0;
  37492. positions.push(position.x, position.y, position.z);
  37493. normals.push(normal.x, normal.y, normal.z);
  37494. uvs.push(col / precision.w, row / precision.h);
  37495. }
  37496. }
  37497. }
  37498. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37499. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37500. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37501. }
  37502. }
  37503. // Result
  37504. var vertexData = new VertexData();
  37505. vertexData.indices = indices;
  37506. vertexData.positions = positions;
  37507. vertexData.normals = normals;
  37508. vertexData.uvs = uvs;
  37509. return vertexData;
  37510. };
  37511. /**
  37512. * Creates the VertexData of the Ground designed from a heightmap
  37513. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37514. * * width the width (x direction) of the ground
  37515. * * height the height (z direction) of the ground
  37516. * * subdivisions the number of subdivisions per side
  37517. * * minHeight the minimum altitude on the ground, optional, default 0
  37518. * * maxHeight the maximum altitude on the ground, optional default 1
  37519. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37520. * * buffer the array holding the image color data
  37521. * * bufferWidth the width of image
  37522. * * bufferHeight the height of image
  37523. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37524. * @returns the VertexData of the Ground designed from a heightmap
  37525. */
  37526. VertexData.CreateGroundFromHeightMap = function (options) {
  37527. var indices = [];
  37528. var positions = [];
  37529. var normals = [];
  37530. var uvs = [];
  37531. var row, col;
  37532. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37533. var alphaFilter = options.alphaFilter || 0.0;
  37534. // Vertices
  37535. for (row = 0; row <= options.subdivisions; row++) {
  37536. for (col = 0; col <= options.subdivisions; col++) {
  37537. 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));
  37538. // Compute height
  37539. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37540. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37541. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37542. var r = options.buffer[pos] / 255.0;
  37543. var g = options.buffer[pos + 1] / 255.0;
  37544. var b = options.buffer[pos + 2] / 255.0;
  37545. var a = options.buffer[pos + 3] / 255.0;
  37546. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37547. // If our alpha channel is not within our filter then we will assign a 'special' height
  37548. // Then when building the indices, we will ignore any vertex that is using the special height
  37549. if (a >= alphaFilter)
  37550. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37551. else {
  37552. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37553. }
  37554. // Add vertex
  37555. positions.push(position.x, position.y, position.z);
  37556. normals.push(0, 0, 0);
  37557. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37558. }
  37559. }
  37560. // Indices
  37561. for (row = 0; row < options.subdivisions; row++) {
  37562. for (col = 0; col < options.subdivisions; col++) {
  37563. // Calculate Indices
  37564. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37565. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37566. var idx3 = (col + row * (options.subdivisions + 1));
  37567. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37568. // Check that all indices are visible (based on our special height)
  37569. // Only display the vertex if all Indices are visible
  37570. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37571. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37572. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37573. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37574. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37575. indices.push(idx1);
  37576. indices.push(idx2);
  37577. indices.push(idx3);
  37578. }
  37579. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37580. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37581. indices.push(idx4);
  37582. indices.push(idx1);
  37583. indices.push(idx3);
  37584. }
  37585. }
  37586. }
  37587. // Normals
  37588. VertexData.ComputeNormals(positions, indices, normals);
  37589. // Result
  37590. var vertexData = new VertexData();
  37591. vertexData.indices = indices;
  37592. vertexData.positions = positions;
  37593. vertexData.normals = normals;
  37594. vertexData.uvs = uvs;
  37595. return vertexData;
  37596. };
  37597. /**
  37598. * Creates the VertexData for a Plane
  37599. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37600. * * size sets the width and height of the plane to the value of size, optional default 1
  37601. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37602. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37603. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37604. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37605. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37606. * @returns the VertexData of the box
  37607. */
  37608. VertexData.CreatePlane = function (options) {
  37609. var indices = [];
  37610. var positions = [];
  37611. var normals = [];
  37612. var uvs = [];
  37613. var width = options.width || options.size || 1;
  37614. var height = options.height || options.size || 1;
  37615. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37616. // Vertices
  37617. var halfWidth = width / 2.0;
  37618. var halfHeight = height / 2.0;
  37619. positions.push(-halfWidth, -halfHeight, 0);
  37620. normals.push(0, 0, -1.0);
  37621. uvs.push(0.0, 0.0);
  37622. positions.push(halfWidth, -halfHeight, 0);
  37623. normals.push(0, 0, -1.0);
  37624. uvs.push(1.0, 0.0);
  37625. positions.push(halfWidth, halfHeight, 0);
  37626. normals.push(0, 0, -1.0);
  37627. uvs.push(1.0, 1.0);
  37628. positions.push(-halfWidth, halfHeight, 0);
  37629. normals.push(0, 0, -1.0);
  37630. uvs.push(0.0, 1.0);
  37631. // Indices
  37632. indices.push(0);
  37633. indices.push(1);
  37634. indices.push(2);
  37635. indices.push(0);
  37636. indices.push(2);
  37637. indices.push(3);
  37638. // Sides
  37639. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37640. // Result
  37641. var vertexData = new VertexData();
  37642. vertexData.indices = indices;
  37643. vertexData.positions = positions;
  37644. vertexData.normals = normals;
  37645. vertexData.uvs = uvs;
  37646. return vertexData;
  37647. };
  37648. /**
  37649. * Creates the VertexData of the Disc or regular Polygon
  37650. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37651. * * radius the radius of the disc, optional default 0.5
  37652. * * tessellation the number of polygon sides, optional, default 64
  37653. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37654. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37655. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37656. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37657. * @returns the VertexData of the box
  37658. */
  37659. VertexData.CreateDisc = function (options) {
  37660. var positions = new Array();
  37661. var indices = new Array();
  37662. var normals = new Array();
  37663. var uvs = new Array();
  37664. var radius = options.radius || 0.5;
  37665. var tessellation = options.tessellation || 64;
  37666. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37667. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37668. // positions and uvs
  37669. positions.push(0, 0, 0); // disc center first
  37670. uvs.push(0.5, 0.5);
  37671. var theta = Math.PI * 2 * arc;
  37672. var step = theta / tessellation;
  37673. for (var a = 0; a < theta; a += step) {
  37674. var x = Math.cos(a);
  37675. var y = Math.sin(a);
  37676. var u = (x + 1) / 2;
  37677. var v = (1 - y) / 2;
  37678. positions.push(radius * x, radius * y, 0);
  37679. uvs.push(u, v);
  37680. }
  37681. if (arc === 1) {
  37682. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37683. uvs.push(uvs[2], uvs[3]);
  37684. }
  37685. //indices
  37686. var vertexNb = positions.length / 3;
  37687. for (var i = 1; i < vertexNb - 1; i++) {
  37688. indices.push(i + 1, 0, i);
  37689. }
  37690. // result
  37691. VertexData.ComputeNormals(positions, indices, normals);
  37692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37693. var vertexData = new VertexData();
  37694. vertexData.indices = indices;
  37695. vertexData.positions = positions;
  37696. vertexData.normals = normals;
  37697. vertexData.uvs = uvs;
  37698. return vertexData;
  37699. };
  37700. /**
  37701. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37702. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37703. * @param polygon a mesh built from polygonTriangulation.build()
  37704. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37705. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37706. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37707. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37708. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37709. * @returns the VertexData of the Polygon
  37710. */
  37711. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37712. var faceUV = fUV || new Array(3);
  37713. var faceColors = fColors;
  37714. var colors = [];
  37715. // default face colors and UV if undefined
  37716. for (var f = 0; f < 3; f++) {
  37717. if (faceUV[f] === undefined) {
  37718. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37719. }
  37720. if (faceColors && faceColors[f] === undefined) {
  37721. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37722. }
  37723. }
  37724. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37725. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37726. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37727. var indices = polygon.getIndices();
  37728. // set face colours and textures
  37729. var idx = 0;
  37730. var face = 0;
  37731. for (var index = 0; index < normals.length; index += 3) {
  37732. //Edge Face no. 1
  37733. if (Math.abs(normals[index + 1]) < 0.001) {
  37734. face = 1;
  37735. }
  37736. //Top Face no. 0
  37737. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37738. face = 0;
  37739. }
  37740. //Bottom Face no. 2
  37741. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37742. face = 2;
  37743. }
  37744. idx = index / 3;
  37745. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37746. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37747. if (faceColors) {
  37748. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37749. }
  37750. }
  37751. // sides
  37752. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37753. // Result
  37754. var vertexData = new VertexData();
  37755. vertexData.indices = indices;
  37756. vertexData.positions = positions;
  37757. vertexData.normals = normals;
  37758. vertexData.uvs = uvs;
  37759. if (faceColors) {
  37760. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37761. vertexData.colors = totalColors;
  37762. }
  37763. return vertexData;
  37764. };
  37765. /**
  37766. * Creates the VertexData of the IcoSphere
  37767. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37768. * * radius the radius of the IcoSphere, optional default 1
  37769. * * radiusX allows stretching in the x direction, optional, default radius
  37770. * * radiusY allows stretching in the y direction, optional, default radius
  37771. * * radiusZ allows stretching in the z direction, optional, default radius
  37772. * * flat when true creates a flat shaded mesh, optional, default true
  37773. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37774. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37775. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37776. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37777. * @returns the VertexData of the IcoSphere
  37778. */
  37779. VertexData.CreateIcoSphere = function (options) {
  37780. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37781. var radius = options.radius || 1;
  37782. var flat = (options.flat === undefined) ? true : options.flat;
  37783. var subdivisions = options.subdivisions || 4;
  37784. var radiusX = options.radiusX || radius;
  37785. var radiusY = options.radiusY || radius;
  37786. var radiusZ = options.radiusZ || radius;
  37787. var t = (1 + Math.sqrt(5)) / 2;
  37788. // 12 vertex x,y,z
  37789. var ico_vertices = [
  37790. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37791. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37792. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37793. ];
  37794. // index of 3 vertex makes a face of icopshere
  37795. var ico_indices = [
  37796. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37797. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37798. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37799. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37800. ];
  37801. // vertex for uv have aliased position, not for UV
  37802. var vertices_unalias_id = [
  37803. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37804. // vertex alias
  37805. 0,
  37806. 2,
  37807. 3,
  37808. 3,
  37809. 3,
  37810. 4,
  37811. 7,
  37812. 8,
  37813. 9,
  37814. 9,
  37815. 10,
  37816. 11 // 23: B + 12
  37817. ];
  37818. // uv as integer step (not pixels !)
  37819. var ico_vertexuv = [
  37820. 5, 1, 3, 1, 6, 4, 0, 0,
  37821. 5, 3, 4, 2, 2, 2, 4, 0,
  37822. 2, 0, 1, 1, 6, 0, 6, 2,
  37823. // vertex alias (for same vertex on different faces)
  37824. 0, 4,
  37825. 3, 3,
  37826. 4, 4,
  37827. 3, 1,
  37828. 4, 2,
  37829. 4, 4,
  37830. 0, 2,
  37831. 1, 1,
  37832. 2, 2,
  37833. 3, 3,
  37834. 1, 3,
  37835. 2, 4 // 23: B + 12
  37836. ];
  37837. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37838. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37839. // First island of uv mapping
  37840. // v = 4h 3+ 2
  37841. // v = 3h 9+ 4
  37842. // v = 2h 9+ 5 B
  37843. // v = 1h 9 1 0
  37844. // v = 0h 3 8 7 A
  37845. // u = 0 1 2 3 4 5 6 *a
  37846. // Second island of uv mapping
  37847. // v = 4h 0+ B+ 4+
  37848. // v = 3h A+ 2+
  37849. // v = 2h 7+ 6 3+
  37850. // v = 1h 8+ 3+
  37851. // v = 0h
  37852. // u = 0 1 2 3 4 5 6 *a
  37853. // Face layout on texture UV mapping
  37854. // ============
  37855. // \ 4 /\ 16 / ======
  37856. // \ / \ / /\ 11 /
  37857. // \/ 7 \/ / \ /
  37858. // ======= / 10 \/
  37859. // /\ 17 /\ =======
  37860. // / \ / \ \ 15 /\
  37861. // / 8 \/ 12 \ \ / \
  37862. // ============ \/ 6 \
  37863. // \ 18 /\ ============
  37864. // \ / \ \ 5 /\ 0 /
  37865. // \/ 13 \ \ / \ /
  37866. // ======= \/ 1 \/
  37867. // =============
  37868. // /\ 19 /\ 2 /\
  37869. // / \ / \ / \
  37870. // / 14 \/ 9 \/ 3 \
  37871. // ===================
  37872. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37873. var ustep = 138 / 1024;
  37874. var vstep = 239 / 1024;
  37875. var uoffset = 60 / 1024;
  37876. var voffset = 26 / 1024;
  37877. // Second island should have margin, not to touch the first island
  37878. // avoid any borderline artefact in pixel rounding
  37879. var island_u_offset = -40 / 1024;
  37880. var island_v_offset = +20 / 1024;
  37881. // face is either island 0 or 1 :
  37882. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37883. var island = [
  37884. 0, 0, 0, 0, 1,
  37885. 0, 0, 1, 1, 0,
  37886. 0, 0, 1, 1, 0,
  37887. 0, 1, 1, 1, 0 // 15 - 19
  37888. ];
  37889. var indices = new Array();
  37890. var positions = new Array();
  37891. var normals = new Array();
  37892. var uvs = new Array();
  37893. var current_indice = 0;
  37894. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37895. var face_vertex_pos = new Array(3);
  37896. var face_vertex_uv = new Array(3);
  37897. var v012;
  37898. for (v012 = 0; v012 < 3; v012++) {
  37899. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37900. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37901. }
  37902. // create all with normals
  37903. for (var face = 0; face < 20; face++) {
  37904. // 3 vertex per face
  37905. for (v012 = 0; v012 < 3; v012++) {
  37906. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37907. var v_id = ico_indices[3 * face + v012];
  37908. // vertex have 3D position (x,y,z)
  37909. 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]);
  37910. // Normalize to get normal, then scale to radius
  37911. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37912. // uv Coordinates from vertex ID
  37913. 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);
  37914. }
  37915. // Subdivide the face (interpolate pos, norm, uv)
  37916. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37917. // - norm is linear interpolation of vertex corner normal
  37918. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37919. // - uv is linear interpolation
  37920. //
  37921. // Topology is as below for sub-divide by 2
  37922. // vertex shown as v0,v1,v2
  37923. // interp index is i1 to progress in range [v0,v1[
  37924. // interp index is i2 to progress in range [v0,v2[
  37925. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37926. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37927. //
  37928. //
  37929. // i2 v2
  37930. // ^ ^
  37931. // / / \
  37932. // / / \
  37933. // / / \
  37934. // / / (0,1) \
  37935. // / #---------\
  37936. // / / \ (0,0)'/ \
  37937. // / / \ / \
  37938. // / / \ / \
  37939. // / / (0,0) \ / (1,0) \
  37940. // / #---------#---------\
  37941. // v0 v1
  37942. //
  37943. // --------------------> i1
  37944. //
  37945. // interp of (i1,i2):
  37946. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37947. // along i1 : lerp(x0,x1, i1/(S-i2))
  37948. //
  37949. // centroid of triangle is needed to get help normal computation
  37950. // (c1,c2) are used for centroid location
  37951. var interp_vertex = function (i1, i2, c1, c2) {
  37952. // vertex is interpolated from
  37953. // - face_vertex_pos[0..2]
  37954. // - face_vertex_uv[0..2]
  37955. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37956. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37957. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37958. pos_interp.normalize();
  37959. var vertex_normal;
  37960. if (flat) {
  37961. // in flat mode, recalculate normal as face centroid normal
  37962. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37963. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37964. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37965. }
  37966. else {
  37967. // in smooth mode, recalculate normal from each single vertex position
  37968. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37969. }
  37970. // Vertex normal need correction due to X,Y,Z radius scaling
  37971. vertex_normal.x /= radiusX;
  37972. vertex_normal.y /= radiusY;
  37973. vertex_normal.z /= radiusZ;
  37974. vertex_normal.normalize();
  37975. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37976. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37977. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37978. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37979. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37980. uvs.push(uv_interp.x, uv_interp.y);
  37981. // push each vertex has member of a face
  37982. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37983. indices.push(current_indice);
  37984. current_indice++;
  37985. };
  37986. for (var i2 = 0; i2 < subdivisions; i2++) {
  37987. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37988. // face : (i1,i2) for /\ :
  37989. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37990. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37991. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37992. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37993. if (i1 + i2 + 1 < subdivisions) {
  37994. // face : (i1,i2)' for \/ :
  37995. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37996. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37997. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37998. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37999. }
  38000. }
  38001. }
  38002. }
  38003. // Sides
  38004. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38005. // Result
  38006. var vertexData = new VertexData();
  38007. vertexData.indices = indices;
  38008. vertexData.positions = positions;
  38009. vertexData.normals = normals;
  38010. vertexData.uvs = uvs;
  38011. return vertexData;
  38012. };
  38013. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38014. /**
  38015. * Creates the VertexData for a Polyhedron
  38016. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38017. * * type provided types are:
  38018. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38019. * * 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)
  38020. * * size the size of the IcoSphere, optional default 1
  38021. * * sizeX allows stretching in the x direction, optional, default size
  38022. * * sizeY allows stretching in the y direction, optional, default size
  38023. * * sizeZ allows stretching in the z direction, optional, default size
  38024. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38025. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38026. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38027. * * flat when true creates a flat shaded mesh, optional, default true
  38028. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38029. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38030. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38031. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38032. * @returns the VertexData of the Polyhedron
  38033. */
  38034. VertexData.CreatePolyhedron = function (options) {
  38035. // provided polyhedron types :
  38036. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38037. // 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)
  38038. var polyhedra = [];
  38039. 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]] };
  38040. 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]] };
  38041. polyhedra[2] = {
  38042. 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]],
  38043. 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]]
  38044. };
  38045. polyhedra[3] = {
  38046. 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]],
  38047. 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]]
  38048. };
  38049. polyhedra[4] = {
  38050. 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]],
  38051. 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]]
  38052. };
  38053. 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]] };
  38054. 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]] };
  38055. 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]] };
  38056. 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]] };
  38057. 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]] };
  38058. 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]] };
  38059. 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]] };
  38060. 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]] };
  38061. 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]] };
  38062. polyhedra[14] = {
  38063. 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]],
  38064. 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]]
  38065. };
  38066. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38067. var size = options.size;
  38068. var sizeX = options.sizeX || size || 1;
  38069. var sizeY = options.sizeY || size || 1;
  38070. var sizeZ = options.sizeZ || size || 1;
  38071. var data = options.custom || polyhedra[type];
  38072. var nbfaces = data.face.length;
  38073. var faceUV = options.faceUV || new Array(nbfaces);
  38074. var faceColors = options.faceColors;
  38075. var flat = (options.flat === undefined) ? true : options.flat;
  38076. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38077. var positions = new Array();
  38078. var indices = new Array();
  38079. var normals = new Array();
  38080. var uvs = new Array();
  38081. var colors = new Array();
  38082. var index = 0;
  38083. var faceIdx = 0; // face cursor in the array "indexes"
  38084. var indexes = new Array();
  38085. var i = 0;
  38086. var f = 0;
  38087. var u, v, ang, x, y, tmp;
  38088. // default face colors and UV if undefined
  38089. if (flat) {
  38090. for (f = 0; f < nbfaces; f++) {
  38091. if (faceColors && faceColors[f] === undefined) {
  38092. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38093. }
  38094. if (faceUV && faceUV[f] === undefined) {
  38095. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38096. }
  38097. }
  38098. }
  38099. if (!flat) {
  38100. for (i = 0; i < data.vertex.length; i++) {
  38101. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38102. uvs.push(0, 0);
  38103. }
  38104. for (f = 0; f < nbfaces; f++) {
  38105. for (i = 0; i < data.face[f].length - 2; i++) {
  38106. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38107. }
  38108. }
  38109. }
  38110. else {
  38111. for (f = 0; f < nbfaces; f++) {
  38112. var fl = data.face[f].length; // number of vertices of the current face
  38113. ang = 2 * Math.PI / fl;
  38114. x = 0.5 * Math.tan(ang / 2);
  38115. y = 0.5;
  38116. // positions, uvs, colors
  38117. for (i = 0; i < fl; i++) {
  38118. // positions
  38119. 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);
  38120. indexes.push(index);
  38121. index++;
  38122. // uvs
  38123. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38124. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38125. uvs.push(u, v);
  38126. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38127. y = x * Math.sin(ang) + y * Math.cos(ang);
  38128. x = tmp;
  38129. // colors
  38130. if (faceColors) {
  38131. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38132. }
  38133. }
  38134. // indices from indexes
  38135. for (i = 0; i < fl - 2; i++) {
  38136. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38137. }
  38138. faceIdx += fl;
  38139. }
  38140. }
  38141. VertexData.ComputeNormals(positions, indices, normals);
  38142. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38143. var vertexData = new VertexData();
  38144. vertexData.positions = positions;
  38145. vertexData.indices = indices;
  38146. vertexData.normals = normals;
  38147. vertexData.uvs = uvs;
  38148. if (faceColors && flat) {
  38149. vertexData.colors = colors;
  38150. }
  38151. return vertexData;
  38152. };
  38153. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38154. /**
  38155. * Creates the VertexData for a TorusKnot
  38156. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38157. * * radius the radius of the torus knot, optional, default 2
  38158. * * tube the thickness of the tube, optional, default 0.5
  38159. * * radialSegments the number of sides on each tube segments, optional, default 32
  38160. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38161. * * p the number of windings around the z axis, optional, default 2
  38162. * * q the number of windings around the x axis, optional, default 3
  38163. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38164. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38165. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38166. * @returns the VertexData of the Torus Knot
  38167. */
  38168. VertexData.CreateTorusKnot = function (options) {
  38169. var indices = new Array();
  38170. var positions = new Array();
  38171. var normals = new Array();
  38172. var uvs = new Array();
  38173. var radius = options.radius || 2;
  38174. var tube = options.tube || 0.5;
  38175. var radialSegments = options.radialSegments || 32;
  38176. var tubularSegments = options.tubularSegments || 32;
  38177. var p = options.p || 2;
  38178. var q = options.q || 3;
  38179. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38180. // Helper
  38181. var getPos = function (angle) {
  38182. var cu = Math.cos(angle);
  38183. var su = Math.sin(angle);
  38184. var quOverP = q / p * angle;
  38185. var cs = Math.cos(quOverP);
  38186. var tx = radius * (2 + cs) * 0.5 * cu;
  38187. var ty = radius * (2 + cs) * su * 0.5;
  38188. var tz = radius * Math.sin(quOverP) * 0.5;
  38189. return new BABYLON.Vector3(tx, ty, tz);
  38190. };
  38191. // Vertices
  38192. var i;
  38193. var j;
  38194. for (i = 0; i <= radialSegments; i++) {
  38195. var modI = i % radialSegments;
  38196. var u = modI / radialSegments * 2 * p * Math.PI;
  38197. var p1 = getPos(u);
  38198. var p2 = getPos(u + 0.01);
  38199. var tang = p2.subtract(p1);
  38200. var n = p2.add(p1);
  38201. var bitan = BABYLON.Vector3.Cross(tang, n);
  38202. n = BABYLON.Vector3.Cross(bitan, tang);
  38203. bitan.normalize();
  38204. n.normalize();
  38205. for (j = 0; j < tubularSegments; j++) {
  38206. var modJ = j % tubularSegments;
  38207. var v = modJ / tubularSegments * 2 * Math.PI;
  38208. var cx = -tube * Math.cos(v);
  38209. var cy = tube * Math.sin(v);
  38210. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38211. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38212. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38213. uvs.push(i / radialSegments);
  38214. uvs.push(j / tubularSegments);
  38215. }
  38216. }
  38217. for (i = 0; i < radialSegments; i++) {
  38218. for (j = 0; j < tubularSegments; j++) {
  38219. var jNext = (j + 1) % tubularSegments;
  38220. var a = i * tubularSegments + j;
  38221. var b = (i + 1) * tubularSegments + j;
  38222. var c = (i + 1) * tubularSegments + jNext;
  38223. var d = i * tubularSegments + jNext;
  38224. indices.push(d);
  38225. indices.push(b);
  38226. indices.push(a);
  38227. indices.push(d);
  38228. indices.push(c);
  38229. indices.push(b);
  38230. }
  38231. }
  38232. // Normals
  38233. VertexData.ComputeNormals(positions, indices, normals);
  38234. // Sides
  38235. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38236. // Result
  38237. var vertexData = new VertexData();
  38238. vertexData.indices = indices;
  38239. vertexData.positions = positions;
  38240. vertexData.normals = normals;
  38241. vertexData.uvs = uvs;
  38242. return vertexData;
  38243. };
  38244. // Tools
  38245. /**
  38246. * Compute normals for given positions and indices
  38247. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38248. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38249. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38250. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38251. * * facetNormals : optional array of facet normals (vector3)
  38252. * * facetPositions : optional array of facet positions (vector3)
  38253. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38254. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38255. * * bInfo : optional bounding info, required for facetPartitioning computation
  38256. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38257. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38258. * * useRightHandedSystem: optional boolean to for right handed system computation
  38259. * * depthSort : optional boolean to enable the facet depth sort computation
  38260. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38261. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38262. */
  38263. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38264. // temporary scalar variables
  38265. var index = 0; // facet index
  38266. var p1p2x = 0.0; // p1p2 vector x coordinate
  38267. var p1p2y = 0.0; // p1p2 vector y coordinate
  38268. var p1p2z = 0.0; // p1p2 vector z coordinate
  38269. var p3p2x = 0.0; // p3p2 vector x coordinate
  38270. var p3p2y = 0.0; // p3p2 vector y coordinate
  38271. var p3p2z = 0.0; // p3p2 vector z coordinate
  38272. var faceNormalx = 0.0; // facet normal x coordinate
  38273. var faceNormaly = 0.0; // facet normal y coordinate
  38274. var faceNormalz = 0.0; // facet normal z coordinate
  38275. var length = 0.0; // facet normal length before normalization
  38276. var v1x = 0; // vector1 x index in the positions array
  38277. var v1y = 0; // vector1 y index in the positions array
  38278. var v1z = 0; // vector1 z index in the positions array
  38279. var v2x = 0; // vector2 x index in the positions array
  38280. var v2y = 0; // vector2 y index in the positions array
  38281. var v2z = 0; // vector2 z index in the positions array
  38282. var v3x = 0; // vector3 x index in the positions array
  38283. var v3y = 0; // vector3 y index in the positions array
  38284. var v3z = 0; // vector3 z index in the positions array
  38285. var computeFacetNormals = false;
  38286. var computeFacetPositions = false;
  38287. var computeFacetPartitioning = false;
  38288. var computeDepthSort = false;
  38289. var faceNormalSign = 1;
  38290. var ratio = 0;
  38291. var distanceTo = null;
  38292. if (options) {
  38293. computeFacetNormals = (options.facetNormals) ? true : false;
  38294. computeFacetPositions = (options.facetPositions) ? true : false;
  38295. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38296. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38297. ratio = options.ratio || 0;
  38298. computeDepthSort = (options.depthSort) ? true : false;
  38299. distanceTo = (options.distanceTo);
  38300. if (computeDepthSort) {
  38301. if (distanceTo === undefined) {
  38302. distanceTo = BABYLON.Vector3.Zero();
  38303. }
  38304. var depthSortedFacets = options.depthSortedFacets;
  38305. }
  38306. }
  38307. // facetPartitioning reinit if needed
  38308. var xSubRatio = 0;
  38309. var ySubRatio = 0;
  38310. var zSubRatio = 0;
  38311. var subSq = 0;
  38312. if (computeFacetPartitioning && options && options.bbSize) {
  38313. var ox = 0; // X partitioning index for facet position
  38314. var oy = 0; // Y partinioning index for facet position
  38315. var oz = 0; // Z partinioning index for facet position
  38316. var b1x = 0; // X partitioning index for facet v1 vertex
  38317. var b1y = 0; // Y partitioning index for facet v1 vertex
  38318. var b1z = 0; // z partitioning index for facet v1 vertex
  38319. var b2x = 0; // X partitioning index for facet v2 vertex
  38320. var b2y = 0; // Y partitioning index for facet v2 vertex
  38321. var b2z = 0; // Z partitioning index for facet v2 vertex
  38322. var b3x = 0; // X partitioning index for facet v3 vertex
  38323. var b3y = 0; // Y partitioning index for facet v3 vertex
  38324. var b3z = 0; // Z partitioning index for facet v3 vertex
  38325. var block_idx_o = 0; // facet barycenter block index
  38326. var block_idx_v1 = 0; // v1 vertex block index
  38327. var block_idx_v2 = 0; // v2 vertex block index
  38328. var block_idx_v3 = 0; // v3 vertex block index
  38329. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38330. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38331. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38332. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38333. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38334. subSq = options.subDiv.max * options.subDiv.max;
  38335. options.facetPartitioning.length = 0;
  38336. }
  38337. // reset the normals
  38338. for (index = 0; index < positions.length; index++) {
  38339. normals[index] = 0.0;
  38340. }
  38341. // Loop : 1 indice triplet = 1 facet
  38342. var nbFaces = (indices.length / 3) | 0;
  38343. for (index = 0; index < nbFaces; index++) {
  38344. // get the indexes of the coordinates of each vertex of the facet
  38345. v1x = indices[index * 3] * 3;
  38346. v1y = v1x + 1;
  38347. v1z = v1x + 2;
  38348. v2x = indices[index * 3 + 1] * 3;
  38349. v2y = v2x + 1;
  38350. v2z = v2x + 2;
  38351. v3x = indices[index * 3 + 2] * 3;
  38352. v3y = v3x + 1;
  38353. v3z = v3x + 2;
  38354. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38355. p1p2y = positions[v1y] - positions[v2y];
  38356. p1p2z = positions[v1z] - positions[v2z];
  38357. p3p2x = positions[v3x] - positions[v2x];
  38358. p3p2y = positions[v3y] - positions[v2y];
  38359. p3p2z = positions[v3z] - positions[v2z];
  38360. // compute the face normal with the cross product
  38361. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38362. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38363. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38364. // normalize this normal and store it in the array facetData
  38365. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38366. length = (length === 0) ? 1.0 : length;
  38367. faceNormalx /= length;
  38368. faceNormaly /= length;
  38369. faceNormalz /= length;
  38370. if (computeFacetNormals && options) {
  38371. options.facetNormals[index].x = faceNormalx;
  38372. options.facetNormals[index].y = faceNormaly;
  38373. options.facetNormals[index].z = faceNormalz;
  38374. }
  38375. if (computeFacetPositions && options) {
  38376. // compute and the facet barycenter coordinates in the array facetPositions
  38377. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38378. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38379. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38380. }
  38381. if (computeFacetPartitioning && options) {
  38382. // store the facet indexes in arrays in the main facetPartitioning array :
  38383. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38384. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38385. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38386. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38387. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38388. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38389. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38390. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38391. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38392. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38393. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38394. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38395. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38396. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38397. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38398. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38399. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38400. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38401. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38402. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38403. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38404. // push each facet index in each block containing the vertex
  38405. options.facetPartitioning[block_idx_v1].push(index);
  38406. if (block_idx_v2 != block_idx_v1) {
  38407. options.facetPartitioning[block_idx_v2].push(index);
  38408. }
  38409. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38410. options.facetPartitioning[block_idx_v3].push(index);
  38411. }
  38412. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38413. options.facetPartitioning[block_idx_o].push(index);
  38414. }
  38415. }
  38416. if (computeDepthSort && options && options.facetPositions) {
  38417. var dsf = depthSortedFacets[index];
  38418. dsf.ind = index * 3;
  38419. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38420. }
  38421. // compute the normals anyway
  38422. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38423. normals[v1y] += faceNormaly;
  38424. normals[v1z] += faceNormalz;
  38425. normals[v2x] += faceNormalx;
  38426. normals[v2y] += faceNormaly;
  38427. normals[v2z] += faceNormalz;
  38428. normals[v3x] += faceNormalx;
  38429. normals[v3y] += faceNormaly;
  38430. normals[v3z] += faceNormalz;
  38431. }
  38432. // last normalization of each normal
  38433. for (index = 0; index < normals.length / 3; index++) {
  38434. faceNormalx = normals[index * 3];
  38435. faceNormaly = normals[index * 3 + 1];
  38436. faceNormalz = normals[index * 3 + 2];
  38437. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38438. length = (length === 0) ? 1.0 : length;
  38439. faceNormalx /= length;
  38440. faceNormaly /= length;
  38441. faceNormalz /= length;
  38442. normals[index * 3] = faceNormalx;
  38443. normals[index * 3 + 1] = faceNormaly;
  38444. normals[index * 3 + 2] = faceNormalz;
  38445. }
  38446. };
  38447. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38448. var li = indices.length;
  38449. var ln = normals.length;
  38450. var i;
  38451. var n;
  38452. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38453. switch (sideOrientation) {
  38454. case BABYLON.Mesh.FRONTSIDE:
  38455. // nothing changed
  38456. break;
  38457. case BABYLON.Mesh.BACKSIDE:
  38458. var tmp;
  38459. // indices
  38460. for (i = 0; i < li; i += 3) {
  38461. tmp = indices[i];
  38462. indices[i] = indices[i + 2];
  38463. indices[i + 2] = tmp;
  38464. }
  38465. // normals
  38466. for (n = 0; n < ln; n++) {
  38467. normals[n] = -normals[n];
  38468. }
  38469. break;
  38470. case BABYLON.Mesh.DOUBLESIDE:
  38471. // positions
  38472. var lp = positions.length;
  38473. var l = lp / 3;
  38474. for (var p = 0; p < lp; p++) {
  38475. positions[lp + p] = positions[p];
  38476. }
  38477. // indices
  38478. for (i = 0; i < li; i += 3) {
  38479. indices[i + li] = indices[i + 2] + l;
  38480. indices[i + 1 + li] = indices[i + 1] + l;
  38481. indices[i + 2 + li] = indices[i] + l;
  38482. }
  38483. // normals
  38484. for (n = 0; n < ln; n++) {
  38485. normals[ln + n] = -normals[n];
  38486. }
  38487. // uvs
  38488. var lu = uvs.length;
  38489. var u = 0;
  38490. for (u = 0; u < lu; u++) {
  38491. uvs[u + lu] = uvs[u];
  38492. }
  38493. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38494. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38495. u = 0;
  38496. for (i = 0; i < lu / 2; i++) {
  38497. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38498. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38499. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38500. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38501. u += 2;
  38502. }
  38503. break;
  38504. }
  38505. };
  38506. /**
  38507. * Applies VertexData created from the imported parameters to the geometry
  38508. * @param parsedVertexData the parsed data from an imported file
  38509. * @param geometry the geometry to apply the VertexData to
  38510. */
  38511. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38512. var vertexData = new VertexData();
  38513. // positions
  38514. var positions = parsedVertexData.positions;
  38515. if (positions) {
  38516. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38517. }
  38518. // normals
  38519. var normals = parsedVertexData.normals;
  38520. if (normals) {
  38521. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38522. }
  38523. // tangents
  38524. var tangents = parsedVertexData.tangents;
  38525. if (tangents) {
  38526. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38527. }
  38528. // uvs
  38529. var uvs = parsedVertexData.uvs;
  38530. if (uvs) {
  38531. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38532. }
  38533. // uv2s
  38534. var uv2s = parsedVertexData.uv2s;
  38535. if (uv2s) {
  38536. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38537. }
  38538. // uv3s
  38539. var uv3s = parsedVertexData.uv3s;
  38540. if (uv3s) {
  38541. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38542. }
  38543. // uv4s
  38544. var uv4s = parsedVertexData.uv4s;
  38545. if (uv4s) {
  38546. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38547. }
  38548. // uv5s
  38549. var uv5s = parsedVertexData.uv5s;
  38550. if (uv5s) {
  38551. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38552. }
  38553. // uv6s
  38554. var uv6s = parsedVertexData.uv6s;
  38555. if (uv6s) {
  38556. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38557. }
  38558. // colors
  38559. var colors = parsedVertexData.colors;
  38560. if (colors) {
  38561. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38562. }
  38563. // matricesIndices
  38564. var matricesIndices = parsedVertexData.matricesIndices;
  38565. if (matricesIndices) {
  38566. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38567. }
  38568. // matricesWeights
  38569. var matricesWeights = parsedVertexData.matricesWeights;
  38570. if (matricesWeights) {
  38571. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38572. }
  38573. // indices
  38574. var indices = parsedVertexData.indices;
  38575. if (indices) {
  38576. vertexData.indices = indices;
  38577. }
  38578. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38579. };
  38580. return VertexData;
  38581. }());
  38582. BABYLON.VertexData = VertexData;
  38583. })(BABYLON || (BABYLON = {}));
  38584. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38585. var BABYLON;
  38586. (function (BABYLON) {
  38587. /**
  38588. * Class used to store geometry data (vertex buffers + index buffer)
  38589. */
  38590. var Geometry = /** @class */ (function () {
  38591. /**
  38592. * Creates a new geometry
  38593. * @param id defines the unique ID
  38594. * @param scene defines the hosting scene
  38595. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38596. * @param updatable defines if geometry must be updatable (false by default)
  38597. * @param mesh defines the mesh that will be associated with the geometry
  38598. */
  38599. function Geometry(id, scene, vertexData, updatable, mesh) {
  38600. if (updatable === void 0) { updatable = false; }
  38601. if (mesh === void 0) { mesh = null; }
  38602. /**
  38603. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38604. */
  38605. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38606. this._totalVertices = 0;
  38607. this._isDisposed = false;
  38608. this._indexBufferIsUpdatable = false;
  38609. this.id = id;
  38610. this._engine = scene.getEngine();
  38611. this._meshes = [];
  38612. this._scene = scene;
  38613. //Init vertex buffer cache
  38614. this._vertexBuffers = {};
  38615. this._indices = [];
  38616. this._updatable = updatable;
  38617. // vertexData
  38618. if (vertexData) {
  38619. this.setAllVerticesData(vertexData, updatable);
  38620. }
  38621. else {
  38622. this._totalVertices = 0;
  38623. this._indices = [];
  38624. }
  38625. if (this._engine.getCaps().vertexArrayObject) {
  38626. this._vertexArrayObjects = {};
  38627. }
  38628. // applyToMesh
  38629. if (mesh) {
  38630. if (mesh.getClassName() === "LinesMesh") {
  38631. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38632. this._updateExtend();
  38633. }
  38634. this.applyToMesh(mesh);
  38635. mesh.computeWorldMatrix(true);
  38636. }
  38637. }
  38638. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38639. /**
  38640. * Gets or sets 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
  38641. */
  38642. get: function () {
  38643. return this._boundingBias;
  38644. },
  38645. /**
  38646. * Gets or sets 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
  38647. */
  38648. set: function (value) {
  38649. if (this._boundingBias && this._boundingBias.equals(value)) {
  38650. return;
  38651. }
  38652. this._boundingBias = value.clone();
  38653. this._updateBoundingInfo(true, null);
  38654. },
  38655. enumerable: true,
  38656. configurable: true
  38657. });
  38658. /**
  38659. * Static function used to attach a new empty geometry to a mesh
  38660. * @param mesh defines the mesh to attach the geometry to
  38661. * @returns the new {BABYLON.Geometry}
  38662. */
  38663. Geometry.CreateGeometryForMesh = function (mesh) {
  38664. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38665. geometry.applyToMesh(mesh);
  38666. return geometry;
  38667. };
  38668. Object.defineProperty(Geometry.prototype, "extend", {
  38669. /**
  38670. * Gets the current extend of the geometry
  38671. */
  38672. get: function () {
  38673. return this._extend;
  38674. },
  38675. enumerable: true,
  38676. configurable: true
  38677. });
  38678. /**
  38679. * Gets the hosting scene
  38680. * @returns the hosting {BABYLON.Scene}
  38681. */
  38682. Geometry.prototype.getScene = function () {
  38683. return this._scene;
  38684. };
  38685. /**
  38686. * Gets the hosting engine
  38687. * @returns the hosting {BABYLON.Engine}
  38688. */
  38689. Geometry.prototype.getEngine = function () {
  38690. return this._engine;
  38691. };
  38692. /**
  38693. * Defines if the geometry is ready to use
  38694. * @returns true if the geometry is ready to be used
  38695. */
  38696. Geometry.prototype.isReady = function () {
  38697. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38698. };
  38699. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38700. /**
  38701. * Gets a value indicating that the geometry should not be serialized
  38702. */
  38703. get: function () {
  38704. for (var index = 0; index < this._meshes.length; index++) {
  38705. if (!this._meshes[index].doNotSerialize) {
  38706. return false;
  38707. }
  38708. }
  38709. return true;
  38710. },
  38711. enumerable: true,
  38712. configurable: true
  38713. });
  38714. /** @hidden */
  38715. Geometry.prototype._rebuild = function () {
  38716. if (this._vertexArrayObjects) {
  38717. this._vertexArrayObjects = {};
  38718. }
  38719. // Index buffer
  38720. if (this._meshes.length !== 0 && this._indices) {
  38721. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38722. }
  38723. // Vertex buffers
  38724. for (var key in this._vertexBuffers) {
  38725. var vertexBuffer = this._vertexBuffers[key];
  38726. vertexBuffer._rebuild();
  38727. }
  38728. };
  38729. /**
  38730. * Affects all geometry data in one call
  38731. * @param vertexData defines the geometry data
  38732. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38733. */
  38734. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38735. vertexData.applyToGeometry(this, updatable);
  38736. this.notifyUpdate();
  38737. };
  38738. /**
  38739. * Set specific vertex data
  38740. * @param kind defines the data kind (Position, normal, etc...)
  38741. * @param data defines the vertex data to use
  38742. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38743. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38744. */
  38745. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38746. if (updatable === void 0) { updatable = false; }
  38747. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38748. this.setVerticesBuffer(buffer);
  38749. };
  38750. /**
  38751. * Removes a specific vertex data
  38752. * @param kind defines the data kind (Position, normal, etc...)
  38753. */
  38754. Geometry.prototype.removeVerticesData = function (kind) {
  38755. if (this._vertexBuffers[kind]) {
  38756. this._vertexBuffers[kind].dispose();
  38757. delete this._vertexBuffers[kind];
  38758. }
  38759. };
  38760. /**
  38761. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38762. * @param buffer defines the vertex buffer to use
  38763. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38764. */
  38765. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38766. if (totalVertices === void 0) { totalVertices = null; }
  38767. var kind = buffer.getKind();
  38768. if (this._vertexBuffers[kind]) {
  38769. this._vertexBuffers[kind].dispose();
  38770. }
  38771. this._vertexBuffers[kind] = buffer;
  38772. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38773. var data = buffer.getData();
  38774. if (totalVertices != null) {
  38775. this._totalVertices = totalVertices;
  38776. }
  38777. else {
  38778. if (data != null) {
  38779. this._totalVertices = data.length / (buffer.byteStride / 4);
  38780. }
  38781. }
  38782. this._updateExtend(data);
  38783. this._resetPointsArrayCache();
  38784. var meshes = this._meshes;
  38785. var numOfMeshes = meshes.length;
  38786. for (var index = 0; index < numOfMeshes; index++) {
  38787. var mesh = meshes[index];
  38788. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38789. mesh._createGlobalSubMesh(false);
  38790. mesh.computeWorldMatrix(true);
  38791. }
  38792. }
  38793. this.notifyUpdate(kind);
  38794. if (this._vertexArrayObjects) {
  38795. this._disposeVertexArrayObjects();
  38796. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38797. }
  38798. };
  38799. /**
  38800. * Update a specific vertex buffer
  38801. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38802. * It will do nothing if the buffer is not updatable
  38803. * @param kind defines the data kind (Position, normal, etc...)
  38804. * @param data defines the data to use
  38805. * @param offset defines the offset in the target buffer where to store the data
  38806. * @param useBytes set to true if the offset is in bytes
  38807. */
  38808. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38809. if (useBytes === void 0) { useBytes = false; }
  38810. var vertexBuffer = this.getVertexBuffer(kind);
  38811. if (!vertexBuffer) {
  38812. return;
  38813. }
  38814. vertexBuffer.updateDirectly(data, offset, useBytes);
  38815. this.notifyUpdate(kind);
  38816. };
  38817. /**
  38818. * Update a specific vertex buffer
  38819. * This function will create a new buffer if the current one is not updatable
  38820. * @param kind defines the data kind (Position, normal, etc...)
  38821. * @param data defines the data to use
  38822. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38823. */
  38824. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38825. if (updateExtends === void 0) { updateExtends = false; }
  38826. var vertexBuffer = this.getVertexBuffer(kind);
  38827. if (!vertexBuffer) {
  38828. return;
  38829. }
  38830. vertexBuffer.update(data);
  38831. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38832. this._updateBoundingInfo(updateExtends, data);
  38833. }
  38834. this.notifyUpdate(kind);
  38835. };
  38836. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38837. if (updateExtends) {
  38838. this._updateExtend(data);
  38839. }
  38840. var meshes = this._meshes;
  38841. var numOfMeshes = meshes.length;
  38842. this._resetPointsArrayCache();
  38843. for (var index = 0; index < numOfMeshes; index++) {
  38844. var mesh = meshes[index];
  38845. if (updateExtends) {
  38846. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38847. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38848. var subMesh = mesh.subMeshes[subIndex];
  38849. subMesh.refreshBoundingInfo();
  38850. }
  38851. }
  38852. }
  38853. };
  38854. /** @hidden */
  38855. Geometry.prototype._bind = function (effect, indexToBind) {
  38856. if (!effect) {
  38857. return;
  38858. }
  38859. if (indexToBind === undefined) {
  38860. indexToBind = this._indexBuffer;
  38861. }
  38862. var vbs = this.getVertexBuffers();
  38863. if (!vbs) {
  38864. return;
  38865. }
  38866. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38867. this._engine.bindBuffers(vbs, indexToBind, effect);
  38868. return;
  38869. }
  38870. // Using VAO
  38871. if (!this._vertexArrayObjects[effect.key]) {
  38872. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38873. }
  38874. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38875. };
  38876. /**
  38877. * Gets total number of vertices
  38878. * @returns the total number of vertices
  38879. */
  38880. Geometry.prototype.getTotalVertices = function () {
  38881. if (!this.isReady()) {
  38882. return 0;
  38883. }
  38884. return this._totalVertices;
  38885. };
  38886. /**
  38887. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38888. * @param kind defines the data kind (Position, normal, etc...)
  38889. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38890. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38891. * @returns a float array containing vertex data
  38892. */
  38893. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38894. var vertexBuffer = this.getVertexBuffer(kind);
  38895. if (!vertexBuffer) {
  38896. return null;
  38897. }
  38898. var data = vertexBuffer.getData();
  38899. if (!data) {
  38900. return null;
  38901. }
  38902. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38903. var count = this._totalVertices * vertexBuffer.getSize();
  38904. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38905. var copy_1 = new Array(count);
  38906. vertexBuffer.forEach(count, function (value, index) {
  38907. copy_1[index] = value;
  38908. });
  38909. return copy_1;
  38910. }
  38911. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38912. if (data instanceof Array) {
  38913. var offset = vertexBuffer.byteOffset / 4;
  38914. return BABYLON.Tools.Slice(data, offset, offset + count);
  38915. }
  38916. else if (data instanceof ArrayBuffer) {
  38917. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38918. }
  38919. else {
  38920. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38921. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38922. var result = new Float32Array(count);
  38923. var source = new Float32Array(data.buffer, offset, count);
  38924. result.set(source);
  38925. return result;
  38926. }
  38927. return new Float32Array(data.buffer, offset, count);
  38928. }
  38929. }
  38930. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38931. return BABYLON.Tools.Slice(data);
  38932. }
  38933. return data;
  38934. };
  38935. /**
  38936. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38937. * @param kind defines the data kind (Position, normal, etc...)
  38938. * @returns true if the vertex buffer with the specified kind is updatable
  38939. */
  38940. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38941. var vb = this._vertexBuffers[kind];
  38942. if (!vb) {
  38943. return false;
  38944. }
  38945. return vb.isUpdatable();
  38946. };
  38947. /**
  38948. * Gets a specific vertex buffer
  38949. * @param kind defines the data kind (Position, normal, etc...)
  38950. * @returns a {BABYLON.VertexBuffer}
  38951. */
  38952. Geometry.prototype.getVertexBuffer = function (kind) {
  38953. if (!this.isReady()) {
  38954. return null;
  38955. }
  38956. return this._vertexBuffers[kind];
  38957. };
  38958. /**
  38959. * Returns all vertex buffers
  38960. * @return an object holding all vertex buffers indexed by kind
  38961. */
  38962. Geometry.prototype.getVertexBuffers = function () {
  38963. if (!this.isReady()) {
  38964. return null;
  38965. }
  38966. return this._vertexBuffers;
  38967. };
  38968. /**
  38969. * Gets a boolean indicating if specific vertex buffer is present
  38970. * @param kind defines the data kind (Position, normal, etc...)
  38971. * @returns true if data is present
  38972. */
  38973. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38974. if (!this._vertexBuffers) {
  38975. if (this._delayInfo) {
  38976. return this._delayInfo.indexOf(kind) !== -1;
  38977. }
  38978. return false;
  38979. }
  38980. return this._vertexBuffers[kind] !== undefined;
  38981. };
  38982. /**
  38983. * Gets a list of all attached data kinds (Position, normal, etc...)
  38984. * @returns a list of string containing all kinds
  38985. */
  38986. Geometry.prototype.getVerticesDataKinds = function () {
  38987. var result = [];
  38988. var kind;
  38989. if (!this._vertexBuffers && this._delayInfo) {
  38990. for (kind in this._delayInfo) {
  38991. result.push(kind);
  38992. }
  38993. }
  38994. else {
  38995. for (kind in this._vertexBuffers) {
  38996. result.push(kind);
  38997. }
  38998. }
  38999. return result;
  39000. };
  39001. /**
  39002. * Update index buffer
  39003. * @param indices defines the indices to store in the index buffer
  39004. * @param offset defines the offset in the target buffer where to store the data
  39005. */
  39006. Geometry.prototype.updateIndices = function (indices, offset) {
  39007. if (!this._indexBuffer) {
  39008. return;
  39009. }
  39010. if (!this._indexBufferIsUpdatable) {
  39011. this.setIndices(indices, null, true);
  39012. }
  39013. else {
  39014. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39015. }
  39016. };
  39017. /**
  39018. * Creates a new index buffer
  39019. * @param indices defines the indices to store in the index buffer
  39020. * @param totalVertices defines the total number of vertices (could be null)
  39021. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39022. */
  39023. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39024. if (totalVertices === void 0) { totalVertices = null; }
  39025. if (updatable === void 0) { updatable = false; }
  39026. if (this._indexBuffer) {
  39027. this._engine._releaseBuffer(this._indexBuffer);
  39028. }
  39029. this._disposeVertexArrayObjects();
  39030. this._indices = indices;
  39031. this._indexBufferIsUpdatable = updatable;
  39032. if (this._meshes.length !== 0 && this._indices) {
  39033. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39034. }
  39035. if (totalVertices != undefined) { // including null and undefined
  39036. this._totalVertices = totalVertices;
  39037. }
  39038. var meshes = this._meshes;
  39039. var numOfMeshes = meshes.length;
  39040. for (var index = 0; index < numOfMeshes; index++) {
  39041. meshes[index]._createGlobalSubMesh(true);
  39042. }
  39043. this.notifyUpdate();
  39044. };
  39045. /**
  39046. * Return the total number of indices
  39047. * @returns the total number of indices
  39048. */
  39049. Geometry.prototype.getTotalIndices = function () {
  39050. if (!this.isReady()) {
  39051. return 0;
  39052. }
  39053. return this._indices.length;
  39054. };
  39055. /**
  39056. * Gets the index buffer array
  39057. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39058. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39059. * @returns the index buffer array
  39060. */
  39061. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39062. if (!this.isReady()) {
  39063. return null;
  39064. }
  39065. var orig = this._indices;
  39066. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39067. return orig;
  39068. }
  39069. else {
  39070. var len = orig.length;
  39071. var copy = [];
  39072. for (var i = 0; i < len; i++) {
  39073. copy.push(orig[i]);
  39074. }
  39075. return copy;
  39076. }
  39077. };
  39078. /**
  39079. * Gets the index buffer
  39080. * @return the index buffer
  39081. */
  39082. Geometry.prototype.getIndexBuffer = function () {
  39083. if (!this.isReady()) {
  39084. return null;
  39085. }
  39086. return this._indexBuffer;
  39087. };
  39088. /** @hidden */
  39089. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39090. if (effect === void 0) { effect = null; }
  39091. if (!effect || !this._vertexArrayObjects) {
  39092. return;
  39093. }
  39094. if (this._vertexArrayObjects[effect.key]) {
  39095. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39096. delete this._vertexArrayObjects[effect.key];
  39097. }
  39098. };
  39099. /**
  39100. * Release the associated resources for a specific mesh
  39101. * @param mesh defines the source mesh
  39102. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39103. */
  39104. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39105. var meshes = this._meshes;
  39106. var index = meshes.indexOf(mesh);
  39107. if (index === -1) {
  39108. return;
  39109. }
  39110. meshes.splice(index, 1);
  39111. mesh._geometry = null;
  39112. if (meshes.length === 0 && shouldDispose) {
  39113. this.dispose();
  39114. }
  39115. };
  39116. /**
  39117. * Apply current geometry to a given mesh
  39118. * @param mesh defines the mesh to apply geometry to
  39119. */
  39120. Geometry.prototype.applyToMesh = function (mesh) {
  39121. if (mesh._geometry === this) {
  39122. return;
  39123. }
  39124. var previousGeometry = mesh._geometry;
  39125. if (previousGeometry) {
  39126. previousGeometry.releaseForMesh(mesh);
  39127. }
  39128. var meshes = this._meshes;
  39129. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39130. mesh._geometry = this;
  39131. this._scene.pushGeometry(this);
  39132. meshes.push(mesh);
  39133. if (this.isReady()) {
  39134. this._applyToMesh(mesh);
  39135. }
  39136. else {
  39137. mesh._boundingInfo = this._boundingInfo;
  39138. }
  39139. };
  39140. Geometry.prototype._updateExtend = function (data) {
  39141. if (data === void 0) { data = null; }
  39142. if (!data) {
  39143. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39144. }
  39145. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39146. };
  39147. Geometry.prototype._applyToMesh = function (mesh) {
  39148. var numOfMeshes = this._meshes.length;
  39149. // vertexBuffers
  39150. for (var kind in this._vertexBuffers) {
  39151. if (numOfMeshes === 1) {
  39152. this._vertexBuffers[kind].create();
  39153. }
  39154. var buffer = this._vertexBuffers[kind].getBuffer();
  39155. if (buffer)
  39156. buffer.references = numOfMeshes;
  39157. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39158. if (!this._extend) {
  39159. this._updateExtend();
  39160. }
  39161. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39162. mesh._createGlobalSubMesh(false);
  39163. //bounding info was just created again, world matrix should be applied again.
  39164. mesh._updateBoundingInfo();
  39165. }
  39166. }
  39167. // indexBuffer
  39168. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39169. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39170. }
  39171. if (this._indexBuffer) {
  39172. this._indexBuffer.references = numOfMeshes;
  39173. }
  39174. };
  39175. Geometry.prototype.notifyUpdate = function (kind) {
  39176. if (this.onGeometryUpdated) {
  39177. this.onGeometryUpdated(this, kind);
  39178. }
  39179. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39180. var mesh = _a[_i];
  39181. mesh._markSubMeshesAsAttributesDirty();
  39182. }
  39183. };
  39184. /**
  39185. * Load the geometry if it was flagged as delay loaded
  39186. * @param scene defines the hosting scene
  39187. * @param onLoaded defines a callback called when the geometry is loaded
  39188. */
  39189. Geometry.prototype.load = function (scene, onLoaded) {
  39190. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39191. return;
  39192. }
  39193. if (this.isReady()) {
  39194. if (onLoaded) {
  39195. onLoaded();
  39196. }
  39197. return;
  39198. }
  39199. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39200. this._queueLoad(scene, onLoaded);
  39201. };
  39202. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39203. var _this = this;
  39204. if (!this.delayLoadingFile) {
  39205. return;
  39206. }
  39207. scene._addPendingData(this);
  39208. scene._loadFile(this.delayLoadingFile, function (data) {
  39209. if (!_this._delayLoadingFunction) {
  39210. return;
  39211. }
  39212. _this._delayLoadingFunction(JSON.parse(data), _this);
  39213. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39214. _this._delayInfo = [];
  39215. scene._removePendingData(_this);
  39216. var meshes = _this._meshes;
  39217. var numOfMeshes = meshes.length;
  39218. for (var index = 0; index < numOfMeshes; index++) {
  39219. _this._applyToMesh(meshes[index]);
  39220. }
  39221. if (onLoaded) {
  39222. onLoaded();
  39223. }
  39224. }, undefined, true);
  39225. };
  39226. /**
  39227. * Invert the geometry to move from a right handed system to a left handed one.
  39228. */
  39229. Geometry.prototype.toLeftHanded = function () {
  39230. // Flip faces
  39231. var tIndices = this.getIndices(false);
  39232. if (tIndices != null && tIndices.length > 0) {
  39233. for (var i = 0; i < tIndices.length; i += 3) {
  39234. var tTemp = tIndices[i + 0];
  39235. tIndices[i + 0] = tIndices[i + 2];
  39236. tIndices[i + 2] = tTemp;
  39237. }
  39238. this.setIndices(tIndices);
  39239. }
  39240. // Negate position.z
  39241. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39242. if (tPositions != null && tPositions.length > 0) {
  39243. for (var i = 0; i < tPositions.length; i += 3) {
  39244. tPositions[i + 2] = -tPositions[i + 2];
  39245. }
  39246. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39247. }
  39248. // Negate normal.z
  39249. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39250. if (tNormals != null && tNormals.length > 0) {
  39251. for (var i = 0; i < tNormals.length; i += 3) {
  39252. tNormals[i + 2] = -tNormals[i + 2];
  39253. }
  39254. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39255. }
  39256. };
  39257. // Cache
  39258. /** @hidden */
  39259. Geometry.prototype._resetPointsArrayCache = function () {
  39260. this._positions = null;
  39261. };
  39262. /** @hidden */
  39263. Geometry.prototype._generatePointsArray = function () {
  39264. if (this._positions)
  39265. return true;
  39266. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39267. if (!data || data.length === 0) {
  39268. return false;
  39269. }
  39270. this._positions = [];
  39271. for (var index = 0; index < data.length; index += 3) {
  39272. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39273. }
  39274. return true;
  39275. };
  39276. /**
  39277. * Gets a value indicating if the geometry is disposed
  39278. * @returns true if the geometry was disposed
  39279. */
  39280. Geometry.prototype.isDisposed = function () {
  39281. return this._isDisposed;
  39282. };
  39283. Geometry.prototype._disposeVertexArrayObjects = function () {
  39284. if (this._vertexArrayObjects) {
  39285. for (var kind in this._vertexArrayObjects) {
  39286. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39287. }
  39288. this._vertexArrayObjects = {};
  39289. }
  39290. };
  39291. /**
  39292. * Free all associated resources
  39293. */
  39294. Geometry.prototype.dispose = function () {
  39295. var meshes = this._meshes;
  39296. var numOfMeshes = meshes.length;
  39297. var index;
  39298. for (index = 0; index < numOfMeshes; index++) {
  39299. this.releaseForMesh(meshes[index]);
  39300. }
  39301. this._meshes = [];
  39302. this._disposeVertexArrayObjects();
  39303. for (var kind in this._vertexBuffers) {
  39304. this._vertexBuffers[kind].dispose();
  39305. }
  39306. this._vertexBuffers = {};
  39307. this._totalVertices = 0;
  39308. if (this._indexBuffer) {
  39309. this._engine._releaseBuffer(this._indexBuffer);
  39310. }
  39311. this._indexBuffer = null;
  39312. this._indices = [];
  39313. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39314. this.delayLoadingFile = null;
  39315. this._delayLoadingFunction = null;
  39316. this._delayInfo = [];
  39317. this._boundingInfo = null;
  39318. this._scene.removeGeometry(this);
  39319. this._isDisposed = true;
  39320. };
  39321. /**
  39322. * Clone the current geometry into a new geometry
  39323. * @param id defines the unique ID of the new geometry
  39324. * @returns a new geometry object
  39325. */
  39326. Geometry.prototype.copy = function (id) {
  39327. var vertexData = new BABYLON.VertexData();
  39328. vertexData.indices = [];
  39329. var indices = this.getIndices();
  39330. if (indices) {
  39331. for (var index = 0; index < indices.length; index++) {
  39332. vertexData.indices.push(indices[index]);
  39333. }
  39334. }
  39335. var updatable = false;
  39336. var stopChecking = false;
  39337. var kind;
  39338. for (kind in this._vertexBuffers) {
  39339. // using slice() to make a copy of the array and not just reference it
  39340. var data = this.getVerticesData(kind);
  39341. if (data instanceof Float32Array) {
  39342. vertexData.set(new Float32Array(data), kind);
  39343. }
  39344. else {
  39345. vertexData.set(data.slice(0), kind);
  39346. }
  39347. if (!stopChecking) {
  39348. var vb = this.getVertexBuffer(kind);
  39349. if (vb) {
  39350. updatable = vb.isUpdatable();
  39351. stopChecking = !updatable;
  39352. }
  39353. }
  39354. }
  39355. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39356. geometry.delayLoadState = this.delayLoadState;
  39357. geometry.delayLoadingFile = this.delayLoadingFile;
  39358. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39359. for (kind in this._delayInfo) {
  39360. geometry._delayInfo = geometry._delayInfo || [];
  39361. geometry._delayInfo.push(kind);
  39362. }
  39363. // Bounding info
  39364. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39365. return geometry;
  39366. };
  39367. /**
  39368. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39369. * @return a JSON representation of the current geometry data (without the vertices data)
  39370. */
  39371. Geometry.prototype.serialize = function () {
  39372. var serializationObject = {};
  39373. serializationObject.id = this.id;
  39374. serializationObject.updatable = this._updatable;
  39375. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39376. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39377. }
  39378. return serializationObject;
  39379. };
  39380. Geometry.prototype.toNumberArray = function (origin) {
  39381. if (Array.isArray(origin)) {
  39382. return origin;
  39383. }
  39384. else {
  39385. return Array.prototype.slice.call(origin);
  39386. }
  39387. };
  39388. /**
  39389. * Serialize all vertices data into a JSON oject
  39390. * @returns a JSON representation of the current geometry data
  39391. */
  39392. Geometry.prototype.serializeVerticeData = function () {
  39393. var serializationObject = this.serialize();
  39394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39395. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39396. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39397. serializationObject.positions._updatable = true;
  39398. }
  39399. }
  39400. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39401. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39402. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39403. serializationObject.normals._updatable = true;
  39404. }
  39405. }
  39406. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39407. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39408. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39409. serializationObject.tangets._updatable = true;
  39410. }
  39411. }
  39412. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39413. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39414. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39415. serializationObject.uvs._updatable = true;
  39416. }
  39417. }
  39418. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39419. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39420. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39421. serializationObject.uv2s._updatable = true;
  39422. }
  39423. }
  39424. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39425. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39426. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39427. serializationObject.uv3s._updatable = true;
  39428. }
  39429. }
  39430. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39431. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39432. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39433. serializationObject.uv4s._updatable = true;
  39434. }
  39435. }
  39436. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39437. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39438. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39439. serializationObject.uv5s._updatable = true;
  39440. }
  39441. }
  39442. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39443. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39444. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39445. serializationObject.uv6s._updatable = true;
  39446. }
  39447. }
  39448. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39449. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39450. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39451. serializationObject.colors._updatable = true;
  39452. }
  39453. }
  39454. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39455. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39456. serializationObject.matricesIndices._isExpanded = true;
  39457. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39458. serializationObject.matricesIndices._updatable = true;
  39459. }
  39460. }
  39461. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39462. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39463. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39464. serializationObject.matricesWeights._updatable = true;
  39465. }
  39466. }
  39467. serializationObject.indices = this.toNumberArray(this.getIndices());
  39468. return serializationObject;
  39469. };
  39470. // Statics
  39471. /**
  39472. * Extracts a clone of a mesh geometry
  39473. * @param mesh defines the source mesh
  39474. * @param id defines the unique ID of the new geometry object
  39475. * @returns the new geometry object
  39476. */
  39477. Geometry.ExtractFromMesh = function (mesh, id) {
  39478. var geometry = mesh._geometry;
  39479. if (!geometry) {
  39480. return null;
  39481. }
  39482. return geometry.copy(id);
  39483. };
  39484. /**
  39485. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39486. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39487. * Be aware Math.random() could cause collisions, but:
  39488. * "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"
  39489. * @returns a string containing a new GUID
  39490. */
  39491. Geometry.RandomId = function () {
  39492. return BABYLON.Tools.RandomId();
  39493. };
  39494. /** @hidden */
  39495. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39496. var scene = mesh.getScene();
  39497. // Geometry
  39498. var geometryId = parsedGeometry.geometryId;
  39499. if (geometryId) {
  39500. var geometry = scene.getGeometryByID(geometryId);
  39501. if (geometry) {
  39502. geometry.applyToMesh(mesh);
  39503. }
  39504. }
  39505. else if (parsedGeometry instanceof ArrayBuffer) {
  39506. var binaryInfo = mesh._binaryInfo;
  39507. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39508. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39509. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39510. }
  39511. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39512. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39513. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39514. }
  39515. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39516. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39517. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39518. }
  39519. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39520. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39521. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39522. }
  39523. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39524. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39525. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39526. }
  39527. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39528. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39529. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39530. }
  39531. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39532. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39533. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39534. }
  39535. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39536. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39537. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39538. }
  39539. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39540. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39541. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39542. }
  39543. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39544. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39545. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39546. }
  39547. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39548. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39549. var floatIndices = [];
  39550. for (var i = 0; i < matricesIndicesData.length; i++) {
  39551. var index = matricesIndicesData[i];
  39552. floatIndices.push(index & 0x000000FF);
  39553. floatIndices.push((index & 0x0000FF00) >> 8);
  39554. floatIndices.push((index & 0x00FF0000) >> 16);
  39555. floatIndices.push(index >> 24);
  39556. }
  39557. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39558. }
  39559. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39560. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39561. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39562. }
  39563. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39564. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39565. mesh.setIndices(indicesData, null);
  39566. }
  39567. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39568. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39569. mesh.subMeshes = [];
  39570. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39571. var materialIndex = subMeshesData[(i * 5) + 0];
  39572. var verticesStart = subMeshesData[(i * 5) + 1];
  39573. var verticesCount = subMeshesData[(i * 5) + 2];
  39574. var indexStart = subMeshesData[(i * 5) + 3];
  39575. var indexCount = subMeshesData[(i * 5) + 4];
  39576. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39577. }
  39578. }
  39579. }
  39580. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39581. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39582. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39583. if (parsedGeometry.tangents) {
  39584. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39585. }
  39586. if (parsedGeometry.uvs) {
  39587. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39588. }
  39589. if (parsedGeometry.uvs2) {
  39590. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39591. }
  39592. if (parsedGeometry.uvs3) {
  39593. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39594. }
  39595. if (parsedGeometry.uvs4) {
  39596. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39597. }
  39598. if (parsedGeometry.uvs5) {
  39599. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39600. }
  39601. if (parsedGeometry.uvs6) {
  39602. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39603. }
  39604. if (parsedGeometry.colors) {
  39605. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39606. }
  39607. if (parsedGeometry.matricesIndices) {
  39608. if (!parsedGeometry.matricesIndices._isExpanded) {
  39609. var floatIndices = [];
  39610. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39611. var matricesIndex = parsedGeometry.matricesIndices[i];
  39612. floatIndices.push(matricesIndex & 0x000000FF);
  39613. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39614. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39615. floatIndices.push(matricesIndex >> 24);
  39616. }
  39617. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39618. }
  39619. else {
  39620. delete parsedGeometry.matricesIndices._isExpanded;
  39621. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39622. }
  39623. }
  39624. if (parsedGeometry.matricesIndicesExtra) {
  39625. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39626. var floatIndices = [];
  39627. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39628. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39629. floatIndices.push(matricesIndex & 0x000000FF);
  39630. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39631. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39632. floatIndices.push(matricesIndex >> 24);
  39633. }
  39634. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39635. }
  39636. else {
  39637. delete parsedGeometry.matricesIndices._isExpanded;
  39638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39639. }
  39640. }
  39641. if (parsedGeometry.matricesWeights) {
  39642. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39643. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39644. }
  39645. if (parsedGeometry.matricesWeightsExtra) {
  39646. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39647. }
  39648. mesh.setIndices(parsedGeometry.indices, null);
  39649. }
  39650. // SubMeshes
  39651. if (parsedGeometry.subMeshes) {
  39652. mesh.subMeshes = [];
  39653. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39654. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39655. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39656. }
  39657. }
  39658. // Flat shading
  39659. if (mesh._shouldGenerateFlatShading) {
  39660. mesh.convertToFlatShadedMesh();
  39661. delete mesh._shouldGenerateFlatShading;
  39662. }
  39663. // Update
  39664. mesh.computeWorldMatrix(true);
  39665. scene.onMeshImportedObservable.notifyObservers(mesh);
  39666. };
  39667. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39668. var epsilon = 1e-3;
  39669. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39670. return;
  39671. }
  39672. var noInfluenceBoneIndex = 0.0;
  39673. if (parsedGeometry.skeletonId > -1) {
  39674. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39675. if (!skeleton) {
  39676. return;
  39677. }
  39678. noInfluenceBoneIndex = skeleton.bones.length;
  39679. }
  39680. else {
  39681. return;
  39682. }
  39683. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39684. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39685. var matricesWeights = parsedGeometry.matricesWeights;
  39686. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39687. var influencers = parsedGeometry.numBoneInfluencer;
  39688. var size = matricesWeights.length;
  39689. for (var i = 0; i < size; i += 4) {
  39690. var weight = 0.0;
  39691. var firstZeroWeight = -1;
  39692. for (var j = 0; j < 4; j++) {
  39693. var w = matricesWeights[i + j];
  39694. weight += w;
  39695. if (w < epsilon && firstZeroWeight < 0) {
  39696. firstZeroWeight = j;
  39697. }
  39698. }
  39699. if (matricesWeightsExtra) {
  39700. for (var j = 0; j < 4; j++) {
  39701. var w = matricesWeightsExtra[i + j];
  39702. weight += w;
  39703. if (w < epsilon && firstZeroWeight < 0) {
  39704. firstZeroWeight = j + 4;
  39705. }
  39706. }
  39707. }
  39708. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39709. firstZeroWeight = influencers - 1;
  39710. }
  39711. if (weight > epsilon) {
  39712. var mweight = 1.0 / weight;
  39713. for (var j = 0; j < 4; j++) {
  39714. matricesWeights[i + j] *= mweight;
  39715. }
  39716. if (matricesWeightsExtra) {
  39717. for (var j = 0; j < 4; j++) {
  39718. matricesWeightsExtra[i + j] *= mweight;
  39719. }
  39720. }
  39721. }
  39722. else {
  39723. if (firstZeroWeight >= 4) {
  39724. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39725. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39726. }
  39727. else {
  39728. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39729. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39730. }
  39731. }
  39732. }
  39733. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39734. if (parsedGeometry.matricesWeightsExtra) {
  39735. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39736. }
  39737. };
  39738. /**
  39739. * Create a new geometry from persisted data (Using .babylon file format)
  39740. * @param parsedVertexData defines the persisted data
  39741. * @param scene defines the hosting scene
  39742. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39743. * @returns the new geometry object
  39744. */
  39745. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39746. if (scene.getGeometryByID(parsedVertexData.id)) {
  39747. return null; // null since geometry could be something else than a box...
  39748. }
  39749. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39750. if (BABYLON.Tags) {
  39751. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39752. }
  39753. if (parsedVertexData.delayLoadingFile) {
  39754. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39755. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39756. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39757. geometry._delayInfo = [];
  39758. if (parsedVertexData.hasUVs) {
  39759. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39760. }
  39761. if (parsedVertexData.hasUVs2) {
  39762. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39763. }
  39764. if (parsedVertexData.hasUVs3) {
  39765. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39766. }
  39767. if (parsedVertexData.hasUVs4) {
  39768. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39769. }
  39770. if (parsedVertexData.hasUVs5) {
  39771. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39772. }
  39773. if (parsedVertexData.hasUVs6) {
  39774. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39775. }
  39776. if (parsedVertexData.hasColors) {
  39777. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39778. }
  39779. if (parsedVertexData.hasMatricesIndices) {
  39780. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39781. }
  39782. if (parsedVertexData.hasMatricesWeights) {
  39783. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39784. }
  39785. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39786. }
  39787. else {
  39788. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39789. }
  39790. scene.pushGeometry(geometry, true);
  39791. return geometry;
  39792. };
  39793. return Geometry;
  39794. }());
  39795. BABYLON.Geometry = Geometry;
  39796. // Primitives
  39797. /// Abstract class
  39798. /**
  39799. * Abstract class used to provide common services for all typed geometries
  39800. * @hidden
  39801. */
  39802. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39803. __extends(_PrimitiveGeometry, _super);
  39804. /**
  39805. * Creates a new typed geometry
  39806. * @param id defines the unique ID of the geometry
  39807. * @param scene defines the hosting scene
  39808. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39809. * @param mesh defines the hosting mesh (can be null)
  39810. */
  39811. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39812. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39813. if (mesh === void 0) { mesh = null; }
  39814. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39815. _this._canBeRegenerated = _canBeRegenerated;
  39816. _this._beingRegenerated = true;
  39817. _this.regenerate();
  39818. _this._beingRegenerated = false;
  39819. return _this;
  39820. }
  39821. /**
  39822. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39823. * @returns true if the geometry can be regenerated
  39824. */
  39825. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39826. return this._canBeRegenerated;
  39827. };
  39828. /**
  39829. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39830. */
  39831. _PrimitiveGeometry.prototype.regenerate = function () {
  39832. if (!this._canBeRegenerated) {
  39833. return;
  39834. }
  39835. this._beingRegenerated = true;
  39836. this.setAllVerticesData(this._regenerateVertexData(), false);
  39837. this._beingRegenerated = false;
  39838. };
  39839. /**
  39840. * Clone the geometry
  39841. * @param id defines the unique ID of the new geometry
  39842. * @returns the new geometry
  39843. */
  39844. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39845. return _super.prototype.copy.call(this, id);
  39846. };
  39847. // overrides
  39848. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39849. if (!this._beingRegenerated) {
  39850. return;
  39851. }
  39852. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39853. };
  39854. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39855. if (!this._beingRegenerated) {
  39856. return;
  39857. }
  39858. _super.prototype.setVerticesData.call(this, kind, data, false);
  39859. };
  39860. // to override
  39861. /** @hidden */
  39862. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39863. throw new Error("Abstract method");
  39864. };
  39865. _PrimitiveGeometry.prototype.copy = function (id) {
  39866. throw new Error("Must be overriden in sub-classes.");
  39867. };
  39868. _PrimitiveGeometry.prototype.serialize = function () {
  39869. var serializationObject = _super.prototype.serialize.call(this);
  39870. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39871. return serializationObject;
  39872. };
  39873. return _PrimitiveGeometry;
  39874. }(Geometry));
  39875. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39876. /**
  39877. * Creates a ribbon geometry
  39878. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39879. */
  39880. var RibbonGeometry = /** @class */ (function (_super) {
  39881. __extends(RibbonGeometry, _super);
  39882. /**
  39883. * Creates a ribbon geometry
  39884. * @param id defines the unique ID of the geometry
  39885. * @param scene defines the hosting scene
  39886. * @param pathArray defines the array of paths to use
  39887. * @param closeArray defines if the last path and the first path must be joined
  39888. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39889. * @param offset defines the offset between points
  39890. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39891. * @param mesh defines the hosting mesh (can be null)
  39892. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39893. */
  39894. function RibbonGeometry(id, scene,
  39895. /**
  39896. * Defines the array of paths to use
  39897. */
  39898. pathArray,
  39899. /**
  39900. * Defines if the last and first points of each path in your pathArray must be joined
  39901. */
  39902. closeArray,
  39903. /**
  39904. * Defines if the last and first points of each path in your pathArray must be joined
  39905. */
  39906. closePath,
  39907. /**
  39908. * Defines the offset between points
  39909. */
  39910. offset, canBeRegenerated, mesh,
  39911. /**
  39912. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39913. */
  39914. side) {
  39915. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39916. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39917. _this.pathArray = pathArray;
  39918. _this.closeArray = closeArray;
  39919. _this.closePath = closePath;
  39920. _this.offset = offset;
  39921. _this.side = side;
  39922. return _this;
  39923. }
  39924. /** @hidden */
  39925. RibbonGeometry.prototype._regenerateVertexData = function () {
  39926. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39927. };
  39928. RibbonGeometry.prototype.copy = function (id) {
  39929. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39930. };
  39931. return RibbonGeometry;
  39932. }(_PrimitiveGeometry));
  39933. BABYLON.RibbonGeometry = RibbonGeometry;
  39934. /**
  39935. * Creates a box geometry
  39936. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39937. */
  39938. var BoxGeometry = /** @class */ (function (_super) {
  39939. __extends(BoxGeometry, _super);
  39940. /**
  39941. * Creates a box geometry
  39942. * @param id defines the unique ID of the geometry
  39943. * @param scene defines the hosting scene
  39944. * @param size defines the zise of the box (width, height and depth are the same)
  39945. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39946. * @param mesh defines the hosting mesh (can be null)
  39947. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39948. */
  39949. function BoxGeometry(id, scene,
  39950. /**
  39951. * Defines the zise of the box (width, height and depth are the same)
  39952. */
  39953. size, canBeRegenerated, mesh,
  39954. /**
  39955. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39956. */
  39957. side) {
  39958. if (mesh === void 0) { mesh = null; }
  39959. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39960. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39961. _this.size = size;
  39962. _this.side = side;
  39963. return _this;
  39964. }
  39965. /** @hidden */
  39966. BoxGeometry.prototype._regenerateVertexData = function () {
  39967. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39968. };
  39969. BoxGeometry.prototype.copy = function (id) {
  39970. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39971. };
  39972. BoxGeometry.prototype.serialize = function () {
  39973. var serializationObject = _super.prototype.serialize.call(this);
  39974. serializationObject.size = this.size;
  39975. return serializationObject;
  39976. };
  39977. BoxGeometry.Parse = function (parsedBox, scene) {
  39978. if (scene.getGeometryByID(parsedBox.id)) {
  39979. return null; // null since geometry could be something else than a box...
  39980. }
  39981. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39982. if (BABYLON.Tags) {
  39983. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39984. }
  39985. scene.pushGeometry(box, true);
  39986. return box;
  39987. };
  39988. return BoxGeometry;
  39989. }(_PrimitiveGeometry));
  39990. BABYLON.BoxGeometry = BoxGeometry;
  39991. /**
  39992. * Creates a sphere geometry
  39993. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39994. */
  39995. var SphereGeometry = /** @class */ (function (_super) {
  39996. __extends(SphereGeometry, _super);
  39997. /**
  39998. * Create a new sphere geometry
  39999. * @param id defines the unique ID of the geometry
  40000. * @param scene defines the hosting scene
  40001. * @param segments defines the number of segments to use to create the sphere
  40002. * @param diameter defines the diameter of the sphere
  40003. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40004. * @param mesh defines the hosting mesh (can be null)
  40005. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40006. */
  40007. function SphereGeometry(id, scene,
  40008. /**
  40009. * Defines the number of segments to use to create the sphere
  40010. */
  40011. segments,
  40012. /**
  40013. * Defines the diameter of the sphere
  40014. */
  40015. diameter, canBeRegenerated, mesh,
  40016. /**
  40017. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40018. */
  40019. side) {
  40020. if (mesh === void 0) { mesh = null; }
  40021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40022. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40023. _this.segments = segments;
  40024. _this.diameter = diameter;
  40025. _this.side = side;
  40026. return _this;
  40027. }
  40028. /** @hidden */
  40029. SphereGeometry.prototype._regenerateVertexData = function () {
  40030. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40031. };
  40032. SphereGeometry.prototype.copy = function (id) {
  40033. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40034. };
  40035. SphereGeometry.prototype.serialize = function () {
  40036. var serializationObject = _super.prototype.serialize.call(this);
  40037. serializationObject.segments = this.segments;
  40038. serializationObject.diameter = this.diameter;
  40039. return serializationObject;
  40040. };
  40041. SphereGeometry.Parse = function (parsedSphere, scene) {
  40042. if (scene.getGeometryByID(parsedSphere.id)) {
  40043. return null; // null since geometry could be something else than a sphere...
  40044. }
  40045. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40046. if (BABYLON.Tags) {
  40047. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40048. }
  40049. scene.pushGeometry(sphere, true);
  40050. return sphere;
  40051. };
  40052. return SphereGeometry;
  40053. }(_PrimitiveGeometry));
  40054. BABYLON.SphereGeometry = SphereGeometry;
  40055. /**
  40056. * Creates a disc geometry
  40057. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40058. */
  40059. var DiscGeometry = /** @class */ (function (_super) {
  40060. __extends(DiscGeometry, _super);
  40061. /**
  40062. * Creates a new disc geometry
  40063. * @param id defines the unique ID of the geometry
  40064. * @param scene defines the hosting scene
  40065. * @param radius defines the radius of the disc
  40066. * @param tessellation defines the tesselation factor to apply to the disc
  40067. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40068. * @param mesh defines the hosting mesh (can be null)
  40069. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40070. */
  40071. function DiscGeometry(id, scene,
  40072. /**
  40073. * Defines the radius of the disc
  40074. */
  40075. radius,
  40076. /**
  40077. * Defines the tesselation factor to apply to the disc
  40078. */
  40079. tessellation, canBeRegenerated, mesh,
  40080. /**
  40081. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40082. */
  40083. side) {
  40084. if (mesh === void 0) { mesh = null; }
  40085. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40086. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40087. _this.radius = radius;
  40088. _this.tessellation = tessellation;
  40089. _this.side = side;
  40090. return _this;
  40091. }
  40092. /** @hidden */
  40093. DiscGeometry.prototype._regenerateVertexData = function () {
  40094. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40095. };
  40096. DiscGeometry.prototype.copy = function (id) {
  40097. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40098. };
  40099. return DiscGeometry;
  40100. }(_PrimitiveGeometry));
  40101. BABYLON.DiscGeometry = DiscGeometry;
  40102. /**
  40103. * Creates a new cylinder geometry
  40104. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40105. */
  40106. var CylinderGeometry = /** @class */ (function (_super) {
  40107. __extends(CylinderGeometry, _super);
  40108. /**
  40109. * Creates a new cylinder geometry
  40110. * @param id defines the unique ID of the geometry
  40111. * @param scene defines the hosting scene
  40112. * @param height defines the height of the cylinder
  40113. * @param diameterTop defines the diameter of the cylinder's top cap
  40114. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40115. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40116. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40117. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40118. * @param mesh defines the hosting mesh (can be null)
  40119. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40120. */
  40121. function CylinderGeometry(id, scene,
  40122. /**
  40123. * Defines the height of the cylinder
  40124. */
  40125. height,
  40126. /**
  40127. * Defines the diameter of the cylinder's top cap
  40128. */
  40129. diameterTop,
  40130. /**
  40131. * Defines the diameter of the cylinder's bottom cap
  40132. */
  40133. diameterBottom,
  40134. /**
  40135. * Defines the tessellation factor to apply to the cylinder
  40136. */
  40137. tessellation,
  40138. /**
  40139. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40140. */
  40141. subdivisions, canBeRegenerated, mesh,
  40142. /**
  40143. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40144. */
  40145. side) {
  40146. if (subdivisions === void 0) { subdivisions = 1; }
  40147. if (mesh === void 0) { mesh = null; }
  40148. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40149. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40150. _this.height = height;
  40151. _this.diameterTop = diameterTop;
  40152. _this.diameterBottom = diameterBottom;
  40153. _this.tessellation = tessellation;
  40154. _this.subdivisions = subdivisions;
  40155. _this.side = side;
  40156. return _this;
  40157. }
  40158. /** @hidden */
  40159. CylinderGeometry.prototype._regenerateVertexData = function () {
  40160. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40161. };
  40162. CylinderGeometry.prototype.copy = function (id) {
  40163. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40164. };
  40165. CylinderGeometry.prototype.serialize = function () {
  40166. var serializationObject = _super.prototype.serialize.call(this);
  40167. serializationObject.height = this.height;
  40168. serializationObject.diameterTop = this.diameterTop;
  40169. serializationObject.diameterBottom = this.diameterBottom;
  40170. serializationObject.tessellation = this.tessellation;
  40171. return serializationObject;
  40172. };
  40173. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40174. if (scene.getGeometryByID(parsedCylinder.id)) {
  40175. return null; // null since geometry could be something else than a cylinder...
  40176. }
  40177. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40178. if (BABYLON.Tags) {
  40179. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40180. }
  40181. scene.pushGeometry(cylinder, true);
  40182. return cylinder;
  40183. };
  40184. return CylinderGeometry;
  40185. }(_PrimitiveGeometry));
  40186. BABYLON.CylinderGeometry = CylinderGeometry;
  40187. /**
  40188. * Creates a new torus geometry
  40189. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40190. */
  40191. var TorusGeometry = /** @class */ (function (_super) {
  40192. __extends(TorusGeometry, _super);
  40193. /**
  40194. * Creates a new torus geometry
  40195. * @param id defines the unique ID of the geometry
  40196. * @param scene defines the hosting scene
  40197. * @param diameter defines the diameter of the torus
  40198. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40199. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40200. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40201. * @param mesh defines the hosting mesh (can be null)
  40202. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40203. */
  40204. function TorusGeometry(id, scene,
  40205. /**
  40206. * Defines the diameter of the torus
  40207. */
  40208. diameter,
  40209. /**
  40210. * Defines the thickness of the torus (ie. internal diameter)
  40211. */
  40212. thickness,
  40213. /**
  40214. * Defines the tesselation factor to apply to the torus
  40215. */
  40216. tessellation, canBeRegenerated, mesh,
  40217. /**
  40218. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40219. */
  40220. side) {
  40221. if (mesh === void 0) { mesh = null; }
  40222. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40223. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40224. _this.diameter = diameter;
  40225. _this.thickness = thickness;
  40226. _this.tessellation = tessellation;
  40227. _this.side = side;
  40228. return _this;
  40229. }
  40230. /** @hidden */
  40231. TorusGeometry.prototype._regenerateVertexData = function () {
  40232. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40233. };
  40234. TorusGeometry.prototype.copy = function (id) {
  40235. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40236. };
  40237. TorusGeometry.prototype.serialize = function () {
  40238. var serializationObject = _super.prototype.serialize.call(this);
  40239. serializationObject.diameter = this.diameter;
  40240. serializationObject.thickness = this.thickness;
  40241. serializationObject.tessellation = this.tessellation;
  40242. return serializationObject;
  40243. };
  40244. TorusGeometry.Parse = function (parsedTorus, scene) {
  40245. if (scene.getGeometryByID(parsedTorus.id)) {
  40246. return null; // null since geometry could be something else than a torus...
  40247. }
  40248. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40249. if (BABYLON.Tags) {
  40250. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40251. }
  40252. scene.pushGeometry(torus, true);
  40253. return torus;
  40254. };
  40255. return TorusGeometry;
  40256. }(_PrimitiveGeometry));
  40257. BABYLON.TorusGeometry = TorusGeometry;
  40258. /**
  40259. * Creates a new ground geometry
  40260. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40261. */
  40262. var GroundGeometry = /** @class */ (function (_super) {
  40263. __extends(GroundGeometry, _super);
  40264. /**
  40265. * Creates a new ground geometry
  40266. * @param id defines the unique ID of the geometry
  40267. * @param scene defines the hosting scene
  40268. * @param width defines the width of the ground
  40269. * @param height defines the height of the ground
  40270. * @param subdivisions defines the subdivisions to apply to the ground
  40271. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40272. * @param mesh defines the hosting mesh (can be null)
  40273. */
  40274. function GroundGeometry(id, scene,
  40275. /**
  40276. * Defines the width of the ground
  40277. */
  40278. width,
  40279. /**
  40280. * Defines the height of the ground
  40281. */
  40282. height,
  40283. /**
  40284. * Defines the subdivisions to apply to the ground
  40285. */
  40286. subdivisions, canBeRegenerated, mesh) {
  40287. if (mesh === void 0) { mesh = null; }
  40288. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40289. _this.width = width;
  40290. _this.height = height;
  40291. _this.subdivisions = subdivisions;
  40292. return _this;
  40293. }
  40294. /** @hidden */
  40295. GroundGeometry.prototype._regenerateVertexData = function () {
  40296. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40297. };
  40298. GroundGeometry.prototype.copy = function (id) {
  40299. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40300. };
  40301. GroundGeometry.prototype.serialize = function () {
  40302. var serializationObject = _super.prototype.serialize.call(this);
  40303. serializationObject.width = this.width;
  40304. serializationObject.height = this.height;
  40305. serializationObject.subdivisions = this.subdivisions;
  40306. return serializationObject;
  40307. };
  40308. GroundGeometry.Parse = function (parsedGround, scene) {
  40309. if (scene.getGeometryByID(parsedGround.id)) {
  40310. return null; // null since geometry could be something else than a ground...
  40311. }
  40312. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40313. if (BABYLON.Tags) {
  40314. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40315. }
  40316. scene.pushGeometry(ground, true);
  40317. return ground;
  40318. };
  40319. return GroundGeometry;
  40320. }(_PrimitiveGeometry));
  40321. BABYLON.GroundGeometry = GroundGeometry;
  40322. /**
  40323. * Creates a tiled ground geometry
  40324. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40325. */
  40326. var TiledGroundGeometry = /** @class */ (function (_super) {
  40327. __extends(TiledGroundGeometry, _super);
  40328. /**
  40329. * Creates a tiled ground geometry
  40330. * @param id defines the unique ID of the geometry
  40331. * @param scene defines the hosting scene
  40332. * @param xmin defines the minimum value on X axis
  40333. * @param zmin defines the minimum value on Z axis
  40334. * @param xmax defines the maximum value on X axis
  40335. * @param zmax defines the maximum value on Z axis
  40336. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40337. * @param precision defines the precision to use when computing the tiles
  40338. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40339. * @param mesh defines the hosting mesh (can be null)
  40340. */
  40341. function TiledGroundGeometry(id, scene,
  40342. /**
  40343. * Defines the minimum value on X axis
  40344. */
  40345. xmin,
  40346. /**
  40347. * Defines the minimum value on Z axis
  40348. */
  40349. zmin,
  40350. /**
  40351. * Defines the maximum value on X axis
  40352. */
  40353. xmax,
  40354. /**
  40355. * Defines the maximum value on Z axis
  40356. */
  40357. zmax,
  40358. /**
  40359. * Defines the subdivisions to apply to the ground
  40360. */
  40361. subdivisions,
  40362. /**
  40363. * Defines the precision to use when computing the tiles
  40364. */
  40365. precision, canBeRegenerated, mesh) {
  40366. if (mesh === void 0) { mesh = null; }
  40367. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40368. _this.xmin = xmin;
  40369. _this.zmin = zmin;
  40370. _this.xmax = xmax;
  40371. _this.zmax = zmax;
  40372. _this.subdivisions = subdivisions;
  40373. _this.precision = precision;
  40374. return _this;
  40375. }
  40376. /** @hidden */
  40377. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40378. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40379. };
  40380. TiledGroundGeometry.prototype.copy = function (id) {
  40381. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40382. };
  40383. return TiledGroundGeometry;
  40384. }(_PrimitiveGeometry));
  40385. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40386. /**
  40387. * Creates a plane geometry
  40388. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40389. */
  40390. var PlaneGeometry = /** @class */ (function (_super) {
  40391. __extends(PlaneGeometry, _super);
  40392. /**
  40393. * Creates a plane geometry
  40394. * @param id defines the unique ID of the geometry
  40395. * @param scene defines the hosting scene
  40396. * @param size defines the size of the plane (width === height)
  40397. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40398. * @param mesh defines the hosting mesh (can be null)
  40399. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40400. */
  40401. function PlaneGeometry(id, scene,
  40402. /**
  40403. * Defines the size of the plane (width === height)
  40404. */
  40405. size, canBeRegenerated, mesh,
  40406. /**
  40407. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40408. */
  40409. side) {
  40410. if (mesh === void 0) { mesh = null; }
  40411. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40412. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40413. _this.size = size;
  40414. _this.side = side;
  40415. return _this;
  40416. }
  40417. /** @hidden */
  40418. PlaneGeometry.prototype._regenerateVertexData = function () {
  40419. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40420. };
  40421. PlaneGeometry.prototype.copy = function (id) {
  40422. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40423. };
  40424. PlaneGeometry.prototype.serialize = function () {
  40425. var serializationObject = _super.prototype.serialize.call(this);
  40426. serializationObject.size = this.size;
  40427. return serializationObject;
  40428. };
  40429. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40430. if (scene.getGeometryByID(parsedPlane.id)) {
  40431. return null; // null since geometry could be something else than a ground...
  40432. }
  40433. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40434. if (BABYLON.Tags) {
  40435. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40436. }
  40437. scene.pushGeometry(plane, true);
  40438. return plane;
  40439. };
  40440. return PlaneGeometry;
  40441. }(_PrimitiveGeometry));
  40442. BABYLON.PlaneGeometry = PlaneGeometry;
  40443. /**
  40444. * Creates a torus knot geometry
  40445. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40446. */
  40447. var TorusKnotGeometry = /** @class */ (function (_super) {
  40448. __extends(TorusKnotGeometry, _super);
  40449. /**
  40450. * Creates a torus knot geometry
  40451. * @param id defines the unique ID of the geometry
  40452. * @param scene defines the hosting scene
  40453. * @param radius defines the radius of the torus knot
  40454. * @param tube defines the thickness of the torus knot tube
  40455. * @param radialSegments defines the number of radial segments
  40456. * @param tubularSegments defines the number of tubular segments
  40457. * @param p defines the first number of windings
  40458. * @param q defines the second number of windings
  40459. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40460. * @param mesh defines the hosting mesh (can be null)
  40461. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40462. */
  40463. function TorusKnotGeometry(id, scene,
  40464. /**
  40465. * Defines the radius of the torus knot
  40466. */
  40467. radius,
  40468. /**
  40469. * Defines the thickness of the torus knot tube
  40470. */
  40471. tube,
  40472. /**
  40473. * Defines the number of radial segments
  40474. */
  40475. radialSegments,
  40476. /**
  40477. * Defines the number of tubular segments
  40478. */
  40479. tubularSegments,
  40480. /**
  40481. * Defines the first number of windings
  40482. */
  40483. p,
  40484. /**
  40485. * Defines the second number of windings
  40486. */
  40487. q, canBeRegenerated, mesh,
  40488. /**
  40489. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40490. */
  40491. side) {
  40492. if (mesh === void 0) { mesh = null; }
  40493. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40494. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40495. _this.radius = radius;
  40496. _this.tube = tube;
  40497. _this.radialSegments = radialSegments;
  40498. _this.tubularSegments = tubularSegments;
  40499. _this.p = p;
  40500. _this.q = q;
  40501. _this.side = side;
  40502. return _this;
  40503. }
  40504. /** @hidden */
  40505. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40506. 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 });
  40507. };
  40508. TorusKnotGeometry.prototype.copy = function (id) {
  40509. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40510. };
  40511. TorusKnotGeometry.prototype.serialize = function () {
  40512. var serializationObject = _super.prototype.serialize.call(this);
  40513. serializationObject.radius = this.radius;
  40514. serializationObject.tube = this.tube;
  40515. serializationObject.radialSegments = this.radialSegments;
  40516. serializationObject.tubularSegments = this.tubularSegments;
  40517. serializationObject.p = this.p;
  40518. serializationObject.q = this.q;
  40519. return serializationObject;
  40520. };
  40521. ;
  40522. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40523. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40524. return null; // null since geometry could be something else than a ground...
  40525. }
  40526. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40527. if (BABYLON.Tags) {
  40528. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40529. }
  40530. scene.pushGeometry(torusKnot, true);
  40531. return torusKnot;
  40532. };
  40533. return TorusKnotGeometry;
  40534. }(_PrimitiveGeometry));
  40535. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40536. //}
  40537. })(BABYLON || (BABYLON = {}));
  40538. //# sourceMappingURL=babylon.geometry.js.map
  40539. var BABYLON;
  40540. (function (BABYLON) {
  40541. /**
  40542. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40543. */
  40544. var PerformanceMonitor = /** @class */ (function () {
  40545. /**
  40546. * constructor
  40547. * @param frameSampleSize The number of samples required to saturate the sliding window
  40548. */
  40549. function PerformanceMonitor(frameSampleSize) {
  40550. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40551. this._enabled = true;
  40552. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40553. }
  40554. /**
  40555. * Samples current frame
  40556. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40557. */
  40558. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40559. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40560. if (!this._enabled)
  40561. return;
  40562. if (this._lastFrameTimeMs != null) {
  40563. var dt = timeMs - this._lastFrameTimeMs;
  40564. this._rollingFrameTime.add(dt);
  40565. }
  40566. this._lastFrameTimeMs = timeMs;
  40567. };
  40568. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40569. /**
  40570. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40571. * @return Average frame time in milliseconds
  40572. */
  40573. get: function () {
  40574. return this._rollingFrameTime.average;
  40575. },
  40576. enumerable: true,
  40577. configurable: true
  40578. });
  40579. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40580. /**
  40581. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40582. * @return Frame time variance in milliseconds squared
  40583. */
  40584. get: function () {
  40585. return this._rollingFrameTime.variance;
  40586. },
  40587. enumerable: true,
  40588. configurable: true
  40589. });
  40590. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40591. /**
  40592. * Returns the frame time of the most recent frame
  40593. * @return Frame time in milliseconds
  40594. */
  40595. get: function () {
  40596. return this._rollingFrameTime.history(0);
  40597. },
  40598. enumerable: true,
  40599. configurable: true
  40600. });
  40601. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40602. /**
  40603. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40604. * @return Framerate in frames per second
  40605. */
  40606. get: function () {
  40607. return 1000.0 / this._rollingFrameTime.average;
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40613. /**
  40614. * Returns the average framerate in frames per second using the most recent frame time
  40615. * @return Framerate in frames per second
  40616. */
  40617. get: function () {
  40618. var history = this._rollingFrameTime.history(0);
  40619. if (history === 0) {
  40620. return 0;
  40621. }
  40622. return 1000.0 / history;
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40628. /**
  40629. * Returns true if enough samples have been taken to completely fill the sliding window
  40630. * @return true if saturated
  40631. */
  40632. get: function () {
  40633. return this._rollingFrameTime.isSaturated();
  40634. },
  40635. enumerable: true,
  40636. configurable: true
  40637. });
  40638. /**
  40639. * Enables contributions to the sliding window sample set
  40640. */
  40641. PerformanceMonitor.prototype.enable = function () {
  40642. this._enabled = true;
  40643. };
  40644. /**
  40645. * Disables contributions to the sliding window sample set
  40646. * Samples will not be interpolated over the disabled period
  40647. */
  40648. PerformanceMonitor.prototype.disable = function () {
  40649. this._enabled = false;
  40650. //clear last sample to avoid interpolating over the disabled period when next enabled
  40651. this._lastFrameTimeMs = null;
  40652. };
  40653. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40654. /**
  40655. * Returns true if sampling is enabled
  40656. * @return true if enabled
  40657. */
  40658. get: function () {
  40659. return this._enabled;
  40660. },
  40661. enumerable: true,
  40662. configurable: true
  40663. });
  40664. /**
  40665. * Resets performance monitor
  40666. */
  40667. PerformanceMonitor.prototype.reset = function () {
  40668. //clear last sample to avoid interpolating over the disabled period when next enabled
  40669. this._lastFrameTimeMs = null;
  40670. //wipe record
  40671. this._rollingFrameTime.reset();
  40672. };
  40673. return PerformanceMonitor;
  40674. }());
  40675. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40676. /**
  40677. * RollingAverage
  40678. *
  40679. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40680. */
  40681. var RollingAverage = /** @class */ (function () {
  40682. /**
  40683. * constructor
  40684. * @param length The number of samples required to saturate the sliding window
  40685. */
  40686. function RollingAverage(length) {
  40687. this._samples = new Array(length);
  40688. this.reset();
  40689. }
  40690. /**
  40691. * Adds a sample to the sample set
  40692. * @param v The sample value
  40693. */
  40694. RollingAverage.prototype.add = function (v) {
  40695. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40696. var delta;
  40697. //we need to check if we've already wrapped round
  40698. if (this.isSaturated()) {
  40699. //remove bottom of stack from mean
  40700. var bottomValue = this._samples[this._pos];
  40701. delta = bottomValue - this.average;
  40702. this.average -= delta / (this._sampleCount - 1);
  40703. this._m2 -= delta * (bottomValue - this.average);
  40704. }
  40705. else {
  40706. this._sampleCount++;
  40707. }
  40708. //add new value to mean
  40709. delta = v - this.average;
  40710. this.average += delta / (this._sampleCount);
  40711. this._m2 += delta * (v - this.average);
  40712. //set the new variance
  40713. this.variance = this._m2 / (this._sampleCount - 1);
  40714. this._samples[this._pos] = v;
  40715. this._pos++;
  40716. this._pos %= this._samples.length; //positive wrap around
  40717. };
  40718. /**
  40719. * Returns previously added values or null if outside of history or outside the sliding window domain
  40720. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40721. * @return Value previously recorded with add() or null if outside of range
  40722. */
  40723. RollingAverage.prototype.history = function (i) {
  40724. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40725. return 0;
  40726. }
  40727. var i0 = this._wrapPosition(this._pos - 1.0);
  40728. return this._samples[this._wrapPosition(i0 - i)];
  40729. };
  40730. /**
  40731. * Returns true if enough samples have been taken to completely fill the sliding window
  40732. * @return true if sample-set saturated
  40733. */
  40734. RollingAverage.prototype.isSaturated = function () {
  40735. return this._sampleCount >= this._samples.length;
  40736. };
  40737. /**
  40738. * Resets the rolling average (equivalent to 0 samples taken so far)
  40739. */
  40740. RollingAverage.prototype.reset = function () {
  40741. this.average = 0;
  40742. this.variance = 0;
  40743. this._sampleCount = 0;
  40744. this._pos = 0;
  40745. this._m2 = 0;
  40746. };
  40747. /**
  40748. * Wraps a value around the sample range boundaries
  40749. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40750. * @return Wrapped position in sample range
  40751. */
  40752. RollingAverage.prototype._wrapPosition = function (i) {
  40753. var max = this._samples.length;
  40754. return ((i % max) + max) % max;
  40755. };
  40756. return RollingAverage;
  40757. }());
  40758. BABYLON.RollingAverage = RollingAverage;
  40759. })(BABYLON || (BABYLON = {}));
  40760. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40761. var BABYLON;
  40762. (function (BABYLON) {
  40763. /**
  40764. * "Static Class" containing the most commonly used helper while dealing with material for
  40765. * rendering purpose.
  40766. *
  40767. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40768. *
  40769. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40770. */
  40771. var MaterialHelper = /** @class */ (function () {
  40772. function MaterialHelper() {
  40773. }
  40774. /**
  40775. * Bind the current view position to an effect.
  40776. * @param effect The effect to be bound
  40777. * @param scene The scene the eyes position is used from
  40778. */
  40779. MaterialHelper.BindEyePosition = function (effect, scene) {
  40780. if (scene._forcedViewPosition) {
  40781. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40782. return;
  40783. }
  40784. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40785. };
  40786. /**
  40787. * Helps preparing the defines values about the UVs in used in the effect.
  40788. * UVs are shared as much as we can accross chanels in the shaders.
  40789. * @param texture The texture we are preparing the UVs for
  40790. * @param defines The defines to update
  40791. * @param key The chanel key "diffuse", "specular"... used in the shader
  40792. */
  40793. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40794. defines._needUVs = true;
  40795. defines[key] = true;
  40796. if (texture.getTextureMatrix().isIdentity(true)) {
  40797. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40798. if (texture.coordinatesIndex === 0) {
  40799. defines["MAINUV1"] = true;
  40800. }
  40801. else {
  40802. defines["MAINUV2"] = true;
  40803. }
  40804. }
  40805. else {
  40806. defines[key + "DIRECTUV"] = 0;
  40807. }
  40808. };
  40809. /**
  40810. * Binds a texture matrix value to its corrsponding uniform
  40811. * @param texture The texture to bind the matrix for
  40812. * @param uniformBuffer The uniform buffer receivin the data
  40813. * @param key The chanel key "diffuse", "specular"... used in the shader
  40814. */
  40815. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40816. var matrix = texture.getTextureMatrix();
  40817. if (!matrix.isIdentity(true)) {
  40818. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40819. }
  40820. };
  40821. /**
  40822. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40823. * @param mesh defines the current mesh
  40824. * @param scene defines the current scene
  40825. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40826. * @param pointsCloud defines if point cloud rendering has to be turned on
  40827. * @param fogEnabled defines if fog has to be turned on
  40828. * @param alphaTest defines if alpha testing has to be turned on
  40829. * @param defines defines the current list of defines
  40830. */
  40831. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40832. if (defines._areMiscDirty) {
  40833. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40834. defines["POINTSIZE"] = pointsCloud;
  40835. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40836. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40837. defines["ALPHATEST"] = alphaTest;
  40838. }
  40839. };
  40840. /**
  40841. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40842. * @param scene defines the current scene
  40843. * @param engine defines the current engine
  40844. * @param defines specifies the list of active defines
  40845. * @param useInstances defines if instances have to be turned on
  40846. * @param useClipPlane defines if clip plane have to be turned on
  40847. */
  40848. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40849. if (useClipPlane === void 0) { useClipPlane = null; }
  40850. var changed = false;
  40851. var useClipPlane1 = false;
  40852. var useClipPlane2 = false;
  40853. var useClipPlane3 = false;
  40854. var useClipPlane4 = false;
  40855. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40856. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40857. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40858. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40859. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40860. defines["CLIPPLANE"] = useClipPlane1;
  40861. changed = true;
  40862. }
  40863. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40864. defines["CLIPPLANE2"] = useClipPlane2;
  40865. changed = true;
  40866. }
  40867. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40868. defines["CLIPPLANE3"] = useClipPlane3;
  40869. changed = true;
  40870. }
  40871. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40872. defines["CLIPPLANE4"] = useClipPlane4;
  40873. changed = true;
  40874. }
  40875. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40876. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40877. changed = true;
  40878. }
  40879. if (defines["INSTANCES"] !== useInstances) {
  40880. defines["INSTANCES"] = useInstances;
  40881. changed = true;
  40882. }
  40883. if (changed) {
  40884. defines.markAsUnprocessed();
  40885. }
  40886. };
  40887. /**
  40888. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40889. * @param mesh The mesh containing the geometry data we will draw
  40890. * @param defines The defines to update
  40891. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40892. * @param useBones Precise whether bones should be used or not (override mesh info)
  40893. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40894. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40895. * @returns false if defines are considered not dirty and have not been checked
  40896. */
  40897. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40898. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40899. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40900. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40901. return false;
  40902. }
  40903. defines._normals = defines._needNormals;
  40904. defines._uvs = defines._needUVs;
  40905. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40906. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40907. defines["TANGENT"] = true;
  40908. }
  40909. if (defines._needUVs) {
  40910. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40911. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40912. }
  40913. else {
  40914. defines["UV1"] = false;
  40915. defines["UV2"] = false;
  40916. }
  40917. if (useVertexColor) {
  40918. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40919. defines["VERTEXCOLOR"] = hasVertexColors;
  40920. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40921. }
  40922. if (useBones) {
  40923. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40924. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40925. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40926. }
  40927. else {
  40928. defines["NUM_BONE_INFLUENCERS"] = 0;
  40929. defines["BonesPerMesh"] = 0;
  40930. }
  40931. }
  40932. if (useMorphTargets) {
  40933. var manager = mesh.morphTargetManager;
  40934. if (manager) {
  40935. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40936. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40937. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40938. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40939. }
  40940. else {
  40941. defines["MORPHTARGETS_TANGENT"] = false;
  40942. defines["MORPHTARGETS_NORMAL"] = false;
  40943. defines["MORPHTARGETS"] = false;
  40944. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40945. }
  40946. }
  40947. return true;
  40948. };
  40949. /**
  40950. * Prepares the defines related to the light information passed in parameter
  40951. * @param scene The scene we are intending to draw
  40952. * @param mesh The mesh the effect is compiling for
  40953. * @param defines The defines to update
  40954. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40955. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40956. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40957. * @returns true if normals will be required for the rest of the effect
  40958. */
  40959. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40960. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40961. if (disableLighting === void 0) { disableLighting = false; }
  40962. if (!defines._areLightsDirty) {
  40963. return defines._needNormals;
  40964. }
  40965. var lightIndex = 0;
  40966. var needNormals = false;
  40967. var needRebuild = false;
  40968. var lightmapMode = false;
  40969. var shadowEnabled = false;
  40970. var specularEnabled = false;
  40971. if (scene.lightsEnabled && !disableLighting) {
  40972. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40973. var light = _a[_i];
  40974. needNormals = true;
  40975. if (defines["LIGHT" + lightIndex] === undefined) {
  40976. needRebuild = true;
  40977. }
  40978. defines["LIGHT" + lightIndex] = true;
  40979. defines["SPOTLIGHT" + lightIndex] = false;
  40980. defines["HEMILIGHT" + lightIndex] = false;
  40981. defines["POINTLIGHT" + lightIndex] = false;
  40982. defines["DIRLIGHT" + lightIndex] = false;
  40983. light.prepareLightSpecificDefines(defines, lightIndex);
  40984. // FallOff.
  40985. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40986. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40987. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40988. switch (light.falloffType) {
  40989. case BABYLON.Light.FALLOFF_GLTF:
  40990. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40991. break;
  40992. case BABYLON.Light.FALLOFF_PHYSICAL:
  40993. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40994. break;
  40995. case BABYLON.Light.FALLOFF_STANDARD:
  40996. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40997. break;
  40998. }
  40999. // Specular
  41000. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41001. specularEnabled = true;
  41002. }
  41003. // Shadows
  41004. defines["SHADOW" + lightIndex] = false;
  41005. defines["SHADOWPCF" + lightIndex] = false;
  41006. defines["SHADOWPCSS" + lightIndex] = false;
  41007. defines["SHADOWPOISSON" + lightIndex] = false;
  41008. defines["SHADOWESM" + lightIndex] = false;
  41009. defines["SHADOWCUBE" + lightIndex] = false;
  41010. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41011. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41012. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41013. var shadowGenerator = light.getShadowGenerator();
  41014. if (shadowGenerator) {
  41015. var shadowMap = shadowGenerator.getShadowMap();
  41016. if (shadowMap) {
  41017. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41018. shadowEnabled = true;
  41019. shadowGenerator.prepareDefines(defines, lightIndex);
  41020. }
  41021. }
  41022. }
  41023. }
  41024. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41025. lightmapMode = true;
  41026. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41027. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41028. }
  41029. else {
  41030. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41031. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41032. }
  41033. lightIndex++;
  41034. if (lightIndex === maxSimultaneousLights)
  41035. break;
  41036. }
  41037. }
  41038. defines["SPECULARTERM"] = specularEnabled;
  41039. defines["SHADOWS"] = shadowEnabled;
  41040. // Resetting all other lights if any
  41041. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41042. if (defines["LIGHT" + index] !== undefined) {
  41043. defines["LIGHT" + index] = false;
  41044. defines["HEMILIGHT" + lightIndex] = false;
  41045. defines["POINTLIGHT" + lightIndex] = false;
  41046. defines["DIRLIGHT" + lightIndex] = false;
  41047. defines["SPOTLIGHT" + lightIndex] = false;
  41048. defines["SHADOW" + lightIndex] = false;
  41049. }
  41050. }
  41051. var caps = scene.getEngine().getCaps();
  41052. if (defines["SHADOWFLOAT"] === undefined) {
  41053. needRebuild = true;
  41054. }
  41055. defines["SHADOWFLOAT"] = shadowEnabled &&
  41056. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41057. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41058. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41059. if (needRebuild) {
  41060. defines.rebuild();
  41061. }
  41062. return needNormals;
  41063. };
  41064. /**
  41065. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41066. * that won t be acctive due to defines being turned off.
  41067. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41068. * @param samplersList The samplers list
  41069. * @param defines The defines helping in the list generation
  41070. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41071. */
  41072. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41073. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41074. var uniformsList;
  41075. var uniformBuffersList = null;
  41076. if (uniformsListOrOptions.uniformsNames) {
  41077. var options = uniformsListOrOptions;
  41078. uniformsList = options.uniformsNames;
  41079. uniformBuffersList = options.uniformBuffersNames;
  41080. samplersList = options.samplers;
  41081. defines = options.defines;
  41082. maxSimultaneousLights = options.maxSimultaneousLights;
  41083. }
  41084. else {
  41085. uniformsList = uniformsListOrOptions;
  41086. if (!samplersList) {
  41087. samplersList = [];
  41088. }
  41089. }
  41090. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41091. if (!defines["LIGHT" + lightIndex]) {
  41092. break;
  41093. }
  41094. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41095. if (uniformBuffersList) {
  41096. uniformBuffersList.push("Light" + lightIndex);
  41097. }
  41098. samplersList.push("shadowSampler" + lightIndex);
  41099. samplersList.push("depthSampler" + lightIndex);
  41100. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41101. samplersList.push("projectionLightSampler" + lightIndex);
  41102. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41103. }
  41104. }
  41105. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41106. uniformsList.push("morphTargetInfluences");
  41107. }
  41108. };
  41109. /**
  41110. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41111. * @param defines The defines to update while falling back
  41112. * @param fallbacks The authorized effect fallbacks
  41113. * @param maxSimultaneousLights The maximum number of lights allowed
  41114. * @param rank the current rank of the Effect
  41115. * @returns The newly affected rank
  41116. */
  41117. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41118. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41119. if (rank === void 0) { rank = 0; }
  41120. var lightFallbackRank = 0;
  41121. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41122. if (!defines["LIGHT" + lightIndex]) {
  41123. break;
  41124. }
  41125. if (lightIndex > 0) {
  41126. lightFallbackRank = rank + lightIndex;
  41127. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41128. }
  41129. if (!defines["SHADOWS"]) {
  41130. if (defines["SHADOW" + lightIndex]) {
  41131. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41132. }
  41133. if (defines["SHADOWPCF" + lightIndex]) {
  41134. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41135. }
  41136. if (defines["SHADOWPCSS" + lightIndex]) {
  41137. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41138. }
  41139. if (defines["SHADOWPOISSON" + lightIndex]) {
  41140. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41141. }
  41142. if (defines["SHADOWESM" + lightIndex]) {
  41143. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41144. }
  41145. }
  41146. }
  41147. return lightFallbackRank++;
  41148. };
  41149. /**
  41150. * Prepares the list of attributes required for morph targets according to the effect defines.
  41151. * @param attribs The current list of supported attribs
  41152. * @param mesh The mesh to prepare the morph targets attributes for
  41153. * @param defines The current Defines of the effect
  41154. */
  41155. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41156. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41157. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41158. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41159. var manager = mesh.morphTargetManager;
  41160. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41161. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41162. for (var index = 0; index < influencers; index++) {
  41163. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41164. if (normal) {
  41165. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41166. }
  41167. if (tangent) {
  41168. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41169. }
  41170. if (attribs.length > maxAttributesCount) {
  41171. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41172. }
  41173. }
  41174. }
  41175. };
  41176. /**
  41177. * Prepares the list of attributes required for bones according to the effect defines.
  41178. * @param attribs The current list of supported attribs
  41179. * @param mesh The mesh to prepare the bones attributes for
  41180. * @param defines The current Defines of the effect
  41181. * @param fallbacks The current efffect fallback strategy
  41182. */
  41183. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41184. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41185. fallbacks.addCPUSkinningFallback(0, mesh);
  41186. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41187. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41188. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41189. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41190. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41191. }
  41192. }
  41193. };
  41194. /**
  41195. * Prepares the list of attributes required for instances according to the effect defines.
  41196. * @param attribs The current list of supported attribs
  41197. * @param defines The current Defines of the effect
  41198. */
  41199. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41200. if (defines["INSTANCES"]) {
  41201. attribs.push("world0");
  41202. attribs.push("world1");
  41203. attribs.push("world2");
  41204. attribs.push("world3");
  41205. }
  41206. };
  41207. /**
  41208. * Binds the light shadow information to the effect for the given mesh.
  41209. * @param light The light containing the generator
  41210. * @param scene The scene the lights belongs to
  41211. * @param mesh The mesh we are binding the information to render
  41212. * @param lightIndex The light index in the effect used to render the mesh
  41213. * @param effect The effect we are binding the data to
  41214. */
  41215. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41216. if (light.shadowEnabled && mesh.receiveShadows) {
  41217. var shadowGenerator = light.getShadowGenerator();
  41218. if (shadowGenerator) {
  41219. shadowGenerator.bindShadowLight(lightIndex, effect);
  41220. }
  41221. }
  41222. };
  41223. /**
  41224. * Binds the light information to the effect.
  41225. * @param light The light containing the generator
  41226. * @param effect The effect we are binding the data to
  41227. * @param lightIndex The light index in the effect used to render
  41228. */
  41229. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41230. light.transferToEffect(effect, lightIndex + "");
  41231. };
  41232. /**
  41233. * Binds the lights information from the scene to the effect for the given mesh.
  41234. * @param scene The scene the lights belongs to
  41235. * @param mesh The mesh we are binding the information to render
  41236. * @param effect The effect we are binding the data to
  41237. * @param defines The generated defines for the effect
  41238. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41239. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41240. */
  41241. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41242. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41243. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41244. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41245. for (var i = 0; i < len; i++) {
  41246. var light = mesh._lightSources[i];
  41247. var iAsString = i.toString();
  41248. var scaledIntensity = light.getScaledIntensity();
  41249. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41250. MaterialHelper.BindLightProperties(light, effect, i);
  41251. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41252. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41253. if (defines["SPECULARTERM"]) {
  41254. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41255. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41256. }
  41257. // Shadows
  41258. if (scene.shadowsEnabled) {
  41259. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41260. }
  41261. light._uniformBuffer.update();
  41262. }
  41263. };
  41264. /**
  41265. * Binds the fog information from the scene to the effect for the given mesh.
  41266. * @param scene The scene the lights belongs to
  41267. * @param mesh The mesh we are binding the information to render
  41268. * @param effect The effect we are binding the data to
  41269. */
  41270. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41271. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41272. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41273. effect.setColor3("vFogColor", scene.fogColor);
  41274. }
  41275. };
  41276. /**
  41277. * Binds the bones information from the mesh to the effect.
  41278. * @param mesh The mesh we are binding the information to render
  41279. * @param effect The effect we are binding the data to
  41280. */
  41281. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41282. if (!effect || !mesh) {
  41283. return;
  41284. }
  41285. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41286. mesh.computeBonesUsingShaders = false;
  41287. }
  41288. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41289. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41290. if (matrices) {
  41291. effect.setMatrices("mBones", matrices);
  41292. }
  41293. }
  41294. };
  41295. /**
  41296. * Binds the morph targets information from the mesh to the effect.
  41297. * @param abstractMesh The mesh we are binding the information to render
  41298. * @param effect The effect we are binding the data to
  41299. */
  41300. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41301. var manager = abstractMesh.morphTargetManager;
  41302. if (!abstractMesh || !manager) {
  41303. return;
  41304. }
  41305. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41306. };
  41307. /**
  41308. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41309. * @param defines The generated defines used in the effect
  41310. * @param effect The effect we are binding the data to
  41311. * @param scene The scene we are willing to render with logarithmic scale for
  41312. */
  41313. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41314. if (defines["LOGARITHMICDEPTH"]) {
  41315. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41316. }
  41317. };
  41318. /**
  41319. * Binds the clip plane information from the scene to the effect.
  41320. * @param scene The scene the clip plane information are extracted from
  41321. * @param effect The effect we are binding the data to
  41322. */
  41323. MaterialHelper.BindClipPlane = function (effect, scene) {
  41324. if (scene.clipPlane) {
  41325. var clipPlane = scene.clipPlane;
  41326. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41327. }
  41328. if (scene.clipPlane2) {
  41329. var clipPlane = scene.clipPlane2;
  41330. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41331. }
  41332. if (scene.clipPlane3) {
  41333. var clipPlane = scene.clipPlane3;
  41334. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41335. }
  41336. if (scene.clipPlane4) {
  41337. var clipPlane = scene.clipPlane4;
  41338. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41339. }
  41340. };
  41341. return MaterialHelper;
  41342. }());
  41343. BABYLON.MaterialHelper = MaterialHelper;
  41344. })(BABYLON || (BABYLON = {}));
  41345. //# sourceMappingURL=babylon.materialHelper.js.map
  41346. var BABYLON;
  41347. (function (BABYLON) {
  41348. var PushMaterial = /** @class */ (function (_super) {
  41349. __extends(PushMaterial, _super);
  41350. function PushMaterial(name, scene) {
  41351. var _this = _super.call(this, name, scene) || this;
  41352. _this._normalMatrix = new BABYLON.Matrix();
  41353. _this.storeEffectOnSubMeshes = true;
  41354. return _this;
  41355. }
  41356. PushMaterial.prototype.getEffect = function () {
  41357. return this._activeEffect;
  41358. };
  41359. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41360. if (!mesh) {
  41361. return false;
  41362. }
  41363. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41364. return true;
  41365. }
  41366. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41367. };
  41368. /**
  41369. * Binds the given world matrix to the active effect
  41370. *
  41371. * @param world the matrix to bind
  41372. */
  41373. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41374. this._activeEffect.setMatrix("world", world);
  41375. };
  41376. /**
  41377. * Binds the given normal matrix to the active effect
  41378. *
  41379. * @param normalMatrix the matrix to bind
  41380. */
  41381. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41382. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41383. };
  41384. PushMaterial.prototype.bind = function (world, mesh) {
  41385. if (!mesh) {
  41386. return;
  41387. }
  41388. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41389. };
  41390. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41391. if (effect === void 0) { effect = null; }
  41392. _super.prototype._afterBind.call(this, mesh);
  41393. this.getScene()._cachedEffect = effect;
  41394. };
  41395. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41396. if (visibility === void 0) { visibility = 1; }
  41397. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41398. };
  41399. return PushMaterial;
  41400. }(BABYLON.Material));
  41401. BABYLON.PushMaterial = PushMaterial;
  41402. })(BABYLON || (BABYLON = {}));
  41403. //# sourceMappingURL=babylon.pushMaterial.js.map
  41404. var BABYLON;
  41405. (function (BABYLON) {
  41406. /** @hidden */
  41407. var StandardMaterialDefines = /** @class */ (function (_super) {
  41408. __extends(StandardMaterialDefines, _super);
  41409. function StandardMaterialDefines() {
  41410. var _this = _super.call(this) || this;
  41411. _this.MAINUV1 = false;
  41412. _this.MAINUV2 = false;
  41413. _this.DIFFUSE = false;
  41414. _this.DIFFUSEDIRECTUV = 0;
  41415. _this.AMBIENT = false;
  41416. _this.AMBIENTDIRECTUV = 0;
  41417. _this.OPACITY = false;
  41418. _this.OPACITYDIRECTUV = 0;
  41419. _this.OPACITYRGB = false;
  41420. _this.REFLECTION = false;
  41421. _this.EMISSIVE = false;
  41422. _this.EMISSIVEDIRECTUV = 0;
  41423. _this.SPECULAR = false;
  41424. _this.SPECULARDIRECTUV = 0;
  41425. _this.BUMP = false;
  41426. _this.BUMPDIRECTUV = 0;
  41427. _this.PARALLAX = false;
  41428. _this.PARALLAXOCCLUSION = false;
  41429. _this.SPECULAROVERALPHA = false;
  41430. _this.CLIPPLANE = false;
  41431. _this.CLIPPLANE2 = false;
  41432. _this.CLIPPLANE3 = false;
  41433. _this.CLIPPLANE4 = false;
  41434. _this.ALPHATEST = false;
  41435. _this.DEPTHPREPASS = false;
  41436. _this.ALPHAFROMDIFFUSE = false;
  41437. _this.POINTSIZE = false;
  41438. _this.FOG = false;
  41439. _this.SPECULARTERM = false;
  41440. _this.DIFFUSEFRESNEL = false;
  41441. _this.OPACITYFRESNEL = false;
  41442. _this.REFLECTIONFRESNEL = false;
  41443. _this.REFRACTIONFRESNEL = false;
  41444. _this.EMISSIVEFRESNEL = false;
  41445. _this.FRESNEL = false;
  41446. _this.NORMAL = false;
  41447. _this.UV1 = false;
  41448. _this.UV2 = false;
  41449. _this.VERTEXCOLOR = false;
  41450. _this.VERTEXALPHA = false;
  41451. _this.NUM_BONE_INFLUENCERS = 0;
  41452. _this.BonesPerMesh = 0;
  41453. _this.INSTANCES = false;
  41454. _this.GLOSSINESS = false;
  41455. _this.ROUGHNESS = false;
  41456. _this.EMISSIVEASILLUMINATION = false;
  41457. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41458. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41459. _this.LIGHTMAP = false;
  41460. _this.LIGHTMAPDIRECTUV = 0;
  41461. _this.OBJECTSPACE_NORMALMAP = false;
  41462. _this.USELIGHTMAPASSHADOWMAP = false;
  41463. _this.REFLECTIONMAP_3D = false;
  41464. _this.REFLECTIONMAP_SPHERICAL = false;
  41465. _this.REFLECTIONMAP_PLANAR = false;
  41466. _this.REFLECTIONMAP_CUBIC = false;
  41467. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41468. _this.REFLECTIONMAP_PROJECTION = false;
  41469. _this.REFLECTIONMAP_SKYBOX = false;
  41470. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41471. _this.REFLECTIONMAP_EXPLICIT = false;
  41472. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41473. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41474. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41475. _this.INVERTCUBICMAP = false;
  41476. _this.LOGARITHMICDEPTH = false;
  41477. _this.REFRACTION = false;
  41478. _this.REFRACTIONMAP_3D = false;
  41479. _this.REFLECTIONOVERALPHA = false;
  41480. _this.TWOSIDEDLIGHTING = false;
  41481. _this.SHADOWFLOAT = false;
  41482. _this.MORPHTARGETS = false;
  41483. _this.MORPHTARGETS_NORMAL = false;
  41484. _this.MORPHTARGETS_TANGENT = false;
  41485. _this.NUM_MORPH_INFLUENCERS = 0;
  41486. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41487. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41488. _this.IMAGEPROCESSING = false;
  41489. _this.VIGNETTE = false;
  41490. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41491. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41492. _this.TONEMAPPING = false;
  41493. _this.TONEMAPPING_ACES = false;
  41494. _this.CONTRAST = false;
  41495. _this.COLORCURVES = false;
  41496. _this.COLORGRADING = false;
  41497. _this.COLORGRADING3D = false;
  41498. _this.SAMPLER3DGREENDEPTH = false;
  41499. _this.SAMPLER3DBGRMAP = false;
  41500. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41501. /**
  41502. * If the reflection texture on this material is in linear color space
  41503. * @hidden
  41504. */
  41505. _this.IS_REFLECTION_LINEAR = false;
  41506. /**
  41507. * If the refraction texture on this material is in linear color space
  41508. * @hidden
  41509. */
  41510. _this.IS_REFRACTION_LINEAR = false;
  41511. _this.EXPOSURE = false;
  41512. _this.rebuild();
  41513. return _this;
  41514. }
  41515. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41516. var modes = [
  41517. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41518. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41519. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41520. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41521. ];
  41522. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41523. var mode = modes_1[_i];
  41524. this[mode] = (mode === modeToEnable);
  41525. }
  41526. };
  41527. return StandardMaterialDefines;
  41528. }(BABYLON.MaterialDefines));
  41529. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41530. var StandardMaterial = /** @class */ (function (_super) {
  41531. __extends(StandardMaterial, _super);
  41532. function StandardMaterial(name, scene) {
  41533. var _this = _super.call(this, name, scene) || this;
  41534. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41535. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41536. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41537. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41538. _this.specularPower = 64;
  41539. _this._useAlphaFromDiffuseTexture = false;
  41540. _this._useEmissiveAsIllumination = false;
  41541. _this._linkEmissiveWithDiffuse = false;
  41542. _this._useSpecularOverAlpha = false;
  41543. _this._useReflectionOverAlpha = false;
  41544. _this._disableLighting = false;
  41545. _this._useObjectSpaceNormalMap = false;
  41546. _this._useParallax = false;
  41547. _this._useParallaxOcclusion = false;
  41548. _this.parallaxScaleBias = 0.05;
  41549. _this._roughness = 0;
  41550. _this.indexOfRefraction = 0.98;
  41551. _this.invertRefractionY = true;
  41552. /**
  41553. * Defines the alpha limits in alpha test mode
  41554. */
  41555. _this.alphaCutOff = 0.4;
  41556. _this._useLightmapAsShadowmap = false;
  41557. _this._useReflectionFresnelFromSpecular = false;
  41558. _this._useGlossinessFromSpecularMapAlpha = false;
  41559. _this._maxSimultaneousLights = 4;
  41560. /**
  41561. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41562. */
  41563. _this._invertNormalMapX = false;
  41564. /**
  41565. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41566. */
  41567. _this._invertNormalMapY = false;
  41568. /**
  41569. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41570. */
  41571. _this._twoSidedLighting = false;
  41572. _this._renderTargets = new BABYLON.SmartArray(16);
  41573. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41574. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41575. // Setup the default processing configuration to the scene.
  41576. _this._attachImageProcessingConfiguration(null);
  41577. _this.getRenderTargetTextures = function () {
  41578. _this._renderTargets.reset();
  41579. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41580. _this._renderTargets.push(_this._reflectionTexture);
  41581. }
  41582. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41583. _this._renderTargets.push(_this._refractionTexture);
  41584. }
  41585. return _this._renderTargets;
  41586. };
  41587. return _this;
  41588. }
  41589. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41590. /**
  41591. * Gets the image processing configuration used either in this material.
  41592. */
  41593. get: function () {
  41594. return this._imageProcessingConfiguration;
  41595. },
  41596. /**
  41597. * Sets the Default image processing configuration used either in the this material.
  41598. *
  41599. * If sets to null, the scene one is in use.
  41600. */
  41601. set: function (value) {
  41602. this._attachImageProcessingConfiguration(value);
  41603. // Ensure the effect will be rebuilt.
  41604. this._markAllSubMeshesAsTexturesDirty();
  41605. },
  41606. enumerable: true,
  41607. configurable: true
  41608. });
  41609. /**
  41610. * Attaches a new image processing configuration to the Standard Material.
  41611. * @param configuration
  41612. */
  41613. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41614. var _this = this;
  41615. if (configuration === this._imageProcessingConfiguration) {
  41616. return;
  41617. }
  41618. // Detaches observer.
  41619. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41620. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41621. }
  41622. // Pick the scene configuration if needed.
  41623. if (!configuration) {
  41624. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41625. }
  41626. else {
  41627. this._imageProcessingConfiguration = configuration;
  41628. }
  41629. // Attaches observer.
  41630. if (this._imageProcessingConfiguration) {
  41631. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41632. _this._markAllSubMeshesAsImageProcessingDirty();
  41633. });
  41634. }
  41635. };
  41636. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41637. /**
  41638. * Gets wether the color curves effect is enabled.
  41639. */
  41640. get: function () {
  41641. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41642. },
  41643. /**
  41644. * Sets wether the color curves effect is enabled.
  41645. */
  41646. set: function (value) {
  41647. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41648. },
  41649. enumerable: true,
  41650. configurable: true
  41651. });
  41652. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41653. /**
  41654. * Gets wether the color grading effect is enabled.
  41655. */
  41656. get: function () {
  41657. return this.imageProcessingConfiguration.colorGradingEnabled;
  41658. },
  41659. /**
  41660. * Gets wether the color grading effect is enabled.
  41661. */
  41662. set: function (value) {
  41663. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41664. },
  41665. enumerable: true,
  41666. configurable: true
  41667. });
  41668. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41669. /**
  41670. * Gets wether tonemapping is enabled or not.
  41671. */
  41672. get: function () {
  41673. return this._imageProcessingConfiguration.toneMappingEnabled;
  41674. },
  41675. /**
  41676. * Sets wether tonemapping is enabled or not
  41677. */
  41678. set: function (value) {
  41679. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41680. },
  41681. enumerable: true,
  41682. configurable: true
  41683. });
  41684. ;
  41685. ;
  41686. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41687. /**
  41688. * The camera exposure used on this material.
  41689. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41690. * This corresponds to a photographic exposure.
  41691. */
  41692. get: function () {
  41693. return this._imageProcessingConfiguration.exposure;
  41694. },
  41695. /**
  41696. * The camera exposure used on this material.
  41697. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41698. * This corresponds to a photographic exposure.
  41699. */
  41700. set: function (value) {
  41701. this._imageProcessingConfiguration.exposure = value;
  41702. },
  41703. enumerable: true,
  41704. configurable: true
  41705. });
  41706. ;
  41707. ;
  41708. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41709. /**
  41710. * Gets The camera contrast used on this material.
  41711. */
  41712. get: function () {
  41713. return this._imageProcessingConfiguration.contrast;
  41714. },
  41715. /**
  41716. * Sets The camera contrast used on this material.
  41717. */
  41718. set: function (value) {
  41719. this._imageProcessingConfiguration.contrast = value;
  41720. },
  41721. enumerable: true,
  41722. configurable: true
  41723. });
  41724. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41725. /**
  41726. * Gets the Color Grading 2D Lookup Texture.
  41727. */
  41728. get: function () {
  41729. return this._imageProcessingConfiguration.colorGradingTexture;
  41730. },
  41731. /**
  41732. * Sets the Color Grading 2D Lookup Texture.
  41733. */
  41734. set: function (value) {
  41735. this._imageProcessingConfiguration.colorGradingTexture = value;
  41736. },
  41737. enumerable: true,
  41738. configurable: true
  41739. });
  41740. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41741. /**
  41742. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41743. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41744. * 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;
  41745. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41746. */
  41747. get: function () {
  41748. return this._imageProcessingConfiguration.colorCurves;
  41749. },
  41750. /**
  41751. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41752. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41753. * 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;
  41754. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41755. */
  41756. set: function (value) {
  41757. this._imageProcessingConfiguration.colorCurves = value;
  41758. },
  41759. enumerable: true,
  41760. configurable: true
  41761. });
  41762. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41763. /**
  41764. * Gets a boolean indicating that current material needs to register RTT
  41765. */
  41766. get: function () {
  41767. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41768. return true;
  41769. }
  41770. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41771. return true;
  41772. }
  41773. return false;
  41774. },
  41775. enumerable: true,
  41776. configurable: true
  41777. });
  41778. StandardMaterial.prototype.getClassName = function () {
  41779. return "StandardMaterial";
  41780. };
  41781. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41782. get: function () {
  41783. return this._useLogarithmicDepth;
  41784. },
  41785. set: function (value) {
  41786. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41787. this._markAllSubMeshesAsMiscDirty();
  41788. },
  41789. enumerable: true,
  41790. configurable: true
  41791. });
  41792. StandardMaterial.prototype.needAlphaBlending = function () {
  41793. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41794. };
  41795. StandardMaterial.prototype.needAlphaTesting = function () {
  41796. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41797. };
  41798. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41799. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41800. };
  41801. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41802. return this._diffuseTexture;
  41803. };
  41804. /**
  41805. * Child classes can use it to update shaders
  41806. */
  41807. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41808. if (useInstances === void 0) { useInstances = false; }
  41809. if (subMesh.effect && this.isFrozen) {
  41810. if (this._wasPreviouslyReady) {
  41811. return true;
  41812. }
  41813. }
  41814. if (!subMesh._materialDefines) {
  41815. subMesh._materialDefines = new StandardMaterialDefines();
  41816. }
  41817. var scene = this.getScene();
  41818. var defines = subMesh._materialDefines;
  41819. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41820. if (defines._renderId === scene.getRenderId()) {
  41821. return true;
  41822. }
  41823. }
  41824. var engine = scene.getEngine();
  41825. // Lights
  41826. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41827. // Textures
  41828. if (defines._areTexturesDirty) {
  41829. defines._needUVs = false;
  41830. defines.MAINUV1 = false;
  41831. defines.MAINUV2 = false;
  41832. if (scene.texturesEnabled) {
  41833. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41834. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41835. return false;
  41836. }
  41837. else {
  41838. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41839. }
  41840. }
  41841. else {
  41842. defines.DIFFUSE = false;
  41843. }
  41844. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41845. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41846. return false;
  41847. }
  41848. else {
  41849. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41850. }
  41851. }
  41852. else {
  41853. defines.AMBIENT = false;
  41854. }
  41855. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41856. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41857. return false;
  41858. }
  41859. else {
  41860. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41861. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41862. }
  41863. }
  41864. else {
  41865. defines.OPACITY = false;
  41866. }
  41867. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41868. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41869. return false;
  41870. }
  41871. else {
  41872. defines._needNormals = true;
  41873. defines.REFLECTION = true;
  41874. defines.ROUGHNESS = (this._roughness > 0);
  41875. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41876. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41877. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41878. switch (this._reflectionTexture.coordinatesMode) {
  41879. case BABYLON.Texture.EXPLICIT_MODE:
  41880. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41881. break;
  41882. case BABYLON.Texture.PLANAR_MODE:
  41883. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41884. break;
  41885. case BABYLON.Texture.PROJECTION_MODE:
  41886. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41887. break;
  41888. case BABYLON.Texture.SKYBOX_MODE:
  41889. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41890. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41891. break;
  41892. case BABYLON.Texture.SPHERICAL_MODE:
  41893. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41894. break;
  41895. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41896. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41897. break;
  41898. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41899. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41900. break;
  41901. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41902. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41903. break;
  41904. case BABYLON.Texture.CUBIC_MODE:
  41905. case BABYLON.Texture.INVCUBIC_MODE:
  41906. default:
  41907. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41908. break;
  41909. }
  41910. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41911. }
  41912. }
  41913. else {
  41914. defines.REFLECTION = false;
  41915. }
  41916. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41917. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41918. return false;
  41919. }
  41920. else {
  41921. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41922. }
  41923. }
  41924. else {
  41925. defines.EMISSIVE = false;
  41926. }
  41927. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41928. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41929. return false;
  41930. }
  41931. else {
  41932. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41933. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41934. }
  41935. }
  41936. else {
  41937. defines.LIGHTMAP = false;
  41938. }
  41939. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41940. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41941. return false;
  41942. }
  41943. else {
  41944. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41945. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41946. }
  41947. }
  41948. else {
  41949. defines.SPECULAR = false;
  41950. }
  41951. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41952. // Bump texure can not be not blocking.
  41953. if (!this._bumpTexture.isReady()) {
  41954. return false;
  41955. }
  41956. else {
  41957. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41958. defines.PARALLAX = this._useParallax;
  41959. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41960. }
  41961. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41962. }
  41963. else {
  41964. defines.BUMP = false;
  41965. }
  41966. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41967. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41968. return false;
  41969. }
  41970. else {
  41971. defines._needUVs = true;
  41972. defines.REFRACTION = true;
  41973. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41974. }
  41975. }
  41976. else {
  41977. defines.REFRACTION = false;
  41978. }
  41979. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41980. }
  41981. else {
  41982. defines.DIFFUSE = false;
  41983. defines.AMBIENT = false;
  41984. defines.OPACITY = false;
  41985. defines.REFLECTION = false;
  41986. defines.EMISSIVE = false;
  41987. defines.LIGHTMAP = false;
  41988. defines.BUMP = false;
  41989. defines.REFRACTION = false;
  41990. }
  41991. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41992. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41993. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41994. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41995. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41996. }
  41997. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41998. if (!this._imageProcessingConfiguration.isReady()) {
  41999. return false;
  42000. }
  42001. this._imageProcessingConfiguration.prepareDefines(defines);
  42002. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42003. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42004. }
  42005. if (defines._areFresnelDirty) {
  42006. if (StandardMaterial.FresnelEnabled) {
  42007. // Fresnel
  42008. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42009. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42010. this._reflectionFresnelParameters) {
  42011. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42012. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42013. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42014. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42015. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42016. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42017. defines._needNormals = true;
  42018. defines.FRESNEL = true;
  42019. }
  42020. }
  42021. else {
  42022. defines.FRESNEL = false;
  42023. }
  42024. }
  42025. // Misc.
  42026. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42027. // Attribs
  42028. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42029. // Values that need to be evaluated on every frame
  42030. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42031. // Get correct effect
  42032. if (defines.isDirty) {
  42033. defines.markAsProcessed();
  42034. scene.resetCachedMaterial();
  42035. // Fallbacks
  42036. var fallbacks = new BABYLON.EffectFallbacks();
  42037. if (defines.REFLECTION) {
  42038. fallbacks.addFallback(0, "REFLECTION");
  42039. }
  42040. if (defines.SPECULAR) {
  42041. fallbacks.addFallback(0, "SPECULAR");
  42042. }
  42043. if (defines.BUMP) {
  42044. fallbacks.addFallback(0, "BUMP");
  42045. }
  42046. if (defines.PARALLAX) {
  42047. fallbacks.addFallback(1, "PARALLAX");
  42048. }
  42049. if (defines.PARALLAXOCCLUSION) {
  42050. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42051. }
  42052. if (defines.SPECULAROVERALPHA) {
  42053. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42054. }
  42055. if (defines.FOG) {
  42056. fallbacks.addFallback(1, "FOG");
  42057. }
  42058. if (defines.POINTSIZE) {
  42059. fallbacks.addFallback(0, "POINTSIZE");
  42060. }
  42061. if (defines.LOGARITHMICDEPTH) {
  42062. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42063. }
  42064. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42065. if (defines.SPECULARTERM) {
  42066. fallbacks.addFallback(0, "SPECULARTERM");
  42067. }
  42068. if (defines.DIFFUSEFRESNEL) {
  42069. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42070. }
  42071. if (defines.OPACITYFRESNEL) {
  42072. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42073. }
  42074. if (defines.REFLECTIONFRESNEL) {
  42075. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42076. }
  42077. if (defines.EMISSIVEFRESNEL) {
  42078. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42079. }
  42080. if (defines.FRESNEL) {
  42081. fallbacks.addFallback(4, "FRESNEL");
  42082. }
  42083. //Attributes
  42084. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42085. if (defines.NORMAL) {
  42086. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42087. }
  42088. if (defines.UV1) {
  42089. attribs.push(BABYLON.VertexBuffer.UVKind);
  42090. }
  42091. if (defines.UV2) {
  42092. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42093. }
  42094. if (defines.VERTEXCOLOR) {
  42095. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42096. }
  42097. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42098. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42099. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42100. var shaderName = "default";
  42101. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42102. "vFogInfos", "vFogColor", "pointSize",
  42103. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42104. "mBones",
  42105. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42106. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42107. "vReflectionPosition", "vReflectionSize",
  42108. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42109. ];
  42110. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42111. var uniformBuffers = ["Material", "Scene"];
  42112. if (BABYLON.ImageProcessingConfiguration) {
  42113. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42114. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42115. }
  42116. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42117. uniformsNames: uniforms,
  42118. uniformBuffersNames: uniformBuffers,
  42119. samplers: samplers,
  42120. defines: defines,
  42121. maxSimultaneousLights: this._maxSimultaneousLights
  42122. });
  42123. if (this.customShaderNameResolve) {
  42124. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42125. }
  42126. var join = defines.toString();
  42127. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42128. attributes: attribs,
  42129. uniformsNames: uniforms,
  42130. uniformBuffersNames: uniformBuffers,
  42131. samplers: samplers,
  42132. defines: join,
  42133. fallbacks: fallbacks,
  42134. onCompiled: this.onCompiled,
  42135. onError: this.onError,
  42136. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42137. }, engine), defines);
  42138. this.buildUniformLayout();
  42139. }
  42140. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42141. return false;
  42142. }
  42143. defines._renderId = scene.getRenderId();
  42144. this._wasPreviouslyReady = true;
  42145. return true;
  42146. };
  42147. StandardMaterial.prototype.buildUniformLayout = function () {
  42148. // Order is important !
  42149. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42150. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42151. this._uniformBuffer.addUniform("opacityParts", 4);
  42152. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42153. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42154. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42155. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42156. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42157. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42158. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42159. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42160. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42161. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42162. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42163. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42164. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42165. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42166. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42167. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42168. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42169. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42170. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42171. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42172. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42173. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42174. this._uniformBuffer.addUniform("specularMatrix", 16);
  42175. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42176. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42177. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42178. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42179. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42180. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42181. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42182. this._uniformBuffer.addUniform("pointSize", 1);
  42183. this._uniformBuffer.create();
  42184. };
  42185. StandardMaterial.prototype.unbind = function () {
  42186. if (this._activeEffect) {
  42187. var needFlag = false;
  42188. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42189. this._activeEffect.setTexture("reflection2DSampler", null);
  42190. needFlag = true;
  42191. }
  42192. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42193. this._activeEffect.setTexture("refraction2DSampler", null);
  42194. needFlag = true;
  42195. }
  42196. if (needFlag) {
  42197. this._markAllSubMeshesAsTexturesDirty();
  42198. }
  42199. }
  42200. _super.prototype.unbind.call(this);
  42201. };
  42202. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42203. var scene = this.getScene();
  42204. var defines = subMesh._materialDefines;
  42205. if (!defines) {
  42206. return;
  42207. }
  42208. var effect = subMesh.effect;
  42209. if (!effect) {
  42210. return;
  42211. }
  42212. this._activeEffect = effect;
  42213. // Matrices
  42214. this.bindOnlyWorldMatrix(world);
  42215. // Normal Matrix
  42216. if (defines.OBJECTSPACE_NORMALMAP) {
  42217. world.toNormalMatrix(this._normalMatrix);
  42218. this.bindOnlyNormalMatrix(this._normalMatrix);
  42219. }
  42220. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42221. // Bones
  42222. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42223. if (mustRebind) {
  42224. this._uniformBuffer.bindToEffect(effect, "Material");
  42225. this.bindViewProjection(effect);
  42226. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42227. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42228. // Fresnel
  42229. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42230. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42231. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42232. }
  42233. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42234. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42235. }
  42236. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42237. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42238. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42239. }
  42240. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42241. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42242. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42243. }
  42244. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42245. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42246. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42247. }
  42248. }
  42249. // Textures
  42250. if (scene.texturesEnabled) {
  42251. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42252. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42253. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42254. if (this._diffuseTexture.hasAlpha) {
  42255. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42256. }
  42257. }
  42258. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42259. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42260. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42261. }
  42262. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42263. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42264. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42265. }
  42266. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42267. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42268. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42269. if (this._reflectionTexture.boundingBoxSize) {
  42270. var cubeTexture = this._reflectionTexture;
  42271. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42272. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42273. }
  42274. }
  42275. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42276. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42277. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42278. }
  42279. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42280. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42281. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42282. }
  42283. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42284. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42285. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42286. }
  42287. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42288. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42289. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42290. if (scene._mirroredCameraPosition) {
  42291. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42292. }
  42293. else {
  42294. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42295. }
  42296. }
  42297. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42298. var depth = 1.0;
  42299. if (!this._refractionTexture.isCube) {
  42300. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42301. if (this._refractionTexture.depth) {
  42302. depth = this._refractionTexture.depth;
  42303. }
  42304. }
  42305. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42306. }
  42307. }
  42308. // Point size
  42309. if (this.pointsCloud) {
  42310. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42311. }
  42312. if (defines.SPECULARTERM) {
  42313. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42314. }
  42315. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42316. // Diffuse
  42317. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42318. }
  42319. // Textures
  42320. if (scene.texturesEnabled) {
  42321. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42322. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42323. }
  42324. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42325. effect.setTexture("ambientSampler", this._ambientTexture);
  42326. }
  42327. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42328. effect.setTexture("opacitySampler", this._opacityTexture);
  42329. }
  42330. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42331. if (this._reflectionTexture.isCube) {
  42332. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42333. }
  42334. else {
  42335. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42336. }
  42337. }
  42338. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42339. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42340. }
  42341. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42342. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42343. }
  42344. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42345. effect.setTexture("specularSampler", this._specularTexture);
  42346. }
  42347. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42348. effect.setTexture("bumpSampler", this._bumpTexture);
  42349. }
  42350. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42351. var depth = 1.0;
  42352. if (this._refractionTexture.isCube) {
  42353. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42354. }
  42355. else {
  42356. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42357. }
  42358. }
  42359. }
  42360. // Clip plane
  42361. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42362. // Colors
  42363. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42364. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42365. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42366. }
  42367. if (mustRebind || !this.isFrozen) {
  42368. // Lights
  42369. if (scene.lightsEnabled && !this._disableLighting) {
  42370. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42371. }
  42372. // View
  42373. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42374. this.bindView(effect);
  42375. }
  42376. // Fog
  42377. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42378. // Morph targets
  42379. if (defines.NUM_MORPH_INFLUENCERS) {
  42380. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42381. }
  42382. // Log. depth
  42383. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42384. // image processing
  42385. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42386. this._imageProcessingConfiguration.bind(this._activeEffect);
  42387. }
  42388. }
  42389. this._uniformBuffer.update();
  42390. this._afterBind(mesh, this._activeEffect);
  42391. };
  42392. StandardMaterial.prototype.getAnimatables = function () {
  42393. var results = [];
  42394. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42395. results.push(this._diffuseTexture);
  42396. }
  42397. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42398. results.push(this._ambientTexture);
  42399. }
  42400. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42401. results.push(this._opacityTexture);
  42402. }
  42403. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42404. results.push(this._reflectionTexture);
  42405. }
  42406. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42407. results.push(this._emissiveTexture);
  42408. }
  42409. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42410. results.push(this._specularTexture);
  42411. }
  42412. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42413. results.push(this._bumpTexture);
  42414. }
  42415. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42416. results.push(this._lightmapTexture);
  42417. }
  42418. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42419. results.push(this._refractionTexture);
  42420. }
  42421. return results;
  42422. };
  42423. StandardMaterial.prototype.getActiveTextures = function () {
  42424. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42425. if (this._diffuseTexture) {
  42426. activeTextures.push(this._diffuseTexture);
  42427. }
  42428. if (this._ambientTexture) {
  42429. activeTextures.push(this._ambientTexture);
  42430. }
  42431. if (this._opacityTexture) {
  42432. activeTextures.push(this._opacityTexture);
  42433. }
  42434. if (this._reflectionTexture) {
  42435. activeTextures.push(this._reflectionTexture);
  42436. }
  42437. if (this._emissiveTexture) {
  42438. activeTextures.push(this._emissiveTexture);
  42439. }
  42440. if (this._specularTexture) {
  42441. activeTextures.push(this._specularTexture);
  42442. }
  42443. if (this._bumpTexture) {
  42444. activeTextures.push(this._bumpTexture);
  42445. }
  42446. if (this._lightmapTexture) {
  42447. activeTextures.push(this._lightmapTexture);
  42448. }
  42449. if (this._refractionTexture) {
  42450. activeTextures.push(this._refractionTexture);
  42451. }
  42452. return activeTextures;
  42453. };
  42454. StandardMaterial.prototype.hasTexture = function (texture) {
  42455. if (_super.prototype.hasTexture.call(this, texture)) {
  42456. return true;
  42457. }
  42458. if (this._diffuseTexture === texture) {
  42459. return true;
  42460. }
  42461. if (this._ambientTexture === texture) {
  42462. return true;
  42463. }
  42464. if (this._opacityTexture === texture) {
  42465. return true;
  42466. }
  42467. if (this._reflectionTexture === texture) {
  42468. return true;
  42469. }
  42470. if (this._emissiveTexture === texture) {
  42471. return true;
  42472. }
  42473. if (this._specularTexture === texture) {
  42474. return true;
  42475. }
  42476. if (this._bumpTexture === texture) {
  42477. return true;
  42478. }
  42479. if (this._lightmapTexture === texture) {
  42480. return true;
  42481. }
  42482. if (this._refractionTexture === texture) {
  42483. return true;
  42484. }
  42485. return false;
  42486. };
  42487. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42488. if (forceDisposeTextures) {
  42489. if (this._diffuseTexture) {
  42490. this._diffuseTexture.dispose();
  42491. }
  42492. if (this._ambientTexture) {
  42493. this._ambientTexture.dispose();
  42494. }
  42495. if (this._opacityTexture) {
  42496. this._opacityTexture.dispose();
  42497. }
  42498. if (this._reflectionTexture) {
  42499. this._reflectionTexture.dispose();
  42500. }
  42501. if (this._emissiveTexture) {
  42502. this._emissiveTexture.dispose();
  42503. }
  42504. if (this._specularTexture) {
  42505. this._specularTexture.dispose();
  42506. }
  42507. if (this._bumpTexture) {
  42508. this._bumpTexture.dispose();
  42509. }
  42510. if (this._lightmapTexture) {
  42511. this._lightmapTexture.dispose();
  42512. }
  42513. if (this._refractionTexture) {
  42514. this._refractionTexture.dispose();
  42515. }
  42516. }
  42517. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42518. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42519. }
  42520. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42521. };
  42522. StandardMaterial.prototype.clone = function (name) {
  42523. var _this = this;
  42524. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42525. result.name = name;
  42526. result.id = name;
  42527. return result;
  42528. };
  42529. StandardMaterial.prototype.serialize = function () {
  42530. return BABYLON.SerializationHelper.Serialize(this);
  42531. };
  42532. // Statics
  42533. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42534. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42535. };
  42536. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42537. get: function () {
  42538. return StandardMaterial._DiffuseTextureEnabled;
  42539. },
  42540. set: function (value) {
  42541. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42542. return;
  42543. }
  42544. StandardMaterial._DiffuseTextureEnabled = value;
  42545. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42546. },
  42547. enumerable: true,
  42548. configurable: true
  42549. });
  42550. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42551. get: function () {
  42552. return StandardMaterial._AmbientTextureEnabled;
  42553. },
  42554. set: function (value) {
  42555. if (StandardMaterial._AmbientTextureEnabled === value) {
  42556. return;
  42557. }
  42558. StandardMaterial._AmbientTextureEnabled = value;
  42559. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42560. },
  42561. enumerable: true,
  42562. configurable: true
  42563. });
  42564. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42565. get: function () {
  42566. return StandardMaterial._OpacityTextureEnabled;
  42567. },
  42568. set: function (value) {
  42569. if (StandardMaterial._OpacityTextureEnabled === value) {
  42570. return;
  42571. }
  42572. StandardMaterial._OpacityTextureEnabled = value;
  42573. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42574. },
  42575. enumerable: true,
  42576. configurable: true
  42577. });
  42578. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42579. get: function () {
  42580. return StandardMaterial._ReflectionTextureEnabled;
  42581. },
  42582. set: function (value) {
  42583. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42584. return;
  42585. }
  42586. StandardMaterial._ReflectionTextureEnabled = value;
  42587. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42588. },
  42589. enumerable: true,
  42590. configurable: true
  42591. });
  42592. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42593. get: function () {
  42594. return StandardMaterial._EmissiveTextureEnabled;
  42595. },
  42596. set: function (value) {
  42597. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42598. return;
  42599. }
  42600. StandardMaterial._EmissiveTextureEnabled = value;
  42601. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42602. },
  42603. enumerable: true,
  42604. configurable: true
  42605. });
  42606. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42607. get: function () {
  42608. return StandardMaterial._SpecularTextureEnabled;
  42609. },
  42610. set: function (value) {
  42611. if (StandardMaterial._SpecularTextureEnabled === value) {
  42612. return;
  42613. }
  42614. StandardMaterial._SpecularTextureEnabled = value;
  42615. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42616. },
  42617. enumerable: true,
  42618. configurable: true
  42619. });
  42620. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42621. get: function () {
  42622. return StandardMaterial._BumpTextureEnabled;
  42623. },
  42624. set: function (value) {
  42625. if (StandardMaterial._BumpTextureEnabled === value) {
  42626. return;
  42627. }
  42628. StandardMaterial._BumpTextureEnabled = value;
  42629. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42630. },
  42631. enumerable: true,
  42632. configurable: true
  42633. });
  42634. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42635. get: function () {
  42636. return StandardMaterial._LightmapTextureEnabled;
  42637. },
  42638. set: function (value) {
  42639. if (StandardMaterial._LightmapTextureEnabled === value) {
  42640. return;
  42641. }
  42642. StandardMaterial._LightmapTextureEnabled = value;
  42643. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42644. },
  42645. enumerable: true,
  42646. configurable: true
  42647. });
  42648. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42649. get: function () {
  42650. return StandardMaterial._RefractionTextureEnabled;
  42651. },
  42652. set: function (value) {
  42653. if (StandardMaterial._RefractionTextureEnabled === value) {
  42654. return;
  42655. }
  42656. StandardMaterial._RefractionTextureEnabled = value;
  42657. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42658. },
  42659. enumerable: true,
  42660. configurable: true
  42661. });
  42662. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42663. get: function () {
  42664. return StandardMaterial._ColorGradingTextureEnabled;
  42665. },
  42666. set: function (value) {
  42667. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42668. return;
  42669. }
  42670. StandardMaterial._ColorGradingTextureEnabled = value;
  42671. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42672. },
  42673. enumerable: true,
  42674. configurable: true
  42675. });
  42676. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42677. get: function () {
  42678. return StandardMaterial._FresnelEnabled;
  42679. },
  42680. set: function (value) {
  42681. if (StandardMaterial._FresnelEnabled === value) {
  42682. return;
  42683. }
  42684. StandardMaterial._FresnelEnabled = value;
  42685. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42686. },
  42687. enumerable: true,
  42688. configurable: true
  42689. });
  42690. // Flags used to enable or disable a type of texture for all Standard Materials
  42691. StandardMaterial._DiffuseTextureEnabled = true;
  42692. StandardMaterial._AmbientTextureEnabled = true;
  42693. StandardMaterial._OpacityTextureEnabled = true;
  42694. StandardMaterial._ReflectionTextureEnabled = true;
  42695. StandardMaterial._EmissiveTextureEnabled = true;
  42696. StandardMaterial._SpecularTextureEnabled = true;
  42697. StandardMaterial._BumpTextureEnabled = true;
  42698. StandardMaterial._LightmapTextureEnabled = true;
  42699. StandardMaterial._RefractionTextureEnabled = true;
  42700. StandardMaterial._ColorGradingTextureEnabled = true;
  42701. StandardMaterial._FresnelEnabled = true;
  42702. __decorate([
  42703. BABYLON.serializeAsTexture("diffuseTexture")
  42704. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42705. __decorate([
  42706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42707. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42708. __decorate([
  42709. BABYLON.serializeAsTexture("ambientTexture")
  42710. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42711. __decorate([
  42712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42713. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42714. __decorate([
  42715. BABYLON.serializeAsTexture("opacityTexture")
  42716. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42717. __decorate([
  42718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42719. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42720. __decorate([
  42721. BABYLON.serializeAsTexture("reflectionTexture")
  42722. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42723. __decorate([
  42724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42725. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42726. __decorate([
  42727. BABYLON.serializeAsTexture("emissiveTexture")
  42728. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42729. __decorate([
  42730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42731. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42732. __decorate([
  42733. BABYLON.serializeAsTexture("specularTexture")
  42734. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42735. __decorate([
  42736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42737. ], StandardMaterial.prototype, "specularTexture", void 0);
  42738. __decorate([
  42739. BABYLON.serializeAsTexture("bumpTexture")
  42740. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42741. __decorate([
  42742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42743. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42744. __decorate([
  42745. BABYLON.serializeAsTexture("lightmapTexture")
  42746. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42747. __decorate([
  42748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42749. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42750. __decorate([
  42751. BABYLON.serializeAsTexture("refractionTexture")
  42752. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42753. __decorate([
  42754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42755. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42756. __decorate([
  42757. BABYLON.serializeAsColor3("ambient")
  42758. ], StandardMaterial.prototype, "ambientColor", void 0);
  42759. __decorate([
  42760. BABYLON.serializeAsColor3("diffuse")
  42761. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42762. __decorate([
  42763. BABYLON.serializeAsColor3("specular")
  42764. ], StandardMaterial.prototype, "specularColor", void 0);
  42765. __decorate([
  42766. BABYLON.serializeAsColor3("emissive")
  42767. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42768. __decorate([
  42769. BABYLON.serialize()
  42770. ], StandardMaterial.prototype, "specularPower", void 0);
  42771. __decorate([
  42772. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42773. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42774. __decorate([
  42775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42776. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42777. __decorate([
  42778. BABYLON.serialize("useEmissiveAsIllumination")
  42779. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42780. __decorate([
  42781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42782. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42783. __decorate([
  42784. BABYLON.serialize("linkEmissiveWithDiffuse")
  42785. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42786. __decorate([
  42787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42788. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42789. __decorate([
  42790. BABYLON.serialize("useSpecularOverAlpha")
  42791. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42792. __decorate([
  42793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42794. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42795. __decorate([
  42796. BABYLON.serialize("useReflectionOverAlpha")
  42797. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42798. __decorate([
  42799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42800. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42801. __decorate([
  42802. BABYLON.serialize("disableLighting")
  42803. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42804. __decorate([
  42805. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42806. ], StandardMaterial.prototype, "disableLighting", void 0);
  42807. __decorate([
  42808. BABYLON.serialize("useObjectSpaceNormalMap")
  42809. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42810. __decorate([
  42811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42812. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42813. __decorate([
  42814. BABYLON.serialize("useParallax")
  42815. ], StandardMaterial.prototype, "_useParallax", void 0);
  42816. __decorate([
  42817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42818. ], StandardMaterial.prototype, "useParallax", void 0);
  42819. __decorate([
  42820. BABYLON.serialize("useParallaxOcclusion")
  42821. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42822. __decorate([
  42823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42824. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42825. __decorate([
  42826. BABYLON.serialize()
  42827. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42828. __decorate([
  42829. BABYLON.serialize("roughness")
  42830. ], StandardMaterial.prototype, "_roughness", void 0);
  42831. __decorate([
  42832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42833. ], StandardMaterial.prototype, "roughness", void 0);
  42834. __decorate([
  42835. BABYLON.serialize()
  42836. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42837. __decorate([
  42838. BABYLON.serialize()
  42839. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42840. __decorate([
  42841. BABYLON.serialize()
  42842. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42843. __decorate([
  42844. BABYLON.serialize("useLightmapAsShadowmap")
  42845. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42846. __decorate([
  42847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42848. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42849. __decorate([
  42850. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42851. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42852. __decorate([
  42853. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42854. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42855. __decorate([
  42856. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42857. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42858. __decorate([
  42859. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42860. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42861. __decorate([
  42862. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42863. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42864. __decorate([
  42865. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42866. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42867. __decorate([
  42868. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42869. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42870. __decorate([
  42871. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42872. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42873. __decorate([
  42874. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42875. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42876. __decorate([
  42877. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42878. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42879. __decorate([
  42880. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42881. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42882. __decorate([
  42883. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42884. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42885. __decorate([
  42886. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42887. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42888. __decorate([
  42889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42890. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42891. __decorate([
  42892. BABYLON.serialize("maxSimultaneousLights")
  42893. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42894. __decorate([
  42895. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42896. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42897. __decorate([
  42898. BABYLON.serialize("invertNormalMapX")
  42899. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42900. __decorate([
  42901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42902. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42903. __decorate([
  42904. BABYLON.serialize("invertNormalMapY")
  42905. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42906. __decorate([
  42907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42908. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42909. __decorate([
  42910. BABYLON.serialize("twoSidedLighting")
  42911. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42912. __decorate([
  42913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42914. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42915. __decorate([
  42916. BABYLON.serialize()
  42917. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42918. return StandardMaterial;
  42919. }(BABYLON.PushMaterial));
  42920. BABYLON.StandardMaterial = StandardMaterial;
  42921. })(BABYLON || (BABYLON = {}));
  42922. //# sourceMappingURL=babylon.standardMaterial.js.map
  42923. var BABYLON;
  42924. (function (BABYLON) {
  42925. /**
  42926. * Class representing spherical polynomial coefficients to the 3rd degree
  42927. */
  42928. var SphericalPolynomial = /** @class */ (function () {
  42929. function SphericalPolynomial() {
  42930. /**
  42931. * The x coefficients of the spherical polynomial
  42932. */
  42933. this.x = BABYLON.Vector3.Zero();
  42934. /**
  42935. * The y coefficients of the spherical polynomial
  42936. */
  42937. this.y = BABYLON.Vector3.Zero();
  42938. /**
  42939. * The z coefficients of the spherical polynomial
  42940. */
  42941. this.z = BABYLON.Vector3.Zero();
  42942. /**
  42943. * The xx coefficients of the spherical polynomial
  42944. */
  42945. this.xx = BABYLON.Vector3.Zero();
  42946. /**
  42947. * The yy coefficients of the spherical polynomial
  42948. */
  42949. this.yy = BABYLON.Vector3.Zero();
  42950. /**
  42951. * The zz coefficients of the spherical polynomial
  42952. */
  42953. this.zz = BABYLON.Vector3.Zero();
  42954. /**
  42955. * The xy coefficients of the spherical polynomial
  42956. */
  42957. this.xy = BABYLON.Vector3.Zero();
  42958. /**
  42959. * The yz coefficients of the spherical polynomial
  42960. */
  42961. this.yz = BABYLON.Vector3.Zero();
  42962. /**
  42963. * The zx coefficients of the spherical polynomial
  42964. */
  42965. this.zx = BABYLON.Vector3.Zero();
  42966. }
  42967. /**
  42968. * Adds an ambient color to the spherical polynomial
  42969. * @param color the color to add
  42970. */
  42971. SphericalPolynomial.prototype.addAmbient = function (color) {
  42972. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42973. this.xx = this.xx.add(colorVector);
  42974. this.yy = this.yy.add(colorVector);
  42975. this.zz = this.zz.add(colorVector);
  42976. };
  42977. /**
  42978. * Scales the spherical polynomial by the given amount
  42979. * @param scale the amount to scale
  42980. */
  42981. SphericalPolynomial.prototype.scale = function (scale) {
  42982. this.x = this.x.scale(scale);
  42983. this.y = this.y.scale(scale);
  42984. this.z = this.z.scale(scale);
  42985. this.xx = this.xx.scale(scale);
  42986. this.yy = this.yy.scale(scale);
  42987. this.zz = this.zz.scale(scale);
  42988. this.yz = this.yz.scale(scale);
  42989. this.zx = this.zx.scale(scale);
  42990. this.xy = this.xy.scale(scale);
  42991. };
  42992. /**
  42993. * Gets the spherical polynomial from harmonics
  42994. * @param harmonics the spherical harmonics
  42995. * @returns the spherical polynomial
  42996. */
  42997. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42998. var result = new SphericalPolynomial();
  42999. result.x = harmonics.l11.scale(1.02333);
  43000. result.y = harmonics.l1_1.scale(1.02333);
  43001. result.z = harmonics.l10.scale(1.02333);
  43002. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43003. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43004. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43005. result.yz = harmonics.l2_1.scale(0.858086);
  43006. result.zx = harmonics.l21.scale(0.858086);
  43007. result.xy = harmonics.l2_2.scale(0.858086);
  43008. result.scale(1.0 / Math.PI);
  43009. return result;
  43010. };
  43011. /**
  43012. * Constructs a spherical polynomial from an array.
  43013. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43014. * @returns the spherical polynomial
  43015. */
  43016. SphericalPolynomial.FromArray = function (data) {
  43017. var sp = new SphericalPolynomial();
  43018. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43019. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43020. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43021. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43022. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43023. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43024. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43025. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43026. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43027. return sp;
  43028. };
  43029. return SphericalPolynomial;
  43030. }());
  43031. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43032. /**
  43033. * Class representing spherical harmonics coefficients to the 3rd degree
  43034. */
  43035. var SphericalHarmonics = /** @class */ (function () {
  43036. function SphericalHarmonics() {
  43037. /**
  43038. * The l0,0 coefficients of the spherical harmonics
  43039. */
  43040. this.l00 = BABYLON.Vector3.Zero();
  43041. /**
  43042. * The l1,-1 coefficients of the spherical harmonics
  43043. */
  43044. this.l1_1 = BABYLON.Vector3.Zero();
  43045. /**
  43046. * The l1,0 coefficients of the spherical harmonics
  43047. */
  43048. this.l10 = BABYLON.Vector3.Zero();
  43049. /**
  43050. * The l1,1 coefficients of the spherical harmonics
  43051. */
  43052. this.l11 = BABYLON.Vector3.Zero();
  43053. /**
  43054. * The l2,-2 coefficients of the spherical harmonics
  43055. */
  43056. this.l2_2 = BABYLON.Vector3.Zero();
  43057. /**
  43058. * The l2,-1 coefficients of the spherical harmonics
  43059. */
  43060. this.l2_1 = BABYLON.Vector3.Zero();
  43061. /**
  43062. * The l2,0 coefficients of the spherical harmonics
  43063. */
  43064. this.l20 = BABYLON.Vector3.Zero();
  43065. /**
  43066. * The l2,1 coefficients of the spherical harmonics
  43067. */
  43068. this.l21 = BABYLON.Vector3.Zero();
  43069. /**
  43070. * The l2,2 coefficients of the spherical harmonics
  43071. */
  43072. this.lL22 = BABYLON.Vector3.Zero();
  43073. }
  43074. /**
  43075. * Adds a light to the spherical harmonics
  43076. * @param direction the direction of the light
  43077. * @param color the color of the light
  43078. * @param deltaSolidAngle the delta solid angle of the light
  43079. */
  43080. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43081. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43082. var c = colorVector.scale(deltaSolidAngle);
  43083. this.l00 = this.l00.add(c.scale(0.282095));
  43084. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43085. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43086. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43087. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43088. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43089. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43090. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43091. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43092. };
  43093. /**
  43094. * Scales the spherical harmonics by the given amount
  43095. * @param scale the amount to scale
  43096. */
  43097. SphericalHarmonics.prototype.scale = function (scale) {
  43098. this.l00 = this.l00.scale(scale);
  43099. this.l1_1 = this.l1_1.scale(scale);
  43100. this.l10 = this.l10.scale(scale);
  43101. this.l11 = this.l11.scale(scale);
  43102. this.l2_2 = this.l2_2.scale(scale);
  43103. this.l2_1 = this.l2_1.scale(scale);
  43104. this.l20 = this.l20.scale(scale);
  43105. this.l21 = this.l21.scale(scale);
  43106. this.lL22 = this.lL22.scale(scale);
  43107. };
  43108. /**
  43109. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43110. *
  43111. * ```
  43112. * E_lm = A_l * L_lm
  43113. * ```
  43114. *
  43115. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43116. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43117. * the scaling factors are given in equation 9.
  43118. */
  43119. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43120. // Constant (Band 0)
  43121. this.l00 = this.l00.scale(3.141593);
  43122. // Linear (Band 1)
  43123. this.l1_1 = this.l1_1.scale(2.094395);
  43124. this.l10 = this.l10.scale(2.094395);
  43125. this.l11 = this.l11.scale(2.094395);
  43126. // Quadratic (Band 2)
  43127. this.l2_2 = this.l2_2.scale(0.785398);
  43128. this.l2_1 = this.l2_1.scale(0.785398);
  43129. this.l20 = this.l20.scale(0.785398);
  43130. this.l21 = this.l21.scale(0.785398);
  43131. this.lL22 = this.lL22.scale(0.785398);
  43132. };
  43133. /**
  43134. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43135. *
  43136. * ```
  43137. * L = (1/pi) * E * rho
  43138. * ```
  43139. *
  43140. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43141. */
  43142. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43143. this.scale(1.0 / Math.PI);
  43144. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43145. // (The pixel shader must apply albedo after texture fetches, etc).
  43146. };
  43147. /**
  43148. * Gets the spherical harmonics from polynomial
  43149. * @param polynomial the spherical polynomial
  43150. * @returns the spherical harmonics
  43151. */
  43152. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43153. var result = new SphericalHarmonics();
  43154. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43155. result.l1_1 = polynomial.y.scale(0.977204);
  43156. result.l10 = polynomial.z.scale(0.977204);
  43157. result.l11 = polynomial.x.scale(0.977204);
  43158. result.l2_2 = polynomial.xy.scale(1.16538);
  43159. result.l2_1 = polynomial.yz.scale(1.16538);
  43160. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43161. result.l21 = polynomial.zx.scale(1.16538);
  43162. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43163. result.scale(Math.PI);
  43164. return result;
  43165. };
  43166. /**
  43167. * Constructs a spherical harmonics from an array.
  43168. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43169. * @returns the spherical harmonics
  43170. */
  43171. SphericalHarmonics.FromArray = function (data) {
  43172. var sh = new SphericalHarmonics();
  43173. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43174. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43175. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43176. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43177. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43178. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43179. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43180. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43181. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43182. return sh;
  43183. };
  43184. return SphericalHarmonics;
  43185. }());
  43186. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43187. })(BABYLON || (BABYLON = {}));
  43188. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43189. var BABYLON;
  43190. (function (BABYLON) {
  43191. var FileFaceOrientation = /** @class */ (function () {
  43192. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43193. this.name = name;
  43194. this.worldAxisForNormal = worldAxisForNormal;
  43195. this.worldAxisForFileX = worldAxisForFileX;
  43196. this.worldAxisForFileY = worldAxisForFileY;
  43197. }
  43198. return FileFaceOrientation;
  43199. }());
  43200. ;
  43201. /**
  43202. * Helper class dealing with the extraction of spherical polynomial dataArray
  43203. * from a cube map.
  43204. */
  43205. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43206. function CubeMapToSphericalPolynomialTools() {
  43207. }
  43208. /**
  43209. * Converts a texture to the according Spherical Polynomial data.
  43210. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43211. *
  43212. * @param texture The texture to extract the information from.
  43213. * @return The Spherical Polynomial data.
  43214. */
  43215. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43216. if (!texture.isCube) {
  43217. // Only supports cube Textures currently.
  43218. return null;
  43219. }
  43220. var size = texture.getSize().width;
  43221. var right = texture.readPixels(0);
  43222. var left = texture.readPixels(1);
  43223. var up;
  43224. var down;
  43225. if (texture.isRenderTarget) {
  43226. up = texture.readPixels(3);
  43227. down = texture.readPixels(2);
  43228. }
  43229. else {
  43230. up = texture.readPixels(2);
  43231. down = texture.readPixels(3);
  43232. }
  43233. var front = texture.readPixels(4);
  43234. var back = texture.readPixels(5);
  43235. var gammaSpace = texture.gammaSpace;
  43236. // Always read as RGBA.
  43237. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43238. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43239. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43240. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43241. }
  43242. var cubeInfo = {
  43243. size: size,
  43244. right: right,
  43245. left: left,
  43246. up: up,
  43247. down: down,
  43248. front: front,
  43249. back: back,
  43250. format: format,
  43251. type: type,
  43252. gammaSpace: gammaSpace,
  43253. };
  43254. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43255. };
  43256. /**
  43257. * Converts a cubemap to the according Spherical Polynomial data.
  43258. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43259. *
  43260. * @param cubeInfo The Cube map to extract the information from.
  43261. * @return The Spherical Polynomial data.
  43262. */
  43263. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43264. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43265. var totalSolidAngle = 0.0;
  43266. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43267. var du = 2.0 / cubeInfo.size;
  43268. var dv = du;
  43269. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43270. var minUV = du * 0.5 - 1.0;
  43271. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43272. var fileFace = this.FileFaces[faceIndex];
  43273. var dataArray = cubeInfo[fileFace.name];
  43274. var v = minUV;
  43275. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43276. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43277. // Because SP is still linear, so summation is fine in that basis.
  43278. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43279. for (var y = 0; y < cubeInfo.size; y++) {
  43280. var u = minUV;
  43281. for (var x = 0; x < cubeInfo.size; x++) {
  43282. // World direction (not normalised)
  43283. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43284. worldDirection.normalize();
  43285. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43286. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43287. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43288. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43289. // Handle Integer types.
  43290. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43291. r /= 255;
  43292. g /= 255;
  43293. b /= 255;
  43294. }
  43295. // Handle Gamma space textures.
  43296. if (cubeInfo.gammaSpace) {
  43297. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43298. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43299. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43300. }
  43301. var color = new BABYLON.Color3(r, g, b);
  43302. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43303. totalSolidAngle += deltaSolidAngle;
  43304. u += du;
  43305. }
  43306. v += dv;
  43307. }
  43308. }
  43309. // Solid angle for entire sphere is 4*pi
  43310. var sphereSolidAngle = 4.0 * Math.PI;
  43311. // Adjust the solid angle to allow for how many faces we processed.
  43312. var facesProcessed = 6.0;
  43313. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43314. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43315. // This is needed because the numerical integration over the cube uses a
  43316. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43317. // and also to compensate for accumulative error due to float precision in the summation.
  43318. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43319. sphericalHarmonics.scale(correctionFactor);
  43320. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43321. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43322. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43323. };
  43324. CubeMapToSphericalPolynomialTools.FileFaces = [
  43325. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43326. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43327. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43328. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43329. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43330. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43331. ];
  43332. return CubeMapToSphericalPolynomialTools;
  43333. }());
  43334. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43335. })(BABYLON || (BABYLON = {}));
  43336. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43337. var BABYLON;
  43338. (function (BABYLON) {
  43339. /**
  43340. * Manages the defines for the PBR Material.
  43341. * @hiddenChildren
  43342. */
  43343. var PBRMaterialDefines = /** @class */ (function (_super) {
  43344. __extends(PBRMaterialDefines, _super);
  43345. /**
  43346. * Initializes the PBR Material defines.
  43347. */
  43348. function PBRMaterialDefines() {
  43349. var _this = _super.call(this) || this;
  43350. _this.PBR = true;
  43351. _this.MAINUV1 = false;
  43352. _this.MAINUV2 = false;
  43353. _this.UV1 = false;
  43354. _this.UV2 = false;
  43355. _this.ALBEDO = false;
  43356. _this.ALBEDODIRECTUV = 0;
  43357. _this.VERTEXCOLOR = false;
  43358. _this.AMBIENT = false;
  43359. _this.AMBIENTDIRECTUV = 0;
  43360. _this.AMBIENTINGRAYSCALE = false;
  43361. _this.OPACITY = false;
  43362. _this.VERTEXALPHA = false;
  43363. _this.OPACITYDIRECTUV = 0;
  43364. _this.OPACITYRGB = false;
  43365. _this.ALPHATEST = false;
  43366. _this.DEPTHPREPASS = false;
  43367. _this.ALPHABLEND = false;
  43368. _this.ALPHAFROMALBEDO = false;
  43369. _this.ALPHATESTVALUE = "0.5";
  43370. _this.SPECULAROVERALPHA = false;
  43371. _this.RADIANCEOVERALPHA = false;
  43372. _this.ALPHAFRESNEL = false;
  43373. _this.LINEARALPHAFRESNEL = false;
  43374. _this.PREMULTIPLYALPHA = false;
  43375. _this.EMISSIVE = false;
  43376. _this.EMISSIVEDIRECTUV = 0;
  43377. _this.REFLECTIVITY = false;
  43378. _this.REFLECTIVITYDIRECTUV = 0;
  43379. _this.SPECULARTERM = false;
  43380. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43381. _this.MICROSURFACEAUTOMATIC = false;
  43382. _this.LODBASEDMICROSFURACE = false;
  43383. _this.MICROSURFACEMAP = false;
  43384. _this.MICROSURFACEMAPDIRECTUV = 0;
  43385. _this.METALLICWORKFLOW = false;
  43386. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43387. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43388. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43389. _this.AOSTOREINMETALMAPRED = false;
  43390. _this.ENVIRONMENTBRDF = false;
  43391. _this.NORMAL = false;
  43392. _this.TANGENT = false;
  43393. _this.BUMP = false;
  43394. _this.BUMPDIRECTUV = 0;
  43395. _this.OBJECTSPACE_NORMALMAP = false;
  43396. _this.PARALLAX = false;
  43397. _this.PARALLAXOCCLUSION = false;
  43398. _this.NORMALXYSCALE = true;
  43399. _this.LIGHTMAP = false;
  43400. _this.LIGHTMAPDIRECTUV = 0;
  43401. _this.USELIGHTMAPASSHADOWMAP = false;
  43402. _this.GAMMALIGHTMAP = false;
  43403. _this.REFLECTION = false;
  43404. _this.REFLECTIONMAP_3D = false;
  43405. _this.REFLECTIONMAP_SPHERICAL = false;
  43406. _this.REFLECTIONMAP_PLANAR = false;
  43407. _this.REFLECTIONMAP_CUBIC = false;
  43408. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43409. _this.REFLECTIONMAP_PROJECTION = false;
  43410. _this.REFLECTIONMAP_SKYBOX = false;
  43411. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43412. _this.REFLECTIONMAP_EXPLICIT = false;
  43413. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43414. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43415. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43416. _this.INVERTCUBICMAP = false;
  43417. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43418. _this.USESPHERICALINVERTEX = false;
  43419. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43420. _this.LODINREFLECTIONALPHA = false;
  43421. _this.GAMMAREFLECTION = false;
  43422. _this.RGBDREFLECTION = false;
  43423. _this.RADIANCEOCCLUSION = false;
  43424. _this.HORIZONOCCLUSION = false;
  43425. _this.REFRACTION = false;
  43426. _this.REFRACTIONMAP_3D = false;
  43427. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43428. _this.LODINREFRACTIONALPHA = false;
  43429. _this.GAMMAREFRACTION = false;
  43430. _this.RGBDREFRACTION = false;
  43431. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43432. _this.INSTANCES = false;
  43433. _this.NUM_BONE_INFLUENCERS = 0;
  43434. _this.BonesPerMesh = 0;
  43435. _this.NONUNIFORMSCALING = false;
  43436. _this.MORPHTARGETS = false;
  43437. _this.MORPHTARGETS_NORMAL = false;
  43438. _this.MORPHTARGETS_TANGENT = false;
  43439. _this.NUM_MORPH_INFLUENCERS = 0;
  43440. _this.IMAGEPROCESSING = false;
  43441. _this.VIGNETTE = false;
  43442. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43443. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43444. _this.TONEMAPPING = false;
  43445. _this.TONEMAPPING_ACES = false;
  43446. _this.CONTRAST = false;
  43447. _this.COLORCURVES = false;
  43448. _this.COLORGRADING = false;
  43449. _this.COLORGRADING3D = false;
  43450. _this.SAMPLER3DGREENDEPTH = false;
  43451. _this.SAMPLER3DBGRMAP = false;
  43452. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43453. _this.EXPOSURE = false;
  43454. _this.USEPHYSICALLIGHTFALLOFF = false;
  43455. _this.USEGLTFLIGHTFALLOFF = false;
  43456. _this.TWOSIDEDLIGHTING = false;
  43457. _this.SHADOWFLOAT = false;
  43458. _this.CLIPPLANE = false;
  43459. _this.CLIPPLANE2 = false;
  43460. _this.CLIPPLANE3 = false;
  43461. _this.CLIPPLANE4 = false;
  43462. _this.POINTSIZE = false;
  43463. _this.FOG = false;
  43464. _this.LOGARITHMICDEPTH = false;
  43465. _this.FORCENORMALFORWARD = false;
  43466. _this.SPECULARAA = false;
  43467. _this.UNLIT = false;
  43468. _this.rebuild();
  43469. return _this;
  43470. }
  43471. /**
  43472. * Resets the PBR Material defines.
  43473. */
  43474. PBRMaterialDefines.prototype.reset = function () {
  43475. _super.prototype.reset.call(this);
  43476. this.ALPHATESTVALUE = "0.5";
  43477. this.PBR = true;
  43478. };
  43479. return PBRMaterialDefines;
  43480. }(BABYLON.MaterialDefines));
  43481. /**
  43482. * The Physically based material base class of BJS.
  43483. *
  43484. * This offers the main features of a standard PBR material.
  43485. * For more information, please refer to the documentation :
  43486. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43487. */
  43488. var PBRBaseMaterial = /** @class */ (function (_super) {
  43489. __extends(PBRBaseMaterial, _super);
  43490. /**
  43491. * Instantiates a new PBRMaterial instance.
  43492. *
  43493. * @param name The material name
  43494. * @param scene The scene the material will be use in.
  43495. */
  43496. function PBRBaseMaterial(name, scene) {
  43497. var _this = _super.call(this, name, scene) || this;
  43498. /**
  43499. * Intensity of the direct lights e.g. the four lights available in your scene.
  43500. * This impacts both the direct diffuse and specular highlights.
  43501. */
  43502. _this._directIntensity = 1.0;
  43503. /**
  43504. * Intensity of the emissive part of the material.
  43505. * This helps controlling the emissive effect without modifying the emissive color.
  43506. */
  43507. _this._emissiveIntensity = 1.0;
  43508. /**
  43509. * Intensity of the environment e.g. how much the environment will light the object
  43510. * either through harmonics for rough material or through the refelction for shiny ones.
  43511. */
  43512. _this._environmentIntensity = 1.0;
  43513. /**
  43514. * This is a special control allowing the reduction of the specular highlights coming from the
  43515. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43516. */
  43517. _this._specularIntensity = 1.0;
  43518. /**
  43519. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43520. */
  43521. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43522. /**
  43523. * Debug Control allowing disabling the bump map on this material.
  43524. */
  43525. _this._disableBumpMap = false;
  43526. /**
  43527. * AKA Occlusion Texture Intensity in other nomenclature.
  43528. */
  43529. _this._ambientTextureStrength = 1.0;
  43530. /**
  43531. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43532. * 1 means it completely occludes it
  43533. * 0 mean it has no impact
  43534. */
  43535. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43536. /**
  43537. * The color of a material in ambient lighting.
  43538. */
  43539. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43540. /**
  43541. * AKA Diffuse Color in other nomenclature.
  43542. */
  43543. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43544. /**
  43545. * AKA Specular Color in other nomenclature.
  43546. */
  43547. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43548. /**
  43549. * The color applied when light is reflected from a material.
  43550. */
  43551. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43552. /**
  43553. * The color applied when light is emitted from a material.
  43554. */
  43555. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43556. /**
  43557. * AKA Glossiness in other nomenclature.
  43558. */
  43559. _this._microSurface = 0.9;
  43560. /**
  43561. * source material index of refraction (IOR)' / 'destination material IOR.
  43562. */
  43563. _this._indexOfRefraction = 0.66;
  43564. /**
  43565. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43566. */
  43567. _this._invertRefractionY = false;
  43568. /**
  43569. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43570. * Materials half opaque for instance using refraction could benefit from this control.
  43571. */
  43572. _this._linkRefractionWithTransparency = false;
  43573. /**
  43574. * Specifies that the material will use the light map as a show map.
  43575. */
  43576. _this._useLightmapAsShadowmap = false;
  43577. /**
  43578. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43579. * makes the reflect vector face the model (under horizon).
  43580. */
  43581. _this._useHorizonOcclusion = true;
  43582. /**
  43583. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43584. * too much the area relying on ambient texture to define their ambient occlusion.
  43585. */
  43586. _this._useRadianceOcclusion = true;
  43587. /**
  43588. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43589. */
  43590. _this._useAlphaFromAlbedoTexture = false;
  43591. /**
  43592. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43593. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43594. */
  43595. _this._useSpecularOverAlpha = true;
  43596. /**
  43597. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43598. */
  43599. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43600. /**
  43601. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43602. */
  43603. _this._useRoughnessFromMetallicTextureAlpha = true;
  43604. /**
  43605. * Specifies if the metallic texture contains the roughness information in its green channel.
  43606. */
  43607. _this._useRoughnessFromMetallicTextureGreen = false;
  43608. /**
  43609. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43610. */
  43611. _this._useMetallnessFromMetallicTextureBlue = false;
  43612. /**
  43613. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43614. */
  43615. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43616. /**
  43617. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43618. */
  43619. _this._useAmbientInGrayScale = false;
  43620. /**
  43621. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43622. * The material will try to infer what glossiness each pixel should be.
  43623. */
  43624. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43625. /**
  43626. * Defines the falloff type used in this material.
  43627. * It by default is Physical.
  43628. */
  43629. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43630. /**
  43631. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43632. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43633. */
  43634. _this._useRadianceOverAlpha = true;
  43635. /**
  43636. * Allows using an object space normal map (instead of tangent space).
  43637. */
  43638. _this._useObjectSpaceNormalMap = false;
  43639. /**
  43640. * Allows using the bump map in parallax mode.
  43641. */
  43642. _this._useParallax = false;
  43643. /**
  43644. * Allows using the bump map in parallax occlusion mode.
  43645. */
  43646. _this._useParallaxOcclusion = false;
  43647. /**
  43648. * Controls the scale bias of the parallax mode.
  43649. */
  43650. _this._parallaxScaleBias = 0.05;
  43651. /**
  43652. * If sets to true, disables all the lights affecting the material.
  43653. */
  43654. _this._disableLighting = false;
  43655. /**
  43656. * Number of Simultaneous lights allowed on the material.
  43657. */
  43658. _this._maxSimultaneousLights = 4;
  43659. /**
  43660. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43661. */
  43662. _this._invertNormalMapX = false;
  43663. /**
  43664. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43665. */
  43666. _this._invertNormalMapY = false;
  43667. /**
  43668. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43669. */
  43670. _this._twoSidedLighting = false;
  43671. /**
  43672. * Defines the alpha limits in alpha test mode.
  43673. */
  43674. _this._alphaCutOff = 0.4;
  43675. /**
  43676. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43677. */
  43678. _this._forceAlphaTest = false;
  43679. /**
  43680. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43681. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43682. */
  43683. _this._useAlphaFresnel = false;
  43684. /**
  43685. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43686. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43687. */
  43688. _this._useLinearAlphaFresnel = false;
  43689. /**
  43690. * The transparency mode of the material.
  43691. */
  43692. _this._transparencyMode = null;
  43693. /**
  43694. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43695. * from cos thetav and roughness:
  43696. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43697. */
  43698. _this._environmentBRDFTexture = null;
  43699. /**
  43700. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43701. */
  43702. _this._forceIrradianceInFragment = false;
  43703. /**
  43704. * Force normal to face away from face.
  43705. */
  43706. _this._forceNormalForward = false;
  43707. /**
  43708. * Enables specular anti aliasing in the PBR shader.
  43709. * It will both interacts on the Geometry for analytical and IBL lighting.
  43710. * It also prefilter the roughness map based on the bump values.
  43711. */
  43712. _this._enableSpecularAntiAliasing = false;
  43713. /**
  43714. * Stores the available render targets.
  43715. */
  43716. _this._renderTargets = new BABYLON.SmartArray(16);
  43717. /**
  43718. * Sets the global ambient color for the material used in lighting calculations.
  43719. */
  43720. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43721. /**
  43722. * If set to true, no lighting calculations will be applied.
  43723. */
  43724. _this._unlit = false;
  43725. // Setup the default processing configuration to the scene.
  43726. _this._attachImageProcessingConfiguration(null);
  43727. _this.getRenderTargetTextures = function () {
  43728. _this._renderTargets.reset();
  43729. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43730. _this._renderTargets.push(_this._reflectionTexture);
  43731. }
  43732. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43733. _this._renderTargets.push(_this._refractionTexture);
  43734. }
  43735. return _this._renderTargets;
  43736. };
  43737. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43738. return _this;
  43739. }
  43740. /**
  43741. * Attaches a new image processing configuration to the PBR Material.
  43742. * @param configuration
  43743. */
  43744. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43745. var _this = this;
  43746. if (configuration === this._imageProcessingConfiguration) {
  43747. return;
  43748. }
  43749. // Detaches observer.
  43750. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43751. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43752. }
  43753. // Pick the scene configuration if needed.
  43754. if (!configuration) {
  43755. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43756. }
  43757. else {
  43758. this._imageProcessingConfiguration = configuration;
  43759. }
  43760. // Attaches observer.
  43761. if (this._imageProcessingConfiguration) {
  43762. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43763. _this._markAllSubMeshesAsImageProcessingDirty();
  43764. });
  43765. }
  43766. };
  43767. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43768. /**
  43769. * Gets a boolean indicating that current material needs to register RTT
  43770. */
  43771. get: function () {
  43772. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43773. return true;
  43774. }
  43775. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43776. return true;
  43777. }
  43778. return false;
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. /**
  43784. * Gets the name of the material class.
  43785. */
  43786. PBRBaseMaterial.prototype.getClassName = function () {
  43787. return "PBRBaseMaterial";
  43788. };
  43789. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43790. /**
  43791. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43792. */
  43793. get: function () {
  43794. return this._useLogarithmicDepth;
  43795. },
  43796. /**
  43797. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43798. */
  43799. set: function (value) {
  43800. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43801. },
  43802. enumerable: true,
  43803. configurable: true
  43804. });
  43805. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43806. /**
  43807. * Gets the current transparency mode.
  43808. */
  43809. get: function () {
  43810. return this._transparencyMode;
  43811. },
  43812. /**
  43813. * Sets the transparency mode of the material.
  43814. *
  43815. * | Value | Type | Description |
  43816. * | ----- | ----------------------------------- | ----------- |
  43817. * | 0 | OPAQUE | |
  43818. * | 1 | ALPHATEST | |
  43819. * | 2 | ALPHABLEND | |
  43820. * | 3 | ALPHATESTANDBLEND | |
  43821. *
  43822. */
  43823. set: function (value) {
  43824. if (this._transparencyMode === value) {
  43825. return;
  43826. }
  43827. this._transparencyMode = value;
  43828. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43829. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43830. },
  43831. enumerable: true,
  43832. configurable: true
  43833. });
  43834. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43835. /**
  43836. * Returns true if alpha blending should be disabled.
  43837. */
  43838. get: function () {
  43839. return (this._linkRefractionWithTransparency ||
  43840. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43841. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43842. },
  43843. enumerable: true,
  43844. configurable: true
  43845. });
  43846. /**
  43847. * Specifies whether or not this material should be rendered in alpha blend mode.
  43848. */
  43849. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43850. if (this._disableAlphaBlending) {
  43851. return false;
  43852. }
  43853. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43854. };
  43855. /**
  43856. * Specifies if the mesh will require alpha blending.
  43857. * @param mesh - BJS mesh.
  43858. */
  43859. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43860. if (this._disableAlphaBlending) {
  43861. return false;
  43862. }
  43863. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43864. };
  43865. /**
  43866. * Specifies whether or not this material should be rendered in alpha test mode.
  43867. */
  43868. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43869. if (this._forceAlphaTest) {
  43870. return true;
  43871. }
  43872. if (this._linkRefractionWithTransparency) {
  43873. return false;
  43874. }
  43875. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43876. };
  43877. /**
  43878. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43879. */
  43880. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43881. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43882. };
  43883. /**
  43884. * Gets the texture used for the alpha test.
  43885. */
  43886. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43887. return this._albedoTexture;
  43888. };
  43889. /**
  43890. * Specifies that the submesh is ready to be used.
  43891. * @param mesh - BJS mesh.
  43892. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43893. * @param useInstances - Specifies that instances should be used.
  43894. * @returns - boolean indicating that the submesh is ready or not.
  43895. */
  43896. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43897. if (subMesh.effect && this.isFrozen) {
  43898. if (this._wasPreviouslyReady) {
  43899. return true;
  43900. }
  43901. }
  43902. if (!subMesh._materialDefines) {
  43903. subMesh._materialDefines = new PBRMaterialDefines();
  43904. }
  43905. var defines = subMesh._materialDefines;
  43906. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43907. if (defines._renderId === this.getScene().getRenderId()) {
  43908. return true;
  43909. }
  43910. }
  43911. var scene = this.getScene();
  43912. var engine = scene.getEngine();
  43913. if (defines._areTexturesDirty) {
  43914. if (scene.texturesEnabled) {
  43915. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43916. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43917. return false;
  43918. }
  43919. }
  43920. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43921. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43922. return false;
  43923. }
  43924. }
  43925. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43926. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43927. return false;
  43928. }
  43929. }
  43930. var reflectionTexture = this._getReflectionTexture();
  43931. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43932. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43933. return false;
  43934. }
  43935. }
  43936. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43937. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43938. return false;
  43939. }
  43940. }
  43941. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43942. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43943. return false;
  43944. }
  43945. }
  43946. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43947. if (this._metallicTexture) {
  43948. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43949. return false;
  43950. }
  43951. }
  43952. else if (this._reflectivityTexture) {
  43953. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43954. return false;
  43955. }
  43956. }
  43957. if (this._microSurfaceTexture) {
  43958. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43959. return false;
  43960. }
  43961. }
  43962. }
  43963. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43964. // Bump texture cannot be not blocking.
  43965. if (!this._bumpTexture.isReady()) {
  43966. return false;
  43967. }
  43968. }
  43969. var refractionTexture = this._getRefractionTexture();
  43970. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43971. if (!refractionTexture.isReadyOrNotBlocking()) {
  43972. return false;
  43973. }
  43974. }
  43975. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43976. // This is blocking.
  43977. if (!this._environmentBRDFTexture.isReady()) {
  43978. return false;
  43979. }
  43980. }
  43981. }
  43982. }
  43983. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43984. if (!this._imageProcessingConfiguration.isReady()) {
  43985. return false;
  43986. }
  43987. }
  43988. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43989. mesh.createNormals(true);
  43990. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43991. }
  43992. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43993. if (effect) {
  43994. scene.resetCachedMaterial();
  43995. subMesh.setEffect(effect, defines);
  43996. this.buildUniformLayout();
  43997. }
  43998. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43999. return false;
  44000. }
  44001. defines._renderId = scene.getRenderId();
  44002. this._wasPreviouslyReady = true;
  44003. return true;
  44004. };
  44005. /**
  44006. * Specifies if the material uses metallic roughness workflow.
  44007. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44008. */
  44009. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44010. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44011. return true;
  44012. }
  44013. return false;
  44014. };
  44015. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44016. if (onCompiled === void 0) { onCompiled = null; }
  44017. if (onError === void 0) { onError = null; }
  44018. if (useInstances === void 0) { useInstances = null; }
  44019. if (useClipPlane === void 0) { useClipPlane = null; }
  44020. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44021. if (!defines.isDirty) {
  44022. return null;
  44023. }
  44024. defines.markAsProcessed();
  44025. var scene = this.getScene();
  44026. var engine = scene.getEngine();
  44027. // Fallbacks
  44028. var fallbacks = new BABYLON.EffectFallbacks();
  44029. var fallbackRank = 0;
  44030. if (defines.USESPHERICALINVERTEX) {
  44031. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44032. }
  44033. if (defines.FOG) {
  44034. fallbacks.addFallback(fallbackRank, "FOG");
  44035. }
  44036. if (defines.SPECULARAA) {
  44037. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44038. }
  44039. if (defines.POINTSIZE) {
  44040. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44041. }
  44042. if (defines.LOGARITHMICDEPTH) {
  44043. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44044. }
  44045. if (defines.PARALLAX) {
  44046. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44047. }
  44048. if (defines.PARALLAXOCCLUSION) {
  44049. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44050. }
  44051. if (defines.ENVIRONMENTBRDF) {
  44052. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44053. }
  44054. if (defines.TANGENT) {
  44055. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44056. }
  44057. if (defines.BUMP) {
  44058. fallbacks.addFallback(fallbackRank++, "BUMP");
  44059. }
  44060. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44061. if (defines.SPECULARTERM) {
  44062. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44063. }
  44064. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44065. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44066. }
  44067. if (defines.LIGHTMAP) {
  44068. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44069. }
  44070. if (defines.NORMAL) {
  44071. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44072. }
  44073. if (defines.AMBIENT) {
  44074. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44075. }
  44076. if (defines.EMISSIVE) {
  44077. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44078. }
  44079. if (defines.VERTEXCOLOR) {
  44080. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44081. }
  44082. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44083. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44084. }
  44085. if (defines.MORPHTARGETS) {
  44086. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44087. }
  44088. //Attributes
  44089. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44090. if (defines.NORMAL) {
  44091. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44092. }
  44093. if (defines.TANGENT) {
  44094. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44095. }
  44096. if (defines.UV1) {
  44097. attribs.push(BABYLON.VertexBuffer.UVKind);
  44098. }
  44099. if (defines.UV2) {
  44100. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44101. }
  44102. if (defines.VERTEXCOLOR) {
  44103. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44104. }
  44105. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44106. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44107. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44108. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44109. "vFogInfos", "vFogColor", "pointSize",
  44110. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44111. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44112. "mBones",
  44113. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44114. "vLightingIntensity",
  44115. "logarithmicDepthConstant",
  44116. "vSphericalX", "vSphericalY", "vSphericalZ",
  44117. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44118. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44119. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44120. "vTangentSpaceParams"
  44121. ];
  44122. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44123. "bumpSampler", "lightmapSampler", "opacitySampler",
  44124. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44125. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44126. "microSurfaceSampler", "environmentBrdfSampler"];
  44127. var uniformBuffers = ["Material", "Scene"];
  44128. if (BABYLON.ImageProcessingConfiguration) {
  44129. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44130. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44131. }
  44132. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44133. uniformsNames: uniforms,
  44134. uniformBuffersNames: uniformBuffers,
  44135. samplers: samplers,
  44136. defines: defines,
  44137. maxSimultaneousLights: this._maxSimultaneousLights
  44138. });
  44139. var join = defines.toString();
  44140. return engine.createEffect("pbr", {
  44141. attributes: attribs,
  44142. uniformsNames: uniforms,
  44143. uniformBuffersNames: uniformBuffers,
  44144. samplers: samplers,
  44145. defines: join,
  44146. fallbacks: fallbacks,
  44147. onCompiled: onCompiled,
  44148. onError: onError,
  44149. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44150. }, engine);
  44151. };
  44152. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44153. if (useInstances === void 0) { useInstances = null; }
  44154. if (useClipPlane === void 0) { useClipPlane = null; }
  44155. var scene = this.getScene();
  44156. var engine = scene.getEngine();
  44157. // Lights
  44158. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44159. defines._needNormals = true;
  44160. // Textures
  44161. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44162. if (defines._areTexturesDirty) {
  44163. defines._needUVs = false;
  44164. if (scene.texturesEnabled) {
  44165. if (scene.getEngine().getCaps().textureLOD) {
  44166. defines.LODBASEDMICROSFURACE = true;
  44167. }
  44168. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44169. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44170. }
  44171. else {
  44172. defines.ALBEDO = false;
  44173. }
  44174. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44175. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44176. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44177. }
  44178. else {
  44179. defines.AMBIENT = false;
  44180. }
  44181. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44182. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44183. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44184. }
  44185. else {
  44186. defines.OPACITY = false;
  44187. }
  44188. var reflectionTexture = this._getReflectionTexture();
  44189. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44190. defines.REFLECTION = true;
  44191. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44192. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44193. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44194. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44195. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44196. defines.INVERTCUBICMAP = true;
  44197. }
  44198. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44199. switch (reflectionTexture.coordinatesMode) {
  44200. case BABYLON.Texture.EXPLICIT_MODE:
  44201. defines.REFLECTIONMAP_EXPLICIT = true;
  44202. break;
  44203. case BABYLON.Texture.PLANAR_MODE:
  44204. defines.REFLECTIONMAP_PLANAR = true;
  44205. break;
  44206. case BABYLON.Texture.PROJECTION_MODE:
  44207. defines.REFLECTIONMAP_PROJECTION = true;
  44208. break;
  44209. case BABYLON.Texture.SKYBOX_MODE:
  44210. defines.REFLECTIONMAP_SKYBOX = true;
  44211. break;
  44212. case BABYLON.Texture.SPHERICAL_MODE:
  44213. defines.REFLECTIONMAP_SPHERICAL = true;
  44214. break;
  44215. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44216. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44217. break;
  44218. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44219. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44220. break;
  44221. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44222. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44223. break;
  44224. case BABYLON.Texture.CUBIC_MODE:
  44225. case BABYLON.Texture.INVCUBIC_MODE:
  44226. default:
  44227. defines.REFLECTIONMAP_CUBIC = true;
  44228. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44229. break;
  44230. }
  44231. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44232. if (reflectionTexture.sphericalPolynomial) {
  44233. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44234. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44235. defines.USESPHERICALINVERTEX = false;
  44236. }
  44237. else {
  44238. defines.USESPHERICALINVERTEX = true;
  44239. }
  44240. }
  44241. }
  44242. else {
  44243. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44244. }
  44245. }
  44246. else {
  44247. defines.REFLECTION = false;
  44248. defines.REFLECTIONMAP_3D = false;
  44249. defines.REFLECTIONMAP_SPHERICAL = false;
  44250. defines.REFLECTIONMAP_PLANAR = false;
  44251. defines.REFLECTIONMAP_CUBIC = false;
  44252. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44253. defines.REFLECTIONMAP_PROJECTION = false;
  44254. defines.REFLECTIONMAP_SKYBOX = false;
  44255. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44256. defines.REFLECTIONMAP_EXPLICIT = false;
  44257. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44258. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44259. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44260. defines.INVERTCUBICMAP = false;
  44261. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44262. defines.USESPHERICALINVERTEX = false;
  44263. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44264. defines.LODINREFLECTIONALPHA = false;
  44265. defines.GAMMAREFLECTION = false;
  44266. defines.RGBDREFLECTION = false;
  44267. }
  44268. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44269. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44270. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44271. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44272. }
  44273. else {
  44274. defines.LIGHTMAP = false;
  44275. }
  44276. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44278. }
  44279. else {
  44280. defines.EMISSIVE = false;
  44281. }
  44282. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44283. if (this._metallicTexture) {
  44284. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44285. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44286. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44287. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44288. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44289. }
  44290. else if (this._reflectivityTexture) {
  44291. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44292. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44293. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44294. }
  44295. else {
  44296. defines.REFLECTIVITY = false;
  44297. }
  44298. if (this._microSurfaceTexture) {
  44299. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44300. }
  44301. else {
  44302. defines.MICROSURFACEMAP = false;
  44303. }
  44304. }
  44305. else {
  44306. defines.REFLECTIVITY = false;
  44307. defines.MICROSURFACEMAP = false;
  44308. }
  44309. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44310. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44311. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44312. defines.PARALLAX = true;
  44313. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44314. }
  44315. else {
  44316. defines.PARALLAX = false;
  44317. }
  44318. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44319. }
  44320. else {
  44321. defines.BUMP = false;
  44322. }
  44323. var refractionTexture = this._getRefractionTexture();
  44324. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44325. defines.REFRACTION = true;
  44326. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44327. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44328. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44329. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44330. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44331. if (this._linkRefractionWithTransparency) {
  44332. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44333. }
  44334. }
  44335. else {
  44336. defines.REFRACTION = false;
  44337. }
  44338. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44339. defines.ENVIRONMENTBRDF = true;
  44340. }
  44341. else {
  44342. defines.ENVIRONMENTBRDF = false;
  44343. }
  44344. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44345. defines.ALPHAFROMALBEDO = true;
  44346. }
  44347. else {
  44348. defines.ALPHAFROMALBEDO = false;
  44349. }
  44350. }
  44351. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44352. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44353. defines.USEPHYSICALLIGHTFALLOFF = false;
  44354. defines.USEGLTFLIGHTFALLOFF = false;
  44355. }
  44356. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44357. defines.USEPHYSICALLIGHTFALLOFF = false;
  44358. defines.USEGLTFLIGHTFALLOFF = true;
  44359. }
  44360. else {
  44361. defines.USEPHYSICALLIGHTFALLOFF = true;
  44362. defines.USEGLTFLIGHTFALLOFF = false;
  44363. }
  44364. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44365. if (!this.backFaceCulling && this._twoSidedLighting) {
  44366. defines.TWOSIDEDLIGHTING = true;
  44367. }
  44368. else {
  44369. defines.TWOSIDEDLIGHTING = false;
  44370. }
  44371. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44372. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44373. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44374. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44375. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44376. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44377. }
  44378. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44379. this._imageProcessingConfiguration.prepareDefines(defines);
  44380. }
  44381. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44382. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44383. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44384. // Misc.
  44385. if (defines._areMiscDirty) {
  44386. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44387. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44388. }
  44389. // Values that need to be evaluated on every frame
  44390. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44391. // Attribs
  44392. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44393. };
  44394. /**
  44395. * Force shader compilation
  44396. */
  44397. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44398. var _this = this;
  44399. var localOptions = __assign({ clipPlane: false }, options);
  44400. var defines = new PBRMaterialDefines();
  44401. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44402. if (effect.isReady()) {
  44403. if (onCompiled) {
  44404. onCompiled(this);
  44405. }
  44406. }
  44407. else {
  44408. effect.onCompileObservable.add(function () {
  44409. if (onCompiled) {
  44410. onCompiled(_this);
  44411. }
  44412. });
  44413. }
  44414. };
  44415. /**
  44416. * Initializes the uniform buffer layout for the shader.
  44417. */
  44418. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44419. // Order is important !
  44420. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44421. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44422. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44423. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44424. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44425. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44426. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44427. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44428. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44429. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44430. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44431. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44432. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44433. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44434. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44435. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44436. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44437. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44438. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44439. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44440. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44441. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44442. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44443. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44444. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44445. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44446. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44447. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44448. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44449. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44450. this._uniformBuffer.addUniform("pointSize", 1);
  44451. this._uniformBuffer.create();
  44452. };
  44453. /**
  44454. * Unbinds the textures.
  44455. */
  44456. PBRBaseMaterial.prototype.unbind = function () {
  44457. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44458. this._uniformBuffer.setTexture("reflectionSampler", null);
  44459. }
  44460. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44461. this._uniformBuffer.setTexture("refractionSampler", null);
  44462. }
  44463. _super.prototype.unbind.call(this);
  44464. };
  44465. /**
  44466. * Binds the submesh data.
  44467. * @param world - The world matrix.
  44468. * @param mesh - The BJS mesh.
  44469. * @param subMesh - A submesh of the BJS mesh.
  44470. */
  44471. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44472. var scene = this.getScene();
  44473. var defines = subMesh._materialDefines;
  44474. if (!defines) {
  44475. return;
  44476. }
  44477. var effect = subMesh.effect;
  44478. if (!effect) {
  44479. return;
  44480. }
  44481. this._activeEffect = effect;
  44482. // Matrices
  44483. this.bindOnlyWorldMatrix(world);
  44484. // Normal Matrix
  44485. if (defines.OBJECTSPACE_NORMALMAP) {
  44486. world.toNormalMatrix(this._normalMatrix);
  44487. this.bindOnlyNormalMatrix(this._normalMatrix);
  44488. }
  44489. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44490. // Bones
  44491. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44492. var reflectionTexture = null;
  44493. if (mustRebind) {
  44494. this._uniformBuffer.bindToEffect(effect, "Material");
  44495. this.bindViewProjection(effect);
  44496. reflectionTexture = this._getReflectionTexture();
  44497. var refractionTexture = this._getRefractionTexture();
  44498. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44499. // Texture uniforms
  44500. if (scene.texturesEnabled) {
  44501. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44502. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44503. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44504. }
  44505. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44506. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44507. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44508. }
  44509. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44510. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44511. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44512. }
  44513. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44514. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44515. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44516. if (reflectionTexture.boundingBoxSize) {
  44517. var cubeTexture = reflectionTexture;
  44518. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44519. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44520. }
  44521. var polynomials = reflectionTexture.sphericalPolynomial;
  44522. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44523. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44524. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44525. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44526. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44527. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44528. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44529. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44530. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44531. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44532. }
  44533. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44534. }
  44535. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44536. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44537. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44538. }
  44539. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44540. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44541. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44542. }
  44543. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44544. if (this._metallicTexture) {
  44545. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44546. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44547. }
  44548. else if (this._reflectivityTexture) {
  44549. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44550. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44551. }
  44552. if (this._microSurfaceTexture) {
  44553. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44554. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44555. }
  44556. }
  44557. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44558. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44559. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44560. if (scene._mirroredCameraPosition) {
  44561. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44562. }
  44563. else {
  44564. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44565. }
  44566. }
  44567. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44568. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44569. var depth = 1.0;
  44570. if (!refractionTexture.isCube) {
  44571. if (refractionTexture.depth) {
  44572. depth = refractionTexture.depth;
  44573. }
  44574. }
  44575. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44576. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44577. }
  44578. }
  44579. // Point size
  44580. if (this.pointsCloud) {
  44581. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44582. }
  44583. // Colors
  44584. if (defines.METALLICWORKFLOW) {
  44585. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44586. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44587. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44588. }
  44589. else {
  44590. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44591. }
  44592. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44593. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44594. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44595. // Misc
  44596. this._lightingInfos.x = this._directIntensity;
  44597. this._lightingInfos.y = this._emissiveIntensity;
  44598. this._lightingInfos.z = this._environmentIntensity;
  44599. this._lightingInfos.w = this._specularIntensity;
  44600. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44601. }
  44602. // Textures
  44603. if (scene.texturesEnabled) {
  44604. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44605. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44606. }
  44607. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44608. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44609. }
  44610. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44611. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44612. }
  44613. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44614. if (defines.LODBASEDMICROSFURACE) {
  44615. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44616. }
  44617. else {
  44618. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44619. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44620. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44621. }
  44622. }
  44623. if (defines.ENVIRONMENTBRDF) {
  44624. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44625. }
  44626. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44627. if (defines.LODBASEDMICROSFURACE) {
  44628. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44629. }
  44630. else {
  44631. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44632. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44633. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44634. }
  44635. }
  44636. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44637. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44638. }
  44639. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44640. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44641. }
  44642. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44643. if (this._metallicTexture) {
  44644. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44645. }
  44646. else if (this._reflectivityTexture) {
  44647. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44648. }
  44649. if (this._microSurfaceTexture) {
  44650. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44651. }
  44652. }
  44653. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44654. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44655. }
  44656. }
  44657. // Clip plane
  44658. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44659. // Colors
  44660. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44661. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44662. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44663. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44664. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44665. }
  44666. if (mustRebind || !this.isFrozen) {
  44667. // Lights
  44668. if (scene.lightsEnabled && !this._disableLighting) {
  44669. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44670. }
  44671. // View
  44672. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44673. this.bindView(effect);
  44674. }
  44675. // Fog
  44676. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44677. // Morph targets
  44678. if (defines.NUM_MORPH_INFLUENCERS) {
  44679. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44680. }
  44681. // image processing
  44682. this._imageProcessingConfiguration.bind(this._activeEffect);
  44683. // Log. depth
  44684. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44685. }
  44686. this._uniformBuffer.update();
  44687. this._afterBind(mesh, this._activeEffect);
  44688. };
  44689. /**
  44690. * Returns the animatable textures.
  44691. * @returns - Array of animatable textures.
  44692. */
  44693. PBRBaseMaterial.prototype.getAnimatables = function () {
  44694. var results = [];
  44695. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44696. results.push(this._albedoTexture);
  44697. }
  44698. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44699. results.push(this._ambientTexture);
  44700. }
  44701. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44702. results.push(this._opacityTexture);
  44703. }
  44704. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44705. results.push(this._reflectionTexture);
  44706. }
  44707. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44708. results.push(this._emissiveTexture);
  44709. }
  44710. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44711. results.push(this._metallicTexture);
  44712. }
  44713. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44714. results.push(this._reflectivityTexture);
  44715. }
  44716. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44717. results.push(this._bumpTexture);
  44718. }
  44719. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44720. results.push(this._lightmapTexture);
  44721. }
  44722. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44723. results.push(this._refractionTexture);
  44724. }
  44725. return results;
  44726. };
  44727. /**
  44728. * Returns the texture used for reflections.
  44729. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44730. */
  44731. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44732. if (this._reflectionTexture) {
  44733. return this._reflectionTexture;
  44734. }
  44735. return this.getScene().environmentTexture;
  44736. };
  44737. /**
  44738. * Returns the texture used for refraction or null if none is used.
  44739. * @returns - Refection texture if present. If no refraction texture and refraction
  44740. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44741. */
  44742. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44743. if (this._refractionTexture) {
  44744. return this._refractionTexture;
  44745. }
  44746. if (this._linkRefractionWithTransparency) {
  44747. return this.getScene().environmentTexture;
  44748. }
  44749. return null;
  44750. };
  44751. /**
  44752. * Disposes the resources of the material.
  44753. * @param forceDisposeEffect - Forces the disposal of effects.
  44754. * @param forceDisposeTextures - Forces the disposal of all textures.
  44755. */
  44756. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44757. if (forceDisposeTextures) {
  44758. if (this._albedoTexture) {
  44759. this._albedoTexture.dispose();
  44760. }
  44761. if (this._ambientTexture) {
  44762. this._ambientTexture.dispose();
  44763. }
  44764. if (this._opacityTexture) {
  44765. this._opacityTexture.dispose();
  44766. }
  44767. if (this._reflectionTexture) {
  44768. this._reflectionTexture.dispose();
  44769. }
  44770. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44771. this._environmentBRDFTexture.dispose();
  44772. }
  44773. if (this._emissiveTexture) {
  44774. this._emissiveTexture.dispose();
  44775. }
  44776. if (this._metallicTexture) {
  44777. this._metallicTexture.dispose();
  44778. }
  44779. if (this._reflectivityTexture) {
  44780. this._reflectivityTexture.dispose();
  44781. }
  44782. if (this._bumpTexture) {
  44783. this._bumpTexture.dispose();
  44784. }
  44785. if (this._lightmapTexture) {
  44786. this._lightmapTexture.dispose();
  44787. }
  44788. if (this._refractionTexture) {
  44789. this._refractionTexture.dispose();
  44790. }
  44791. }
  44792. this._renderTargets.dispose();
  44793. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44794. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44795. }
  44796. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44797. };
  44798. /**
  44799. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44800. */
  44801. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44802. /**
  44803. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44804. * to enhance interoperability with other engines.
  44805. */
  44806. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44807. /**
  44808. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44809. * to enhance interoperability with other materials.
  44810. */
  44811. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44812. /**
  44813. * Stores the reflectivity values based on metallic roughness workflow.
  44814. */
  44815. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44816. __decorate([
  44817. BABYLON.serializeAsImageProcessingConfiguration()
  44818. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44819. __decorate([
  44820. BABYLON.serialize()
  44821. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44822. __decorate([
  44823. BABYLON.serialize()
  44824. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44825. return PBRBaseMaterial;
  44826. }(BABYLON.PushMaterial));
  44827. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44828. })(BABYLON || (BABYLON = {}));
  44829. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44830. var BABYLON;
  44831. (function (BABYLON) {
  44832. /**
  44833. * The Physically based simple base material of BJS.
  44834. *
  44835. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44836. * It is used as the base class for both the specGloss and metalRough conventions.
  44837. */
  44838. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44839. __extends(PBRBaseSimpleMaterial, _super);
  44840. /**
  44841. * Instantiates a new PBRMaterial instance.
  44842. *
  44843. * @param name The material name
  44844. * @param scene The scene the material will be use in.
  44845. */
  44846. function PBRBaseSimpleMaterial(name, scene) {
  44847. var _this = _super.call(this, name, scene) || this;
  44848. /**
  44849. * Number of Simultaneous lights allowed on the material.
  44850. */
  44851. _this.maxSimultaneousLights = 4;
  44852. /**
  44853. * If sets to true, disables all the lights affecting the material.
  44854. */
  44855. _this.disableLighting = false;
  44856. /**
  44857. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44858. */
  44859. _this.invertNormalMapX = false;
  44860. /**
  44861. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44862. */
  44863. _this.invertNormalMapY = false;
  44864. /**
  44865. * Emissivie color used to self-illuminate the model.
  44866. */
  44867. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44868. /**
  44869. * Occlusion Channel Strenght.
  44870. */
  44871. _this.occlusionStrength = 1.0;
  44872. _this.useLightmapAsShadowmap = false;
  44873. _this._useAlphaFromAlbedoTexture = true;
  44874. _this._useAmbientInGrayScale = true;
  44875. return _this;
  44876. }
  44877. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44878. /**
  44879. * Gets the current double sided mode.
  44880. */
  44881. get: function () {
  44882. return this._twoSidedLighting;
  44883. },
  44884. /**
  44885. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44886. */
  44887. set: function (value) {
  44888. if (this._twoSidedLighting === value) {
  44889. return;
  44890. }
  44891. this._twoSidedLighting = value;
  44892. this.backFaceCulling = !value;
  44893. this._markAllSubMeshesAsTexturesDirty();
  44894. },
  44895. enumerable: true,
  44896. configurable: true
  44897. });
  44898. /**
  44899. * Return the active textures of the material.
  44900. */
  44901. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44902. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44903. if (this.environmentTexture) {
  44904. activeTextures.push(this.environmentTexture);
  44905. }
  44906. if (this.normalTexture) {
  44907. activeTextures.push(this.normalTexture);
  44908. }
  44909. if (this.emissiveTexture) {
  44910. activeTextures.push(this.emissiveTexture);
  44911. }
  44912. if (this.occlusionTexture) {
  44913. activeTextures.push(this.occlusionTexture);
  44914. }
  44915. if (this.lightmapTexture) {
  44916. activeTextures.push(this.lightmapTexture);
  44917. }
  44918. return activeTextures;
  44919. };
  44920. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44921. if (_super.prototype.hasTexture.call(this, texture)) {
  44922. return true;
  44923. }
  44924. if (this.lightmapTexture === texture) {
  44925. return true;
  44926. }
  44927. return false;
  44928. };
  44929. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44930. return "PBRBaseSimpleMaterial";
  44931. };
  44932. __decorate([
  44933. BABYLON.serialize(),
  44934. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44935. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44936. __decorate([
  44937. BABYLON.serialize(),
  44938. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44939. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44940. __decorate([
  44941. BABYLON.serializeAsTexture(),
  44942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44943. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44944. __decorate([
  44945. BABYLON.serialize(),
  44946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44947. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44948. __decorate([
  44949. BABYLON.serialize(),
  44950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44951. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44952. __decorate([
  44953. BABYLON.serializeAsTexture(),
  44954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44955. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44956. __decorate([
  44957. BABYLON.serializeAsColor3("emissive"),
  44958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44959. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44960. __decorate([
  44961. BABYLON.serializeAsTexture(),
  44962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44963. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44964. __decorate([
  44965. BABYLON.serialize(),
  44966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44967. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44968. __decorate([
  44969. BABYLON.serializeAsTexture(),
  44970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44971. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44972. __decorate([
  44973. BABYLON.serialize(),
  44974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44975. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44976. __decorate([
  44977. BABYLON.serialize()
  44978. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44979. __decorate([
  44980. BABYLON.serializeAsTexture(),
  44981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44982. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44983. __decorate([
  44984. BABYLON.serialize(),
  44985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44986. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44987. return PBRBaseSimpleMaterial;
  44988. }(BABYLON.PBRBaseMaterial));
  44989. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44990. })(BABYLON || (BABYLON = {}));
  44991. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44992. var BABYLON;
  44993. (function (BABYLON) {
  44994. /**
  44995. * The Physically based material of BJS.
  44996. *
  44997. * This offers the main features of a standard PBR material.
  44998. * For more information, please refer to the documentation :
  44999. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45000. */
  45001. var PBRMaterial = /** @class */ (function (_super) {
  45002. __extends(PBRMaterial, _super);
  45003. /**
  45004. * Instantiates a new PBRMaterial instance.
  45005. *
  45006. * @param name The material name
  45007. * @param scene The scene the material will be use in.
  45008. */
  45009. function PBRMaterial(name, scene) {
  45010. var _this = _super.call(this, name, scene) || this;
  45011. /**
  45012. * Intensity of the direct lights e.g. the four lights available in your scene.
  45013. * This impacts both the direct diffuse and specular highlights.
  45014. */
  45015. _this.directIntensity = 1.0;
  45016. /**
  45017. * Intensity of the emissive part of the material.
  45018. * This helps controlling the emissive effect without modifying the emissive color.
  45019. */
  45020. _this.emissiveIntensity = 1.0;
  45021. /**
  45022. * Intensity of the environment e.g. how much the environment will light the object
  45023. * either through harmonics for rough material or through the refelction for shiny ones.
  45024. */
  45025. _this.environmentIntensity = 1.0;
  45026. /**
  45027. * This is a special control allowing the reduction of the specular highlights coming from the
  45028. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45029. */
  45030. _this.specularIntensity = 1.0;
  45031. /**
  45032. * Debug Control allowing disabling the bump map on this material.
  45033. */
  45034. _this.disableBumpMap = false;
  45035. /**
  45036. * AKA Occlusion Texture Intensity in other nomenclature.
  45037. */
  45038. _this.ambientTextureStrength = 1.0;
  45039. /**
  45040. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45041. * 1 means it completely occludes it
  45042. * 0 mean it has no impact
  45043. */
  45044. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45045. /**
  45046. * The color of a material in ambient lighting.
  45047. */
  45048. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45049. /**
  45050. * AKA Diffuse Color in other nomenclature.
  45051. */
  45052. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45053. /**
  45054. * AKA Specular Color in other nomenclature.
  45055. */
  45056. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45057. /**
  45058. * The color reflected from the material.
  45059. */
  45060. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45061. /**
  45062. * The color emitted from the material.
  45063. */
  45064. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45065. /**
  45066. * AKA Glossiness in other nomenclature.
  45067. */
  45068. _this.microSurface = 1.0;
  45069. /**
  45070. * source material index of refraction (IOR)' / 'destination material IOR.
  45071. */
  45072. _this.indexOfRefraction = 0.66;
  45073. /**
  45074. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45075. */
  45076. _this.invertRefractionY = false;
  45077. /**
  45078. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45079. * Materials half opaque for instance using refraction could benefit from this control.
  45080. */
  45081. _this.linkRefractionWithTransparency = false;
  45082. _this.useLightmapAsShadowmap = false;
  45083. /**
  45084. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45085. */
  45086. _this.useAlphaFromAlbedoTexture = false;
  45087. /**
  45088. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45089. */
  45090. _this.forceAlphaTest = false;
  45091. /**
  45092. * Defines the alpha limits in alpha test mode.
  45093. */
  45094. _this.alphaCutOff = 0.4;
  45095. /**
  45096. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45097. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45098. */
  45099. _this.useSpecularOverAlpha = true;
  45100. /**
  45101. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45102. */
  45103. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45104. /**
  45105. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45106. */
  45107. _this.useRoughnessFromMetallicTextureAlpha = true;
  45108. /**
  45109. * Specifies if the metallic texture contains the roughness information in its green channel.
  45110. */
  45111. _this.useRoughnessFromMetallicTextureGreen = false;
  45112. /**
  45113. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45114. */
  45115. _this.useMetallnessFromMetallicTextureBlue = false;
  45116. /**
  45117. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45118. */
  45119. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45120. /**
  45121. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45122. */
  45123. _this.useAmbientInGrayScale = false;
  45124. /**
  45125. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45126. * The material will try to infer what glossiness each pixel should be.
  45127. */
  45128. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45129. /**
  45130. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45131. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45132. */
  45133. _this.useRadianceOverAlpha = true;
  45134. /**
  45135. * Allows using an object space normal map (instead of tangent space).
  45136. */
  45137. _this.useObjectSpaceNormalMap = false;
  45138. /**
  45139. * Allows using the bump map in parallax mode.
  45140. */
  45141. _this.useParallax = false;
  45142. /**
  45143. * Allows using the bump map in parallax occlusion mode.
  45144. */
  45145. _this.useParallaxOcclusion = false;
  45146. /**
  45147. * Controls the scale bias of the parallax mode.
  45148. */
  45149. _this.parallaxScaleBias = 0.05;
  45150. /**
  45151. * If sets to true, disables all the lights affecting the material.
  45152. */
  45153. _this.disableLighting = false;
  45154. /**
  45155. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45156. */
  45157. _this.forceIrradianceInFragment = false;
  45158. /**
  45159. * Number of Simultaneous lights allowed on the material.
  45160. */
  45161. _this.maxSimultaneousLights = 4;
  45162. /**
  45163. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45164. */
  45165. _this.invertNormalMapX = false;
  45166. /**
  45167. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45168. */
  45169. _this.invertNormalMapY = false;
  45170. /**
  45171. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45172. */
  45173. _this.twoSidedLighting = false;
  45174. /**
  45175. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45176. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45177. */
  45178. _this.useAlphaFresnel = false;
  45179. /**
  45180. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45181. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45182. */
  45183. _this.useLinearAlphaFresnel = false;
  45184. /**
  45185. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45186. * And/Or occlude the blended part.
  45187. */
  45188. _this.environmentBRDFTexture = null;
  45189. /**
  45190. * Force normal to face away from face.
  45191. */
  45192. _this.forceNormalForward = false;
  45193. /**
  45194. * Enables specular anti aliasing in the PBR shader.
  45195. * It will both interacts on the Geometry for analytical and IBL lighting.
  45196. * It also prefilter the roughness map based on the bump values.
  45197. */
  45198. _this.enableSpecularAntiAliasing = false;
  45199. /**
  45200. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45201. * makes the reflect vector face the model (under horizon).
  45202. */
  45203. _this.useHorizonOcclusion = true;
  45204. /**
  45205. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45206. * too much the area relying on ambient texture to define their ambient occlusion.
  45207. */
  45208. _this.useRadianceOcclusion = true;
  45209. /**
  45210. * If set to true, no lighting calculations will be applied.
  45211. */
  45212. _this.unlit = false;
  45213. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45214. return _this;
  45215. }
  45216. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45217. /**
  45218. * BJS is using an harcoded light falloff based on a manually sets up range.
  45219. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45220. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45221. */
  45222. get: function () {
  45223. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45224. },
  45225. /**
  45226. * BJS is using an harcoded light falloff based on a manually sets up range.
  45227. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45228. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45229. */
  45230. set: function (value) {
  45231. if (value !== this.usePhysicalLightFalloff) {
  45232. // Ensure the effect will be rebuilt.
  45233. this._markAllSubMeshesAsTexturesDirty();
  45234. if (value) {
  45235. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45236. }
  45237. else {
  45238. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45239. }
  45240. }
  45241. },
  45242. enumerable: true,
  45243. configurable: true
  45244. });
  45245. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45246. /**
  45247. * In order to support the falloff compatibility with gltf, a special mode has been added
  45248. * to reproduce the gltf light falloff.
  45249. */
  45250. get: function () {
  45251. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45252. },
  45253. /**
  45254. * In order to support the falloff compatibility with gltf, a special mode has been added
  45255. * to reproduce the gltf light falloff.
  45256. */
  45257. set: function (value) {
  45258. if (value !== this.useGLTFLightFalloff) {
  45259. // Ensure the effect will be rebuilt.
  45260. this._markAllSubMeshesAsTexturesDirty();
  45261. if (value) {
  45262. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45263. }
  45264. else {
  45265. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45266. }
  45267. }
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45273. /**
  45274. * Gets the image processing configuration used either in this material.
  45275. */
  45276. get: function () {
  45277. return this._imageProcessingConfiguration;
  45278. },
  45279. /**
  45280. * Sets the Default image processing configuration used either in the this material.
  45281. *
  45282. * If sets to null, the scene one is in use.
  45283. */
  45284. set: function (value) {
  45285. this._attachImageProcessingConfiguration(value);
  45286. // Ensure the effect will be rebuilt.
  45287. this._markAllSubMeshesAsTexturesDirty();
  45288. },
  45289. enumerable: true,
  45290. configurable: true
  45291. });
  45292. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45293. /**
  45294. * Gets wether the color curves effect is enabled.
  45295. */
  45296. get: function () {
  45297. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45298. },
  45299. /**
  45300. * Sets wether the color curves effect is enabled.
  45301. */
  45302. set: function (value) {
  45303. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45304. },
  45305. enumerable: true,
  45306. configurable: true
  45307. });
  45308. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45309. /**
  45310. * Gets wether the color grading effect is enabled.
  45311. */
  45312. get: function () {
  45313. return this.imageProcessingConfiguration.colorGradingEnabled;
  45314. },
  45315. /**
  45316. * Gets wether the color grading effect is enabled.
  45317. */
  45318. set: function (value) {
  45319. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45320. },
  45321. enumerable: true,
  45322. configurable: true
  45323. });
  45324. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45325. /**
  45326. * Gets wether tonemapping is enabled or not.
  45327. */
  45328. get: function () {
  45329. return this._imageProcessingConfiguration.toneMappingEnabled;
  45330. },
  45331. /**
  45332. * Sets wether tonemapping is enabled or not
  45333. */
  45334. set: function (value) {
  45335. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45336. },
  45337. enumerable: true,
  45338. configurable: true
  45339. });
  45340. ;
  45341. ;
  45342. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45343. /**
  45344. * The camera exposure used on this material.
  45345. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45346. * This corresponds to a photographic exposure.
  45347. */
  45348. get: function () {
  45349. return this._imageProcessingConfiguration.exposure;
  45350. },
  45351. /**
  45352. * The camera exposure used on this material.
  45353. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45354. * This corresponds to a photographic exposure.
  45355. */
  45356. set: function (value) {
  45357. this._imageProcessingConfiguration.exposure = value;
  45358. },
  45359. enumerable: true,
  45360. configurable: true
  45361. });
  45362. ;
  45363. ;
  45364. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45365. /**
  45366. * Gets The camera contrast used on this material.
  45367. */
  45368. get: function () {
  45369. return this._imageProcessingConfiguration.contrast;
  45370. },
  45371. /**
  45372. * Sets The camera contrast used on this material.
  45373. */
  45374. set: function (value) {
  45375. this._imageProcessingConfiguration.contrast = value;
  45376. },
  45377. enumerable: true,
  45378. configurable: true
  45379. });
  45380. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45381. /**
  45382. * Gets the Color Grading 2D Lookup Texture.
  45383. */
  45384. get: function () {
  45385. return this._imageProcessingConfiguration.colorGradingTexture;
  45386. },
  45387. /**
  45388. * Sets the Color Grading 2D Lookup Texture.
  45389. */
  45390. set: function (value) {
  45391. this._imageProcessingConfiguration.colorGradingTexture = value;
  45392. },
  45393. enumerable: true,
  45394. configurable: true
  45395. });
  45396. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45397. /**
  45398. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45399. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45400. * 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;
  45401. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45402. */
  45403. get: function () {
  45404. return this._imageProcessingConfiguration.colorCurves;
  45405. },
  45406. /**
  45407. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45408. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45409. * 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;
  45410. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45411. */
  45412. set: function (value) {
  45413. this._imageProcessingConfiguration.colorCurves = value;
  45414. },
  45415. enumerable: true,
  45416. configurable: true
  45417. });
  45418. /**
  45419. * Returns the name of this material class.
  45420. */
  45421. PBRMaterial.prototype.getClassName = function () {
  45422. return "PBRMaterial";
  45423. };
  45424. /**
  45425. * Returns an array of the actively used textures.
  45426. * @returns - Array of BaseTextures
  45427. */
  45428. PBRMaterial.prototype.getActiveTextures = function () {
  45429. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45430. if (this._albedoTexture) {
  45431. activeTextures.push(this._albedoTexture);
  45432. }
  45433. if (this._ambientTexture) {
  45434. activeTextures.push(this._ambientTexture);
  45435. }
  45436. if (this._opacityTexture) {
  45437. activeTextures.push(this._opacityTexture);
  45438. }
  45439. if (this._reflectionTexture) {
  45440. activeTextures.push(this._reflectionTexture);
  45441. }
  45442. if (this._emissiveTexture) {
  45443. activeTextures.push(this._emissiveTexture);
  45444. }
  45445. if (this._reflectivityTexture) {
  45446. activeTextures.push(this._reflectivityTexture);
  45447. }
  45448. if (this._metallicTexture) {
  45449. activeTextures.push(this._metallicTexture);
  45450. }
  45451. if (this._microSurfaceTexture) {
  45452. activeTextures.push(this._microSurfaceTexture);
  45453. }
  45454. if (this._bumpTexture) {
  45455. activeTextures.push(this._bumpTexture);
  45456. }
  45457. if (this._lightmapTexture) {
  45458. activeTextures.push(this._lightmapTexture);
  45459. }
  45460. if (this._refractionTexture) {
  45461. activeTextures.push(this._refractionTexture);
  45462. }
  45463. return activeTextures;
  45464. };
  45465. /**
  45466. * Checks to see if a texture is used in the material.
  45467. * @param texture - Base texture to use.
  45468. * @returns - Boolean specifying if a texture is used in the material.
  45469. */
  45470. PBRMaterial.prototype.hasTexture = function (texture) {
  45471. if (_super.prototype.hasTexture.call(this, texture)) {
  45472. return true;
  45473. }
  45474. if (this._albedoTexture === texture) {
  45475. return true;
  45476. }
  45477. if (this._ambientTexture === texture) {
  45478. return true;
  45479. }
  45480. if (this._opacityTexture === texture) {
  45481. return true;
  45482. }
  45483. if (this._reflectionTexture === texture) {
  45484. return true;
  45485. }
  45486. if (this._reflectivityTexture === texture) {
  45487. return true;
  45488. }
  45489. if (this._metallicTexture === texture) {
  45490. return true;
  45491. }
  45492. if (this._microSurfaceTexture === texture) {
  45493. return true;
  45494. }
  45495. if (this._bumpTexture === texture) {
  45496. return true;
  45497. }
  45498. if (this._lightmapTexture === texture) {
  45499. return true;
  45500. }
  45501. if (this._refractionTexture === texture) {
  45502. return true;
  45503. }
  45504. return false;
  45505. };
  45506. /**
  45507. * Makes a duplicate of the current material.
  45508. * @param name - name to use for the new material.
  45509. */
  45510. PBRMaterial.prototype.clone = function (name) {
  45511. var _this = this;
  45512. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45513. clone.id = name;
  45514. clone.name = name;
  45515. return clone;
  45516. };
  45517. /**
  45518. * Serializes this PBR Material.
  45519. * @returns - An object with the serialized material.
  45520. */
  45521. PBRMaterial.prototype.serialize = function () {
  45522. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45523. serializationObject.customType = "BABYLON.PBRMaterial";
  45524. return serializationObject;
  45525. };
  45526. // Statics
  45527. /**
  45528. * Parses a PBR Material from a serialized object.
  45529. * @param source - Serialized object.
  45530. * @param scene - BJS scene instance.
  45531. * @param rootUrl - url for the scene object
  45532. * @returns - PBRMaterial
  45533. */
  45534. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45535. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45536. };
  45537. /**
  45538. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45539. */
  45540. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45541. /**
  45542. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45543. */
  45544. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45545. /**
  45546. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45547. */
  45548. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45549. /**
  45550. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45551. * They are also discarded below the alpha cutoff threshold to improve performances.
  45552. */
  45553. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45554. /**
  45555. * Defines the default value of how much AO map is occluding the analytical lights
  45556. * (point spot...).
  45557. */
  45558. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "directIntensity", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45578. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45579. __decorate([
  45580. BABYLON.serializeAsTexture(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45583. __decorate([
  45584. BABYLON.serializeAsTexture(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45586. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45595. __decorate([
  45596. BABYLON.serializeAsTexture(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45598. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45599. __decorate([
  45600. BABYLON.serializeAsTexture(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45603. __decorate([
  45604. BABYLON.serializeAsTexture(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45607. __decorate([
  45608. BABYLON.serializeAsTexture(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45611. __decorate([
  45612. BABYLON.serializeAsTexture(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "metallic", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "roughness", void 0);
  45623. __decorate([
  45624. BABYLON.serializeAsTexture(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45627. __decorate([
  45628. BABYLON.serializeAsTexture(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45631. __decorate([
  45632. BABYLON.serializeAsTexture(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45634. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45635. __decorate([
  45636. BABYLON.serializeAsTexture(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45638. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45639. __decorate([
  45640. BABYLON.serializeAsColor3("ambient"),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45642. ], PBRMaterial.prototype, "ambientColor", void 0);
  45643. __decorate([
  45644. BABYLON.serializeAsColor3("albedo"),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45646. ], PBRMaterial.prototype, "albedoColor", void 0);
  45647. __decorate([
  45648. BABYLON.serializeAsColor3("reflectivity"),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45650. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45651. __decorate([
  45652. BABYLON.serializeAsColor3("reflection"),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45654. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45655. __decorate([
  45656. BABYLON.serializeAsColor3("emissive"),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45658. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45659. __decorate([
  45660. BABYLON.serialize(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMaterial.prototype, "microSurface", void 0);
  45663. __decorate([
  45664. BABYLON.serialize(),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45666. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45667. __decorate([
  45668. BABYLON.serialize(),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45670. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45671. __decorate([
  45672. BABYLON.serialize(),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45674. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45675. __decorate([
  45676. BABYLON.serialize(),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45678. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45679. __decorate([
  45680. BABYLON.serialize(),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45682. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45686. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45687. __decorate([
  45688. BABYLON.serialize(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45690. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45691. __decorate([
  45692. BABYLON.serialize(),
  45693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45694. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45695. __decorate([
  45696. BABYLON.serialize(),
  45697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45698. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45699. __decorate([
  45700. BABYLON.serialize(),
  45701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45702. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45703. __decorate([
  45704. BABYLON.serialize(),
  45705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45706. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45707. __decorate([
  45708. BABYLON.serialize(),
  45709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45710. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45711. __decorate([
  45712. BABYLON.serialize(),
  45713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45714. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45715. __decorate([
  45716. BABYLON.serialize(),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45718. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45719. __decorate([
  45720. BABYLON.serialize(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45722. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45723. __decorate([
  45724. BABYLON.serialize()
  45725. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45726. __decorate([
  45727. BABYLON.serialize()
  45728. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45729. __decorate([
  45730. BABYLON.serialize(),
  45731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45732. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45733. __decorate([
  45734. BABYLON.serialize(),
  45735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45736. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45737. __decorate([
  45738. BABYLON.serialize(),
  45739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45740. ], PBRMaterial.prototype, "useParallax", void 0);
  45741. __decorate([
  45742. BABYLON.serialize(),
  45743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45744. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45745. __decorate([
  45746. BABYLON.serialize(),
  45747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45748. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45749. __decorate([
  45750. BABYLON.serialize(),
  45751. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45752. ], PBRMaterial.prototype, "disableLighting", void 0);
  45753. __decorate([
  45754. BABYLON.serialize(),
  45755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45756. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45757. __decorate([
  45758. BABYLON.serialize(),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45760. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45764. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45765. __decorate([
  45766. BABYLON.serialize(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45768. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45769. __decorate([
  45770. BABYLON.serialize(),
  45771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45772. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45773. __decorate([
  45774. BABYLON.serialize(),
  45775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45776. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45777. __decorate([
  45778. BABYLON.serialize(),
  45779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45780. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45781. __decorate([
  45782. BABYLON.serializeAsTexture(),
  45783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45784. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45785. __decorate([
  45786. BABYLON.serialize(),
  45787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45788. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45789. __decorate([
  45790. BABYLON.serialize(),
  45791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45792. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45793. __decorate([
  45794. BABYLON.serialize(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45796. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45797. __decorate([
  45798. BABYLON.serialize(),
  45799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45800. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45801. __decorate([
  45802. BABYLON.serialize(),
  45803. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45804. ], PBRMaterial.prototype, "unlit", void 0);
  45805. return PBRMaterial;
  45806. }(BABYLON.PBRBaseMaterial));
  45807. BABYLON.PBRMaterial = PBRMaterial;
  45808. })(BABYLON || (BABYLON = {}));
  45809. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45810. var BABYLON;
  45811. (function (BABYLON) {
  45812. /**
  45813. * The PBR material of BJS following the metal roughness convention.
  45814. *
  45815. * This fits to the PBR convention in the GLTF definition:
  45816. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45817. */
  45818. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45819. __extends(PBRMetallicRoughnessMaterial, _super);
  45820. /**
  45821. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45822. *
  45823. * @param name The material name
  45824. * @param scene The scene the material will be use in.
  45825. */
  45826. function PBRMetallicRoughnessMaterial(name, scene) {
  45827. var _this = _super.call(this, name, scene) || this;
  45828. _this._useRoughnessFromMetallicTextureAlpha = false;
  45829. _this._useRoughnessFromMetallicTextureGreen = true;
  45830. _this._useMetallnessFromMetallicTextureBlue = true;
  45831. _this.metallic = 1.0;
  45832. _this.roughness = 1.0;
  45833. return _this;
  45834. }
  45835. /**
  45836. * Return the currrent class name of the material.
  45837. */
  45838. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45839. return "PBRMetallicRoughnessMaterial";
  45840. };
  45841. /**
  45842. * Return the active textures of the material.
  45843. */
  45844. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45845. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45846. if (this.baseTexture) {
  45847. activeTextures.push(this.baseTexture);
  45848. }
  45849. if (this.metallicRoughnessTexture) {
  45850. activeTextures.push(this.metallicRoughnessTexture);
  45851. }
  45852. return activeTextures;
  45853. };
  45854. /**
  45855. * Checks to see if a texture is used in the material.
  45856. * @param texture - Base texture to use.
  45857. * @returns - Boolean specifying if a texture is used in the material.
  45858. */
  45859. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45860. if (_super.prototype.hasTexture.call(this, texture)) {
  45861. return true;
  45862. }
  45863. if (this.baseTexture === texture) {
  45864. return true;
  45865. }
  45866. if (this.metallicRoughnessTexture === texture) {
  45867. return true;
  45868. }
  45869. return false;
  45870. };
  45871. /**
  45872. * Makes a duplicate of the current material.
  45873. * @param name - name to use for the new material.
  45874. */
  45875. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45876. var _this = this;
  45877. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45878. clone.id = name;
  45879. clone.name = name;
  45880. return clone;
  45881. };
  45882. /**
  45883. * Serialize the material to a parsable JSON object.
  45884. */
  45885. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45886. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45887. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45888. return serializationObject;
  45889. };
  45890. /**
  45891. * Parses a JSON object correponding to the serialize function.
  45892. */
  45893. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45894. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45895. };
  45896. __decorate([
  45897. BABYLON.serializeAsColor3(),
  45898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45899. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45900. __decorate([
  45901. BABYLON.serializeAsTexture(),
  45902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45903. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45904. __decorate([
  45905. BABYLON.serialize(),
  45906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45907. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45908. __decorate([
  45909. BABYLON.serialize(),
  45910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45911. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45912. __decorate([
  45913. BABYLON.serializeAsTexture(),
  45914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45915. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45916. return PBRMetallicRoughnessMaterial;
  45917. }(BABYLON.PBRBaseSimpleMaterial));
  45918. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45919. })(BABYLON || (BABYLON = {}));
  45920. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45921. var BABYLON;
  45922. (function (BABYLON) {
  45923. /**
  45924. * The PBR material of BJS following the specular glossiness convention.
  45925. *
  45926. * This fits to the PBR convention in the GLTF definition:
  45927. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45928. */
  45929. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45930. __extends(PBRSpecularGlossinessMaterial, _super);
  45931. /**
  45932. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45933. *
  45934. * @param name The material name
  45935. * @param scene The scene the material will be use in.
  45936. */
  45937. function PBRSpecularGlossinessMaterial(name, scene) {
  45938. var _this = _super.call(this, name, scene) || this;
  45939. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45940. return _this;
  45941. }
  45942. /**
  45943. * Return the currrent class name of the material.
  45944. */
  45945. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45946. return "PBRSpecularGlossinessMaterial";
  45947. };
  45948. /**
  45949. * Return the active textures of the material.
  45950. */
  45951. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45952. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45953. if (this.diffuseTexture) {
  45954. activeTextures.push(this.diffuseTexture);
  45955. }
  45956. if (this.specularGlossinessTexture) {
  45957. activeTextures.push(this.specularGlossinessTexture);
  45958. }
  45959. return activeTextures;
  45960. };
  45961. /**
  45962. * Checks to see if a texture is used in the material.
  45963. * @param texture - Base texture to use.
  45964. * @returns - Boolean specifying if a texture is used in the material.
  45965. */
  45966. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45967. if (_super.prototype.hasTexture.call(this, texture)) {
  45968. return true;
  45969. }
  45970. if (this.diffuseTexture === texture) {
  45971. return true;
  45972. }
  45973. if (this.specularGlossinessTexture === texture) {
  45974. return true;
  45975. }
  45976. return false;
  45977. };
  45978. /**
  45979. * Makes a duplicate of the current material.
  45980. * @param name - name to use for the new material.
  45981. */
  45982. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45983. var _this = this;
  45984. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45985. clone.id = name;
  45986. clone.name = name;
  45987. return clone;
  45988. };
  45989. /**
  45990. * Serialize the material to a parsable JSON object.
  45991. */
  45992. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45993. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45994. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45995. return serializationObject;
  45996. };
  45997. /**
  45998. * Parses a JSON object correponding to the serialize function.
  45999. */
  46000. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46001. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46002. };
  46003. __decorate([
  46004. BABYLON.serializeAsColor3("diffuse"),
  46005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46006. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46007. __decorate([
  46008. BABYLON.serializeAsTexture(),
  46009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46010. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46011. __decorate([
  46012. BABYLON.serializeAsColor3("specular"),
  46013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46014. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46015. __decorate([
  46016. BABYLON.serialize(),
  46017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46018. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46019. __decorate([
  46020. BABYLON.serializeAsTexture(),
  46021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46022. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46023. return PBRSpecularGlossinessMaterial;
  46024. }(BABYLON.PBRBaseSimpleMaterial));
  46025. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46026. })(BABYLON || (BABYLON = {}));
  46027. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46028. var BABYLON;
  46029. (function (BABYLON) {
  46030. /**
  46031. * This is a list of all the different input types that are available in the application.
  46032. * Fo instance: ArcRotateCameraGamepadInput...
  46033. */
  46034. BABYLON.CameraInputTypes = {};
  46035. /**
  46036. * This represents the input manager used within a camera.
  46037. * It helps dealing with all the different kind of input attached to a camera.
  46038. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46039. */
  46040. var CameraInputsManager = /** @class */ (function () {
  46041. /**
  46042. * Instantiate a new Camera Input Manager.
  46043. * @param camera Defines the camera the input manager blongs to
  46044. */
  46045. function CameraInputsManager(camera) {
  46046. this.attached = {};
  46047. this.camera = camera;
  46048. this.checkInputs = function () { };
  46049. }
  46050. /**
  46051. * Add an input method to a camera
  46052. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46053. * @param input camera input method
  46054. */
  46055. CameraInputsManager.prototype.add = function (input) {
  46056. var type = input.getSimpleName();
  46057. if (this.attached[type]) {
  46058. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46059. return;
  46060. }
  46061. this.attached[type] = input;
  46062. input.camera = this.camera;
  46063. //for checkInputs, we are dynamically creating a function
  46064. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46065. if (input.checkInputs) {
  46066. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46067. }
  46068. if (this.attachedElement) {
  46069. input.attachControl(this.attachedElement);
  46070. }
  46071. };
  46072. /**
  46073. * Remove a specific input method from a camera
  46074. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46075. * @param inputToRemove camera input method
  46076. */
  46077. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46078. for (var cam in this.attached) {
  46079. var input = this.attached[cam];
  46080. if (input === inputToRemove) {
  46081. input.detachControl(this.attachedElement);
  46082. input.camera = null;
  46083. delete this.attached[cam];
  46084. this.rebuildInputCheck();
  46085. }
  46086. }
  46087. };
  46088. /**
  46089. * Remove a specific input type from a camera
  46090. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46091. * @param inputType the type of the input to remove
  46092. */
  46093. CameraInputsManager.prototype.removeByType = function (inputType) {
  46094. for (var cam in this.attached) {
  46095. var input = this.attached[cam];
  46096. if (input.getClassName() === inputType) {
  46097. input.detachControl(this.attachedElement);
  46098. input.camera = null;
  46099. delete this.attached[cam];
  46100. this.rebuildInputCheck();
  46101. }
  46102. }
  46103. };
  46104. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46105. var current = this.checkInputs;
  46106. return function () {
  46107. current();
  46108. fn();
  46109. };
  46110. };
  46111. /**
  46112. * Attach the input controls to the currently attached dom element to listen the events from.
  46113. * @param input Defines the input to attach
  46114. */
  46115. CameraInputsManager.prototype.attachInput = function (input) {
  46116. if (this.attachedElement) {
  46117. input.attachControl(this.attachedElement, this.noPreventDefault);
  46118. }
  46119. };
  46120. /**
  46121. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46122. * @param element Defines the dom element to collect the events from
  46123. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46124. */
  46125. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46126. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46127. if (this.attachedElement) {
  46128. return;
  46129. }
  46130. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46131. this.attachedElement = element;
  46132. this.noPreventDefault = noPreventDefault;
  46133. for (var cam in this.attached) {
  46134. this.attached[cam].attachControl(element, noPreventDefault);
  46135. }
  46136. };
  46137. /**
  46138. * Detach the current manager inputs controls from a specific dom element.
  46139. * @param element Defines the dom element to collect the events from
  46140. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46141. */
  46142. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46143. if (disconnect === void 0) { disconnect = false; }
  46144. if (this.attachedElement !== element) {
  46145. return;
  46146. }
  46147. for (var cam in this.attached) {
  46148. this.attached[cam].detachControl(element);
  46149. if (disconnect) {
  46150. this.attached[cam].camera = null;
  46151. }
  46152. }
  46153. this.attachedElement = null;
  46154. };
  46155. /**
  46156. * Rebuild the dynamic inputCheck function from the current list of
  46157. * defined inputs in the manager.
  46158. */
  46159. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46160. this.checkInputs = function () { };
  46161. for (var cam in this.attached) {
  46162. var input = this.attached[cam];
  46163. if (input.checkInputs) {
  46164. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46165. }
  46166. }
  46167. };
  46168. /**
  46169. * Remove all attached input methods from a camera
  46170. */
  46171. CameraInputsManager.prototype.clear = function () {
  46172. if (this.attachedElement) {
  46173. this.detachElement(this.attachedElement, true);
  46174. }
  46175. this.attached = {};
  46176. this.attachedElement = null;
  46177. this.checkInputs = function () { };
  46178. };
  46179. /**
  46180. * Serialize the current input manager attached to a camera.
  46181. * This ensures than once parsed,
  46182. * the input associated to the camera will be identical to the current ones
  46183. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46184. */
  46185. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46186. var inputs = {};
  46187. for (var cam in this.attached) {
  46188. var input = this.attached[cam];
  46189. var res = BABYLON.SerializationHelper.Serialize(input);
  46190. inputs[input.getClassName()] = res;
  46191. }
  46192. serializedCamera.inputsmgr = inputs;
  46193. };
  46194. /**
  46195. * Parses an input manager serialized JSON to restore the previous list of inputs
  46196. * and states associated to a camera.
  46197. * @param parsedCamera Defines the JSON to parse
  46198. */
  46199. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46200. var parsedInputs = parsedCamera.inputsmgr;
  46201. if (parsedInputs) {
  46202. this.clear();
  46203. for (var n in parsedInputs) {
  46204. var construct = BABYLON.CameraInputTypes[n];
  46205. if (construct) {
  46206. var parsedinput = parsedInputs[n];
  46207. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46208. this.add(input);
  46209. }
  46210. }
  46211. }
  46212. else {
  46213. //2016-03-08 this part is for managing backward compatibility
  46214. for (var n in this.attached) {
  46215. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46216. if (construct) {
  46217. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46218. this.remove(this.attached[n]);
  46219. this.add(input);
  46220. }
  46221. }
  46222. }
  46223. };
  46224. return CameraInputsManager;
  46225. }());
  46226. BABYLON.CameraInputsManager = CameraInputsManager;
  46227. })(BABYLON || (BABYLON = {}));
  46228. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46229. var BABYLON;
  46230. (function (BABYLON) {
  46231. /**
  46232. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46233. * This is the base of the follow, arc rotate cameras and Free camera
  46234. * @see http://doc.babylonjs.com/features/cameras
  46235. */
  46236. var TargetCamera = /** @class */ (function (_super) {
  46237. __extends(TargetCamera, _super);
  46238. /**
  46239. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46240. * This is the base of the follow, arc rotate cameras and Free camera
  46241. * @see http://doc.babylonjs.com/features/cameras
  46242. * @param name Defines the name of the camera in the scene
  46243. * @param position Defines the start position of the camera in the scene
  46244. * @param scene Defines the scene the camera belongs to
  46245. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46246. */
  46247. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46248. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46249. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46250. /**
  46251. * Define the current direction the camera is moving to
  46252. */
  46253. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46254. /**
  46255. * Define the current rotation the camera is rotating to
  46256. */
  46257. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46258. /**
  46259. * Define the current rotation of the camera
  46260. */
  46261. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46262. /**
  46263. * Define the current speed of the camera
  46264. */
  46265. _this.speed = 2.0;
  46266. /**
  46267. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46268. * around all axis.
  46269. */
  46270. _this.noRotationConstraint = false;
  46271. /**
  46272. * Define the current target of the camera as an object or a position.
  46273. */
  46274. _this.lockedTarget = null;
  46275. /** @hidden */
  46276. _this._currentTarget = BABYLON.Vector3.Zero();
  46277. /** @hidden */
  46278. _this._viewMatrix = BABYLON.Matrix.Zero();
  46279. /** @hidden */
  46280. _this._camMatrix = BABYLON.Matrix.Zero();
  46281. /** @hidden */
  46282. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46283. /** @hidden */
  46284. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46285. /** @hidden */
  46286. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46287. /** @hidden */
  46288. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46289. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46290. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46291. _this._defaultUp = BABYLON.Vector3.Up();
  46292. _this._cachedRotationZ = 0;
  46293. return _this;
  46294. }
  46295. /**
  46296. * Gets the position in front of the camera at a given distance.
  46297. * @param distance The distance from the camera we want the position to be
  46298. * @returns the position
  46299. */
  46300. TargetCamera.prototype.getFrontPosition = function (distance) {
  46301. this.getWorldMatrix();
  46302. var direction = this.getTarget().subtract(this.position);
  46303. direction.normalize();
  46304. direction.scaleInPlace(distance);
  46305. return this.globalPosition.add(direction);
  46306. };
  46307. /** @hidden */
  46308. TargetCamera.prototype._getLockedTargetPosition = function () {
  46309. if (!this.lockedTarget) {
  46310. return null;
  46311. }
  46312. if (this.lockedTarget.absolutePosition) {
  46313. this.lockedTarget.computeWorldMatrix();
  46314. }
  46315. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46316. };
  46317. /**
  46318. * Store current camera state of the camera (fov, position, rotation, etc..)
  46319. * @returns the camera
  46320. */
  46321. TargetCamera.prototype.storeState = function () {
  46322. this._storedPosition = this.position.clone();
  46323. this._storedRotation = this.rotation.clone();
  46324. if (this.rotationQuaternion) {
  46325. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46326. }
  46327. return _super.prototype.storeState.call(this);
  46328. };
  46329. /**
  46330. * Restored camera state. You must call storeState() first
  46331. * @returns whether it was successful or not
  46332. * @hidden
  46333. */
  46334. TargetCamera.prototype._restoreStateValues = function () {
  46335. if (!_super.prototype._restoreStateValues.call(this)) {
  46336. return false;
  46337. }
  46338. this.position = this._storedPosition.clone();
  46339. this.rotation = this._storedRotation.clone();
  46340. if (this.rotationQuaternion) {
  46341. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46342. }
  46343. this.cameraDirection.copyFromFloats(0, 0, 0);
  46344. this.cameraRotation.copyFromFloats(0, 0);
  46345. return true;
  46346. };
  46347. /** @hidden */
  46348. TargetCamera.prototype._initCache = function () {
  46349. _super.prototype._initCache.call(this);
  46350. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46351. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46352. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46353. };
  46354. /** @hidden */
  46355. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46356. if (!ignoreParentClass) {
  46357. _super.prototype._updateCache.call(this);
  46358. }
  46359. var lockedTargetPosition = this._getLockedTargetPosition();
  46360. if (!lockedTargetPosition) {
  46361. this._cache.lockedTarget = null;
  46362. }
  46363. else {
  46364. if (!this._cache.lockedTarget) {
  46365. this._cache.lockedTarget = lockedTargetPosition.clone();
  46366. }
  46367. else {
  46368. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46369. }
  46370. }
  46371. this._cache.rotation.copyFrom(this.rotation);
  46372. if (this.rotationQuaternion)
  46373. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46374. };
  46375. // Synchronized
  46376. /** @hidden */
  46377. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46378. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46379. return false;
  46380. }
  46381. var lockedTargetPosition = this._getLockedTargetPosition();
  46382. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46383. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46384. };
  46385. // Methods
  46386. /** @hidden */
  46387. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46388. var engine = this.getEngine();
  46389. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46390. };
  46391. // Target
  46392. /** @hidden */
  46393. TargetCamera.prototype.setTarget = function (target) {
  46394. this.upVector.normalize();
  46395. if (this.position.z === target.z) {
  46396. this.position.z += BABYLON.Epsilon;
  46397. }
  46398. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46399. this._camMatrix.invert();
  46400. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46401. var vDir = target.subtract(this.position);
  46402. if (vDir.x >= 0.0) {
  46403. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46404. }
  46405. else {
  46406. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46407. }
  46408. this.rotation.z = 0;
  46409. if (isNaN(this.rotation.x)) {
  46410. this.rotation.x = 0;
  46411. }
  46412. if (isNaN(this.rotation.y)) {
  46413. this.rotation.y = 0;
  46414. }
  46415. if (isNaN(this.rotation.z)) {
  46416. this.rotation.z = 0;
  46417. }
  46418. if (this.rotationQuaternion) {
  46419. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46420. }
  46421. };
  46422. /**
  46423. * Return the current target position of the camera. This value is expressed in local space.
  46424. * @returns the target position
  46425. */
  46426. TargetCamera.prototype.getTarget = function () {
  46427. return this._currentTarget;
  46428. };
  46429. /** @hidden */
  46430. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46431. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46432. };
  46433. /** @hidden */
  46434. TargetCamera.prototype._updatePosition = function () {
  46435. if (this.parent) {
  46436. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46437. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46438. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46439. return;
  46440. }
  46441. this.position.addInPlace(this.cameraDirection);
  46442. };
  46443. /** @hidden */
  46444. TargetCamera.prototype._checkInputs = function () {
  46445. var needToMove = this._decideIfNeedsToMove();
  46446. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46447. // Move
  46448. if (needToMove) {
  46449. this._updatePosition();
  46450. }
  46451. // Rotate
  46452. if (needToRotate) {
  46453. this.rotation.x += this.cameraRotation.x;
  46454. this.rotation.y += this.cameraRotation.y;
  46455. //rotate, if quaternion is set and rotation was used
  46456. if (this.rotationQuaternion) {
  46457. var len = this.rotation.lengthSquared();
  46458. if (len) {
  46459. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46460. }
  46461. }
  46462. if (!this.noRotationConstraint) {
  46463. var limit = (Math.PI / 2) * 0.95;
  46464. if (this.rotation.x > limit)
  46465. this.rotation.x = limit;
  46466. if (this.rotation.x < -limit)
  46467. this.rotation.x = -limit;
  46468. }
  46469. }
  46470. // Inertia
  46471. if (needToMove) {
  46472. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46473. this.cameraDirection.x = 0;
  46474. }
  46475. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46476. this.cameraDirection.y = 0;
  46477. }
  46478. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46479. this.cameraDirection.z = 0;
  46480. }
  46481. this.cameraDirection.scaleInPlace(this.inertia);
  46482. }
  46483. if (needToRotate) {
  46484. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46485. this.cameraRotation.x = 0;
  46486. }
  46487. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46488. this.cameraRotation.y = 0;
  46489. }
  46490. this.cameraRotation.scaleInPlace(this.inertia);
  46491. }
  46492. _super.prototype._checkInputs.call(this);
  46493. };
  46494. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46495. if (this.rotationQuaternion) {
  46496. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46497. }
  46498. else {
  46499. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46500. }
  46501. };
  46502. /**
  46503. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46504. * @returns the current camera
  46505. */
  46506. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46507. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46508. return this;
  46509. };
  46510. /** @hidden */
  46511. TargetCamera.prototype._getViewMatrix = function () {
  46512. if (this.lockedTarget) {
  46513. this.setTarget(this._getLockedTargetPosition());
  46514. }
  46515. // Compute
  46516. this._updateCameraRotationMatrix();
  46517. // Apply the changed rotation to the upVector.
  46518. if (this._cachedRotationZ != this.rotation.z) {
  46519. this._rotateUpVectorWithCameraRotationMatrix();
  46520. this._cachedRotationZ = this.rotation.z;
  46521. }
  46522. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46523. // Computing target and final matrix
  46524. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46525. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46526. return this._viewMatrix;
  46527. };
  46528. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46529. if (this.parent) {
  46530. var parentWorldMatrix = this.parent.getWorldMatrix();
  46531. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46532. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46533. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46534. this._markSyncedWithParent();
  46535. }
  46536. else {
  46537. this._globalPosition.copyFrom(position);
  46538. this._globalCurrentTarget.copyFrom(target);
  46539. this._globalCurrentUpVector.copyFrom(up);
  46540. }
  46541. if (this.getScene().useRightHandedSystem) {
  46542. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46543. }
  46544. else {
  46545. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46546. }
  46547. };
  46548. /**
  46549. * @hidden
  46550. */
  46551. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46552. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46553. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46554. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46555. if (!this.rotationQuaternion) {
  46556. this.rotationQuaternion = new BABYLON.Quaternion();
  46557. }
  46558. rigCamera._cameraRigParams = {};
  46559. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46560. }
  46561. return rigCamera;
  46562. }
  46563. return null;
  46564. };
  46565. /**
  46566. * @hidden
  46567. */
  46568. TargetCamera.prototype._updateRigCameras = function () {
  46569. var camLeft = this._rigCameras[0];
  46570. var camRight = this._rigCameras[1];
  46571. switch (this.cameraRigMode) {
  46572. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46573. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46575. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46576. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46577. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46578. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46579. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46580. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46581. camLeft.setTarget(this.getTarget());
  46582. camRight.setTarget(this.getTarget());
  46583. break;
  46584. case BABYLON.Camera.RIG_MODE_VR:
  46585. if (camLeft.rotationQuaternion) {
  46586. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46587. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46588. }
  46589. else {
  46590. camLeft.rotation.copyFrom(this.rotation);
  46591. camRight.rotation.copyFrom(this.rotation);
  46592. }
  46593. camLeft.position.copyFrom(this.position);
  46594. camRight.position.copyFrom(this.position);
  46595. break;
  46596. }
  46597. _super.prototype._updateRigCameras.call(this);
  46598. };
  46599. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46600. if (!this._rigCamTransformMatrix) {
  46601. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46602. }
  46603. var target = this.getTarget();
  46604. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46605. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46606. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46607. };
  46608. /**
  46609. * Gets the current object class name.
  46610. * @return the class name
  46611. */
  46612. TargetCamera.prototype.getClassName = function () {
  46613. return "TargetCamera";
  46614. };
  46615. __decorate([
  46616. BABYLON.serializeAsVector3()
  46617. ], TargetCamera.prototype, "rotation", void 0);
  46618. __decorate([
  46619. BABYLON.serialize()
  46620. ], TargetCamera.prototype, "speed", void 0);
  46621. __decorate([
  46622. BABYLON.serializeAsMeshReference("lockedTargetId")
  46623. ], TargetCamera.prototype, "lockedTarget", void 0);
  46624. return TargetCamera;
  46625. }(BABYLON.Camera));
  46626. BABYLON.TargetCamera = TargetCamera;
  46627. })(BABYLON || (BABYLON = {}));
  46628. //# sourceMappingURL=babylon.targetCamera.js.map
  46629. var BABYLON;
  46630. (function (BABYLON) {
  46631. /**
  46632. * Manage the mouse inputs to control the movement of a free camera.
  46633. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46634. */
  46635. var FreeCameraMouseInput = /** @class */ (function () {
  46636. /**
  46637. * Manage the mouse inputs to control the movement of a free camera.
  46638. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46639. * @param touchEnabled Defines if touch is enabled or not
  46640. */
  46641. function FreeCameraMouseInput(
  46642. /**
  46643. * Define if touch is enabled in the mouse input
  46644. */
  46645. touchEnabled) {
  46646. if (touchEnabled === void 0) { touchEnabled = true; }
  46647. this.touchEnabled = touchEnabled;
  46648. /**
  46649. * Defines the buttons associated with the input to handle camera move.
  46650. */
  46651. this.buttons = [0, 1, 2];
  46652. /**
  46653. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  46654. */
  46655. this.angularSensibility = 2000.0;
  46656. this.previousPosition = null;
  46657. }
  46658. /**
  46659. * Attach the input controls to a specific dom element to get the input from.
  46660. * @param element Defines the element the controls should be listened from
  46661. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46662. */
  46663. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46664. var _this = this;
  46665. var engine = this.camera.getEngine();
  46666. if (!this._pointerInput) {
  46667. this._pointerInput = function (p, s) {
  46668. var evt = p.event;
  46669. if (engine.isInVRExclusivePointerMode) {
  46670. return;
  46671. }
  46672. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46673. return;
  46674. }
  46675. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46676. return;
  46677. }
  46678. var srcElement = (evt.srcElement || evt.target);
  46679. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46680. try {
  46681. srcElement.setPointerCapture(evt.pointerId);
  46682. }
  46683. catch (e) {
  46684. //Nothing to do with the error. Execution will continue.
  46685. }
  46686. _this.previousPosition = {
  46687. x: evt.clientX,
  46688. y: evt.clientY
  46689. };
  46690. if (!noPreventDefault) {
  46691. evt.preventDefault();
  46692. element.focus();
  46693. }
  46694. }
  46695. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46696. try {
  46697. srcElement.releasePointerCapture(evt.pointerId);
  46698. }
  46699. catch (e) {
  46700. //Nothing to do with the error.
  46701. }
  46702. _this.previousPosition = null;
  46703. if (!noPreventDefault) {
  46704. evt.preventDefault();
  46705. }
  46706. }
  46707. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46708. if (!_this.previousPosition || engine.isPointerLock) {
  46709. return;
  46710. }
  46711. var offsetX = evt.clientX - _this.previousPosition.x;
  46712. if (_this.camera.getScene().useRightHandedSystem)
  46713. offsetX *= -1;
  46714. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46715. offsetX *= -1;
  46716. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46717. var offsetY = evt.clientY - _this.previousPosition.y;
  46718. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46719. _this.previousPosition = {
  46720. x: evt.clientX,
  46721. y: evt.clientY
  46722. };
  46723. if (!noPreventDefault) {
  46724. evt.preventDefault();
  46725. }
  46726. }
  46727. };
  46728. }
  46729. this._onMouseMove = function (evt) {
  46730. if (!engine.isPointerLock) {
  46731. return;
  46732. }
  46733. if (engine.isInVRExclusivePointerMode) {
  46734. return;
  46735. }
  46736. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46737. if (_this.camera.getScene().useRightHandedSystem)
  46738. offsetX *= -1;
  46739. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46740. offsetX *= -1;
  46741. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46742. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46743. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46744. _this.previousPosition = null;
  46745. if (!noPreventDefault) {
  46746. evt.preventDefault();
  46747. }
  46748. };
  46749. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46750. element.addEventListener("mousemove", this._onMouseMove, false);
  46751. };
  46752. /**
  46753. * Detach the current controls from the specified dom element.
  46754. * @param element Defines the element to stop listening the inputs from
  46755. */
  46756. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46757. if (this._observer && element) {
  46758. this.camera.getScene().onPointerObservable.remove(this._observer);
  46759. if (this._onMouseMove) {
  46760. element.removeEventListener("mousemove", this._onMouseMove);
  46761. }
  46762. this._observer = null;
  46763. this._onMouseMove = null;
  46764. this.previousPosition = null;
  46765. }
  46766. };
  46767. /**
  46768. * Gets the class name of the current intput.
  46769. * @returns the class name
  46770. */
  46771. FreeCameraMouseInput.prototype.getClassName = function () {
  46772. return "FreeCameraMouseInput";
  46773. };
  46774. /**
  46775. * Get the friendly name associated with the input class.
  46776. * @returns the input friendly name
  46777. */
  46778. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46779. return "mouse";
  46780. };
  46781. __decorate([
  46782. BABYLON.serialize()
  46783. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46784. __decorate([
  46785. BABYLON.serialize()
  46786. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46787. return FreeCameraMouseInput;
  46788. }());
  46789. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46790. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46791. })(BABYLON || (BABYLON = {}));
  46792. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46793. var BABYLON;
  46794. (function (BABYLON) {
  46795. /**
  46796. * Manage the keyboard inputs to control the movement of a free camera.
  46797. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46798. */
  46799. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46800. function FreeCameraKeyboardMoveInput() {
  46801. /**
  46802. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  46803. */
  46804. this.keysUp = [38];
  46805. /**
  46806. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  46807. */
  46808. this.keysDown = [40];
  46809. /**
  46810. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  46811. */
  46812. this.keysLeft = [37];
  46813. /**
  46814. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  46815. */
  46816. this.keysRight = [39];
  46817. this._keys = new Array();
  46818. }
  46819. /**
  46820. * Attach the input controls to a specific dom element to get the input from.
  46821. * @param element Defines the element the controls should be listened from
  46822. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46823. */
  46824. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46825. var _this = this;
  46826. if (this._onCanvasBlurObserver) {
  46827. return;
  46828. }
  46829. this._scene = this.camera.getScene();
  46830. this._engine = this._scene.getEngine();
  46831. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46832. _this._keys = [];
  46833. });
  46834. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46835. var evt = info.event;
  46836. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46837. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46838. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46839. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46840. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46841. var index = _this._keys.indexOf(evt.keyCode);
  46842. if (index === -1) {
  46843. _this._keys.push(evt.keyCode);
  46844. }
  46845. if (!noPreventDefault) {
  46846. evt.preventDefault();
  46847. }
  46848. }
  46849. }
  46850. else {
  46851. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46852. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46853. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46854. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46855. var index = _this._keys.indexOf(evt.keyCode);
  46856. if (index >= 0) {
  46857. _this._keys.splice(index, 1);
  46858. }
  46859. if (!noPreventDefault) {
  46860. evt.preventDefault();
  46861. }
  46862. }
  46863. }
  46864. });
  46865. };
  46866. /**
  46867. * Detach the current controls from the specified dom element.
  46868. * @param element Defines the element to stop listening the inputs from
  46869. */
  46870. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46871. if (this._scene) {
  46872. if (this._onKeyboardObserver) {
  46873. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46874. }
  46875. if (this._onCanvasBlurObserver) {
  46876. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46877. }
  46878. this._onKeyboardObserver = null;
  46879. this._onCanvasBlurObserver = null;
  46880. }
  46881. this._keys = [];
  46882. };
  46883. /**
  46884. * Update the current camera state depending on the inputs that have been used this frame.
  46885. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  46886. */
  46887. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46888. if (this._onKeyboardObserver) {
  46889. var camera = this.camera;
  46890. // Keyboard
  46891. for (var index = 0; index < this._keys.length; index++) {
  46892. var keyCode = this._keys[index];
  46893. var speed = camera._computeLocalCameraSpeed();
  46894. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46895. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46896. }
  46897. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46898. camera._localDirection.copyFromFloats(0, 0, speed);
  46899. }
  46900. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46901. camera._localDirection.copyFromFloats(speed, 0, 0);
  46902. }
  46903. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46904. camera._localDirection.copyFromFloats(0, 0, -speed);
  46905. }
  46906. if (camera.getScene().useRightHandedSystem) {
  46907. camera._localDirection.z *= -1;
  46908. }
  46909. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46910. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46911. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46912. }
  46913. }
  46914. };
  46915. /**
  46916. * Gets the class name of the current intput.
  46917. * @returns the class name
  46918. */
  46919. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46920. return "FreeCameraKeyboardMoveInput";
  46921. };
  46922. /** @hidden */
  46923. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46924. this._keys = [];
  46925. };
  46926. /**
  46927. * Get the friendly name associated with the input class.
  46928. * @returns the input friendly name
  46929. */
  46930. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46931. return "keyboard";
  46932. };
  46933. __decorate([
  46934. BABYLON.serialize()
  46935. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46936. __decorate([
  46937. BABYLON.serialize()
  46938. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46939. __decorate([
  46940. BABYLON.serialize()
  46941. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46942. __decorate([
  46943. BABYLON.serialize()
  46944. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46945. return FreeCameraKeyboardMoveInput;
  46946. }());
  46947. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46948. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46949. })(BABYLON || (BABYLON = {}));
  46950. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46951. var BABYLON;
  46952. (function (BABYLON) {
  46953. /**
  46954. * Default Inputs manager for the FreeCamera.
  46955. * It groups all the default supported inputs for ease of use.
  46956. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46957. */
  46958. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46959. __extends(FreeCameraInputsManager, _super);
  46960. /**
  46961. * Instantiates a new FreeCameraInputsManager.
  46962. * @param camera Defines the camera the inputs belong to
  46963. */
  46964. function FreeCameraInputsManager(camera) {
  46965. return _super.call(this, camera) || this;
  46966. }
  46967. /**
  46968. * Add keyboard input support to the input manager.
  46969. * @returns the current input manager
  46970. */
  46971. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46972. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46973. return this;
  46974. };
  46975. /**
  46976. * Add mouse input support to the input manager.
  46977. * @returns the current input manager
  46978. */
  46979. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46980. if (touchEnabled === void 0) { touchEnabled = true; }
  46981. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46982. return this;
  46983. };
  46984. /**
  46985. * Add orientation input support to the input manager.
  46986. * @returns the current input manager
  46987. */
  46988. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46989. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46990. return this;
  46991. };
  46992. /**
  46993. * Add touch input support to the input manager.
  46994. * @returns the current input manager
  46995. */
  46996. FreeCameraInputsManager.prototype.addTouch = function () {
  46997. this.add(new BABYLON.FreeCameraTouchInput());
  46998. return this;
  46999. };
  47000. /**
  47001. * Add virtual joystick input support to the input manager.
  47002. * @returns the current input manager
  47003. */
  47004. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47005. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47006. return this;
  47007. };
  47008. return FreeCameraInputsManager;
  47009. }(BABYLON.CameraInputsManager));
  47010. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47011. })(BABYLON || (BABYLON = {}));
  47012. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47013. var BABYLON;
  47014. (function (BABYLON) {
  47015. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47016. // Forcing to use the Universal camera
  47017. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47018. });
  47019. /**
  47020. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47021. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47022. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47023. */
  47024. var FreeCamera = /** @class */ (function (_super) {
  47025. __extends(FreeCamera, _super);
  47026. /**
  47027. * Instantiates a Free Camera.
  47028. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47029. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47030. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47031. * @param name Define the name of the camera in the scene
  47032. * @param position Define the start position of the camera in the scene
  47033. * @param scene Define the scene the camera belongs to
  47034. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47035. */
  47036. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47037. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47038. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47039. /**
  47040. * Define the collision ellipsoid of the camera.
  47041. * This is helpful to simulate a camera body like the player body around the camera
  47042. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47043. */
  47044. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47045. /**
  47046. * Define an offset for the position of the ellipsoid around the camera.
  47047. * This can be helpful to determine the center of the body near the gravity center of the body
  47048. * instead of its head.
  47049. */
  47050. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47051. /**
  47052. * Enable or disable collisions of the camera with the rest of the scene objects.
  47053. */
  47054. _this.checkCollisions = false;
  47055. /**
  47056. * Enable or disable gravity on the camera.
  47057. */
  47058. _this.applyGravity = false;
  47059. _this._needMoveForGravity = false;
  47060. _this._oldPosition = BABYLON.Vector3.Zero();
  47061. _this._diffPosition = BABYLON.Vector3.Zero();
  47062. _this._newPosition = BABYLON.Vector3.Zero();
  47063. // Collisions
  47064. _this._collisionMask = -1;
  47065. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47066. if (collidedMesh === void 0) { collidedMesh = null; }
  47067. //TODO move this to the collision coordinator!
  47068. if (_this.getScene().workerCollisions)
  47069. newPosition.multiplyInPlace(_this._collider._radius);
  47070. var updatePosition = function (newPos) {
  47071. _this._newPosition.copyFrom(newPos);
  47072. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47073. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47074. _this.position.addInPlace(_this._diffPosition);
  47075. if (_this.onCollide && collidedMesh) {
  47076. _this.onCollide(collidedMesh);
  47077. }
  47078. }
  47079. };
  47080. updatePosition(newPosition);
  47081. };
  47082. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47083. _this.inputs.addKeyboard().addMouse();
  47084. return _this;
  47085. }
  47086. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47087. /**
  47088. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47089. * Higher values reduce sensitivity.
  47090. */
  47091. get: function () {
  47092. var mouse = this.inputs.attached["mouse"];
  47093. if (mouse)
  47094. return mouse.angularSensibility;
  47095. return 0;
  47096. },
  47097. /**
  47098. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47099. * Higher values reduce sensitivity.
  47100. */
  47101. set: function (value) {
  47102. var mouse = this.inputs.attached["mouse"];
  47103. if (mouse)
  47104. mouse.angularSensibility = value;
  47105. },
  47106. enumerable: true,
  47107. configurable: true
  47108. });
  47109. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47110. /**
  47111. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47112. */
  47113. get: function () {
  47114. var keyboard = this.inputs.attached["keyboard"];
  47115. if (keyboard)
  47116. return keyboard.keysUp;
  47117. return [];
  47118. },
  47119. set: function (value) {
  47120. var keyboard = this.inputs.attached["keyboard"];
  47121. if (keyboard)
  47122. keyboard.keysUp = value;
  47123. },
  47124. enumerable: true,
  47125. configurable: true
  47126. });
  47127. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47128. /**
  47129. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47130. */
  47131. get: function () {
  47132. var keyboard = this.inputs.attached["keyboard"];
  47133. if (keyboard)
  47134. return keyboard.keysDown;
  47135. return [];
  47136. },
  47137. set: function (value) {
  47138. var keyboard = this.inputs.attached["keyboard"];
  47139. if (keyboard)
  47140. keyboard.keysDown = value;
  47141. },
  47142. enumerable: true,
  47143. configurable: true
  47144. });
  47145. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47146. /**
  47147. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47148. */
  47149. get: function () {
  47150. var keyboard = this.inputs.attached["keyboard"];
  47151. if (keyboard)
  47152. return keyboard.keysLeft;
  47153. return [];
  47154. },
  47155. set: function (value) {
  47156. var keyboard = this.inputs.attached["keyboard"];
  47157. if (keyboard)
  47158. keyboard.keysLeft = value;
  47159. },
  47160. enumerable: true,
  47161. configurable: true
  47162. });
  47163. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47164. /**
  47165. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47166. */
  47167. get: function () {
  47168. var keyboard = this.inputs.attached["keyboard"];
  47169. if (keyboard)
  47170. return keyboard.keysRight;
  47171. return [];
  47172. },
  47173. set: function (value) {
  47174. var keyboard = this.inputs.attached["keyboard"];
  47175. if (keyboard)
  47176. keyboard.keysRight = value;
  47177. },
  47178. enumerable: true,
  47179. configurable: true
  47180. });
  47181. /**
  47182. * Attached controls to the current camera.
  47183. * @param element Defines the element the controls should be listened from
  47184. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47185. */
  47186. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47187. this.inputs.attachElement(element, noPreventDefault);
  47188. };
  47189. /**
  47190. * Detach the current controls from the camera.
  47191. * The camera will stop reacting to inputs.
  47192. * @param element Defines the element to stop listening the inputs from
  47193. */
  47194. FreeCamera.prototype.detachControl = function (element) {
  47195. this.inputs.detachElement(element);
  47196. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47197. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47198. };
  47199. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47200. /**
  47201. * Define a collision mask to limit the list of object the camera can collide with
  47202. */
  47203. get: function () {
  47204. return this._collisionMask;
  47205. },
  47206. set: function (mask) {
  47207. this._collisionMask = !isNaN(mask) ? mask : -1;
  47208. },
  47209. enumerable: true,
  47210. configurable: true
  47211. });
  47212. /** @hidden */
  47213. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47214. var globalPosition;
  47215. if (this.parent) {
  47216. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47217. }
  47218. else {
  47219. globalPosition = this.position;
  47220. }
  47221. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47222. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47223. if (!this._collider) {
  47224. this._collider = new BABYLON.Collider();
  47225. }
  47226. this._collider._radius = this.ellipsoid;
  47227. this._collider.collisionMask = this._collisionMask;
  47228. //no need for clone, as long as gravity is not on.
  47229. var actualDisplacement = displacement;
  47230. //add gravity to the direction to prevent the dual-collision checking
  47231. if (this.applyGravity) {
  47232. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47233. actualDisplacement = displacement.add(this.getScene().gravity);
  47234. }
  47235. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47236. };
  47237. /** @hidden */
  47238. FreeCamera.prototype._checkInputs = function () {
  47239. if (!this._localDirection) {
  47240. this._localDirection = BABYLON.Vector3.Zero();
  47241. this._transformedDirection = BABYLON.Vector3.Zero();
  47242. }
  47243. this.inputs.checkInputs();
  47244. _super.prototype._checkInputs.call(this);
  47245. };
  47246. /** @hidden */
  47247. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47248. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47249. };
  47250. /** @hidden */
  47251. FreeCamera.prototype._updatePosition = function () {
  47252. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47253. this._collideWithWorld(this.cameraDirection);
  47254. }
  47255. else {
  47256. _super.prototype._updatePosition.call(this);
  47257. }
  47258. };
  47259. /**
  47260. * Destroy the camera and release the current resources hold by it.
  47261. */
  47262. FreeCamera.prototype.dispose = function () {
  47263. this.inputs.clear();
  47264. _super.prototype.dispose.call(this);
  47265. };
  47266. /**
  47267. * Gets the current object class name.
  47268. * @return the class name
  47269. */
  47270. FreeCamera.prototype.getClassName = function () {
  47271. return "FreeCamera";
  47272. };
  47273. __decorate([
  47274. BABYLON.serializeAsVector3()
  47275. ], FreeCamera.prototype, "ellipsoid", void 0);
  47276. __decorate([
  47277. BABYLON.serializeAsVector3()
  47278. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47279. __decorate([
  47280. BABYLON.serialize()
  47281. ], FreeCamera.prototype, "checkCollisions", void 0);
  47282. __decorate([
  47283. BABYLON.serialize()
  47284. ], FreeCamera.prototype, "applyGravity", void 0);
  47285. return FreeCamera;
  47286. }(BABYLON.TargetCamera));
  47287. BABYLON.FreeCamera = FreeCamera;
  47288. })(BABYLON || (BABYLON = {}));
  47289. //# sourceMappingURL=babylon.freeCamera.js.map
  47290. var BABYLON;
  47291. (function (BABYLON) {
  47292. /**
  47293. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47294. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47295. */
  47296. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47297. function ArcRotateCameraKeyboardMoveInput() {
  47298. /**
  47299. * Defines the list of key codes associated with the up action (increase alpha)
  47300. */
  47301. this.keysUp = [38];
  47302. /**
  47303. * Defines the list of key codes associated with the down action (decrease alpha)
  47304. */
  47305. this.keysDown = [40];
  47306. /**
  47307. * Defines the list of key codes associated with the left action (increase beta)
  47308. */
  47309. this.keysLeft = [37];
  47310. /**
  47311. * Defines the list of key codes associated with the right action (decrease beta)
  47312. */
  47313. this.keysRight = [39];
  47314. /**
  47315. * Defines the list of key codes associated with the reset action.
  47316. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47317. */
  47318. this.keysReset = [220];
  47319. /**
  47320. * Defines the panning sensibility of the inputs.
  47321. * (How fast is the camera paning)
  47322. */
  47323. this.panningSensibility = 50.0;
  47324. /**
  47325. * Defines the zooming sensibility of the inputs.
  47326. * (How fast is the camera zooming)
  47327. */
  47328. this.zoomingSensibility = 25.0;
  47329. /**
  47330. * Defines wether maintaining the alt key down switch the movement mode from
  47331. * orientation to zoom.
  47332. */
  47333. this.useAltToZoom = true;
  47334. this._keys = new Array();
  47335. }
  47336. /**
  47337. * Attach the input controls to a specific dom element to get the input from.
  47338. * @param element Defines the element the controls should be listened from
  47339. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47340. */
  47341. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47342. var _this = this;
  47343. if (this._onCanvasBlurObserver) {
  47344. return;
  47345. }
  47346. this._scene = this.camera.getScene();
  47347. this._engine = this._scene.getEngine();
  47348. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47349. _this._keys = [];
  47350. });
  47351. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47352. var evt = info.event;
  47353. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47354. _this._ctrlPressed = evt.ctrlKey;
  47355. _this._altPressed = evt.altKey;
  47356. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47357. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47358. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47359. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47360. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47361. var index = _this._keys.indexOf(evt.keyCode);
  47362. if (index === -1) {
  47363. _this._keys.push(evt.keyCode);
  47364. }
  47365. if (evt.preventDefault) {
  47366. if (!noPreventDefault) {
  47367. evt.preventDefault();
  47368. }
  47369. }
  47370. }
  47371. }
  47372. else {
  47373. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47374. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47375. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47376. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47377. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47378. var index = _this._keys.indexOf(evt.keyCode);
  47379. if (index >= 0) {
  47380. _this._keys.splice(index, 1);
  47381. }
  47382. if (evt.preventDefault) {
  47383. if (!noPreventDefault) {
  47384. evt.preventDefault();
  47385. }
  47386. }
  47387. }
  47388. }
  47389. });
  47390. };
  47391. /**
  47392. * Detach the current controls from the specified dom element.
  47393. * @param element Defines the element to stop listening the inputs from
  47394. */
  47395. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47396. if (this._scene) {
  47397. if (this._onKeyboardObserver) {
  47398. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47399. }
  47400. if (this._onCanvasBlurObserver) {
  47401. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47402. }
  47403. this._onKeyboardObserver = null;
  47404. this._onCanvasBlurObserver = null;
  47405. }
  47406. this._keys = [];
  47407. };
  47408. /**
  47409. * Update the current camera state depending on the inputs that have been used this frame.
  47410. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47411. */
  47412. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47413. if (this._onKeyboardObserver) {
  47414. var camera = this.camera;
  47415. for (var index = 0; index < this._keys.length; index++) {
  47416. var keyCode = this._keys[index];
  47417. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47418. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47419. camera.inertialPanningX -= 1 / this.panningSensibility;
  47420. }
  47421. else {
  47422. camera.inertialAlphaOffset -= 0.01;
  47423. }
  47424. }
  47425. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47426. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47427. camera.inertialPanningY += 1 / this.panningSensibility;
  47428. }
  47429. else if (this._altPressed && this.useAltToZoom) {
  47430. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47431. }
  47432. else {
  47433. camera.inertialBetaOffset -= 0.01;
  47434. }
  47435. }
  47436. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47437. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47438. camera.inertialPanningX += 1 / this.panningSensibility;
  47439. }
  47440. else {
  47441. camera.inertialAlphaOffset += 0.01;
  47442. }
  47443. }
  47444. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47445. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47446. camera.inertialPanningY -= 1 / this.panningSensibility;
  47447. }
  47448. else if (this._altPressed && this.useAltToZoom) {
  47449. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47450. }
  47451. else {
  47452. camera.inertialBetaOffset += 0.01;
  47453. }
  47454. }
  47455. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47456. camera.restoreState();
  47457. }
  47458. }
  47459. }
  47460. };
  47461. /**
  47462. * Gets the class name of the current intput.
  47463. * @returns the class name
  47464. */
  47465. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47466. return "ArcRotateCameraKeyboardMoveInput";
  47467. };
  47468. /**
  47469. * Get the friendly name associated with the input class.
  47470. * @returns the input friendly name
  47471. */
  47472. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47473. return "keyboard";
  47474. };
  47475. __decorate([
  47476. BABYLON.serialize()
  47477. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47478. __decorate([
  47479. BABYLON.serialize()
  47480. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47481. __decorate([
  47482. BABYLON.serialize()
  47483. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47484. __decorate([
  47485. BABYLON.serialize()
  47486. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47487. __decorate([
  47488. BABYLON.serialize()
  47489. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47490. __decorate([
  47491. BABYLON.serialize()
  47492. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47493. __decorate([
  47494. BABYLON.serialize()
  47495. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47496. __decorate([
  47497. BABYLON.serialize()
  47498. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47499. return ArcRotateCameraKeyboardMoveInput;
  47500. }());
  47501. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47502. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47503. })(BABYLON || (BABYLON = {}));
  47504. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47505. var BABYLON;
  47506. (function (BABYLON) {
  47507. /**
  47508. * Manage the mouse wheel inputs to control an arc rotate camera.
  47509. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47510. */
  47511. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47512. function ArcRotateCameraMouseWheelInput() {
  47513. /**
  47514. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47515. */
  47516. this.wheelPrecision = 3.0;
  47517. /**
  47518. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47519. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47520. */
  47521. this.wheelDeltaPercentage = 0;
  47522. }
  47523. /**
  47524. * Attach the input controls to a specific dom element to get the input from.
  47525. * @param element Defines the element the controls should be listened from
  47526. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47527. */
  47528. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47529. var _this = this;
  47530. this._wheel = function (p, s) {
  47531. //sanity check - this should be a PointerWheel event.
  47532. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47533. return;
  47534. var event = p.event;
  47535. var delta = 0;
  47536. if (event.wheelDelta) {
  47537. if (_this.wheelDeltaPercentage) {
  47538. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47539. if (event.wheelDelta > 0) {
  47540. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47541. }
  47542. else {
  47543. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47544. }
  47545. }
  47546. else {
  47547. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47548. }
  47549. }
  47550. else if (event.detail) {
  47551. delta = -event.detail / _this.wheelPrecision;
  47552. }
  47553. if (delta)
  47554. _this.camera.inertialRadiusOffset += delta;
  47555. if (event.preventDefault) {
  47556. if (!noPreventDefault) {
  47557. event.preventDefault();
  47558. }
  47559. }
  47560. };
  47561. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47562. };
  47563. /**
  47564. * Detach the current controls from the specified dom element.
  47565. * @param element Defines the element to stop listening the inputs from
  47566. */
  47567. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47568. if (this._observer && element) {
  47569. this.camera.getScene().onPointerObservable.remove(this._observer);
  47570. this._observer = null;
  47571. this._wheel = null;
  47572. }
  47573. };
  47574. /**
  47575. * Gets the class name of the current intput.
  47576. * @returns the class name
  47577. */
  47578. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47579. return "ArcRotateCameraMouseWheelInput";
  47580. };
  47581. /**
  47582. * Get the friendly name associated with the input class.
  47583. * @returns the input friendly name
  47584. */
  47585. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47586. return "mousewheel";
  47587. };
  47588. __decorate([
  47589. BABYLON.serialize()
  47590. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47591. __decorate([
  47592. BABYLON.serialize()
  47593. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47594. return ArcRotateCameraMouseWheelInput;
  47595. }());
  47596. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47597. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47598. })(BABYLON || (BABYLON = {}));
  47599. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47600. var BABYLON;
  47601. (function (BABYLON) {
  47602. /**
  47603. * Manage the pointers inputs to control an arc rotate camera.
  47604. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47605. */
  47606. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47607. function ArcRotateCameraPointersInput() {
  47608. /**
  47609. * Defines the buttons associated with the input to handle camera move.
  47610. */
  47611. this.buttons = [0, 1, 2];
  47612. /**
  47613. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47614. */
  47615. this.angularSensibilityX = 1000.0;
  47616. /**
  47617. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47618. */
  47619. this.angularSensibilityY = 1000.0;
  47620. /**
  47621. * Defines the pointer pinch precision or how fast is the camera zooming.
  47622. */
  47623. this.pinchPrecision = 12.0;
  47624. /**
  47625. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47626. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47627. */
  47628. this.pinchDeltaPercentage = 0;
  47629. /**
  47630. * Defines the pointer panning sensibility or how fast is the camera moving.
  47631. */
  47632. this.panningSensibility = 1000.0;
  47633. /**
  47634. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  47635. */
  47636. this.multiTouchPanning = true;
  47637. /**
  47638. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  47639. */
  47640. this.multiTouchPanAndZoom = true;
  47641. /**
  47642. * Revers pinch action direction.
  47643. */
  47644. this.pinchInwards = true;
  47645. this._isPanClick = false;
  47646. }
  47647. /**
  47648. * Attach the input controls to a specific dom element to get the input from.
  47649. * @param element Defines the element the controls should be listened from
  47650. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47651. */
  47652. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47653. var _this = this;
  47654. var engine = this.camera.getEngine();
  47655. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47656. var pointA = null;
  47657. var pointB = null;
  47658. var previousPinchSquaredDistance = 0;
  47659. var initialDistance = 0;
  47660. var twoFingerActivityCount = 0;
  47661. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47662. this._pointerInput = function (p, s) {
  47663. var evt = p.event;
  47664. var isTouch = p.event.pointerType === "touch";
  47665. if (engine.isInVRExclusivePointerMode) {
  47666. return;
  47667. }
  47668. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47669. return;
  47670. }
  47671. var srcElement = (evt.srcElement || evt.target);
  47672. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47673. try {
  47674. srcElement.setPointerCapture(evt.pointerId);
  47675. }
  47676. catch (e) {
  47677. //Nothing to do with the error. Execution will continue.
  47678. }
  47679. // Manage panning with pan button click
  47680. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47681. // manage pointers
  47682. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47683. if (pointA === null) {
  47684. pointA = cacheSoloPointer;
  47685. }
  47686. else if (pointB === null) {
  47687. pointB = cacheSoloPointer;
  47688. }
  47689. if (!noPreventDefault) {
  47690. evt.preventDefault();
  47691. element.focus();
  47692. }
  47693. }
  47694. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47695. _this.camera.restoreState();
  47696. }
  47697. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47698. try {
  47699. srcElement.releasePointerCapture(evt.pointerId);
  47700. }
  47701. catch (e) {
  47702. //Nothing to do with the error.
  47703. }
  47704. cacheSoloPointer = null;
  47705. previousPinchSquaredDistance = 0;
  47706. previousMultiTouchPanPosition.isPaning = false;
  47707. previousMultiTouchPanPosition.isPinching = false;
  47708. twoFingerActivityCount = 0;
  47709. initialDistance = 0;
  47710. if (!isTouch) {
  47711. pointB = null; // Mouse and pen are mono pointer
  47712. }
  47713. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47714. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47715. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47716. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47717. if (engine._badOS) {
  47718. pointA = pointB = null;
  47719. }
  47720. else {
  47721. //only remove the impacted pointer in case of multitouch allowing on most
  47722. //platforms switching from rotate to zoom and pan seamlessly.
  47723. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47724. pointA = pointB;
  47725. pointB = null;
  47726. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47727. }
  47728. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47729. pointB = null;
  47730. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47731. }
  47732. else {
  47733. pointA = pointB = null;
  47734. }
  47735. }
  47736. if (!noPreventDefault) {
  47737. evt.preventDefault();
  47738. }
  47739. }
  47740. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47741. if (!noPreventDefault) {
  47742. evt.preventDefault();
  47743. }
  47744. // One button down
  47745. if (pointA && pointB === null && cacheSoloPointer) {
  47746. if (_this.panningSensibility !== 0 &&
  47747. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47748. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47749. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47750. }
  47751. else {
  47752. var offsetX = evt.clientX - cacheSoloPointer.x;
  47753. var offsetY = evt.clientY - cacheSoloPointer.y;
  47754. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47755. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47756. }
  47757. cacheSoloPointer.x = evt.clientX;
  47758. cacheSoloPointer.y = evt.clientY;
  47759. }
  47760. // Two buttons down: pinch/pan
  47761. else if (pointA && pointB) {
  47762. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47763. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47764. ed.x = evt.clientX;
  47765. ed.y = evt.clientY;
  47766. var direction = _this.pinchInwards ? 1 : -1;
  47767. var distX = pointA.x - pointB.x;
  47768. var distY = pointA.y - pointB.y;
  47769. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47770. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47771. if (previousPinchSquaredDistance === 0) {
  47772. initialDistance = pinchDistance;
  47773. previousPinchSquaredDistance = pinchSquaredDistance;
  47774. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47775. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47776. return;
  47777. }
  47778. if (_this.multiTouchPanAndZoom) {
  47779. if (_this.pinchDeltaPercentage) {
  47780. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47781. }
  47782. else {
  47783. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47784. (_this.pinchPrecision *
  47785. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47786. direction);
  47787. }
  47788. if (_this.panningSensibility !== 0) {
  47789. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47790. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47791. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47792. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47793. previousMultiTouchPanPosition.x = pointersCenterX;
  47794. previousMultiTouchPanPosition.y = pointersCenterY;
  47795. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47796. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47797. }
  47798. }
  47799. else {
  47800. twoFingerActivityCount++;
  47801. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47802. if (_this.pinchDeltaPercentage) {
  47803. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47804. }
  47805. else {
  47806. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47807. (_this.pinchPrecision *
  47808. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47809. direction);
  47810. }
  47811. previousMultiTouchPanPosition.isPaning = false;
  47812. previousMultiTouchPanPosition.isPinching = true;
  47813. }
  47814. else {
  47815. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47816. if (!previousMultiTouchPanPosition.isPaning) {
  47817. previousMultiTouchPanPosition.isPaning = true;
  47818. previousMultiTouchPanPosition.isPinching = false;
  47819. previousMultiTouchPanPosition.x = ed.x;
  47820. previousMultiTouchPanPosition.y = ed.y;
  47821. return;
  47822. }
  47823. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47824. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47825. }
  47826. }
  47827. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47828. previousMultiTouchPanPosition.x = ed.x;
  47829. previousMultiTouchPanPosition.y = ed.y;
  47830. }
  47831. }
  47832. previousPinchSquaredDistance = pinchSquaredDistance;
  47833. }
  47834. }
  47835. };
  47836. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47837. this._onContextMenu = function (evt) {
  47838. evt.preventDefault();
  47839. };
  47840. if (!this.camera._useCtrlForPanning) {
  47841. element.addEventListener("contextmenu", this._onContextMenu, false);
  47842. }
  47843. this._onLostFocus = function () {
  47844. //this._keys = [];
  47845. pointA = pointB = null;
  47846. previousPinchSquaredDistance = 0;
  47847. previousMultiTouchPanPosition.isPaning = false;
  47848. previousMultiTouchPanPosition.isPinching = false;
  47849. twoFingerActivityCount = 0;
  47850. cacheSoloPointer = null;
  47851. initialDistance = 0;
  47852. };
  47853. this._onMouseMove = function (evt) {
  47854. if (!engine.isPointerLock) {
  47855. return;
  47856. }
  47857. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47858. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47859. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47860. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47861. if (!noPreventDefault) {
  47862. evt.preventDefault();
  47863. }
  47864. };
  47865. this._onGestureStart = function (e) {
  47866. if (window.MSGesture === undefined) {
  47867. return;
  47868. }
  47869. if (!_this._MSGestureHandler) {
  47870. _this._MSGestureHandler = new MSGesture();
  47871. _this._MSGestureHandler.target = element;
  47872. }
  47873. _this._MSGestureHandler.addPointer(e.pointerId);
  47874. };
  47875. this._onGesture = function (e) {
  47876. _this.camera.radius *= e.scale;
  47877. if (e.preventDefault) {
  47878. if (!noPreventDefault) {
  47879. e.stopPropagation();
  47880. e.preventDefault();
  47881. }
  47882. }
  47883. };
  47884. element.addEventListener("mousemove", this._onMouseMove, false);
  47885. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47886. element.addEventListener("MSGestureChange", this._onGesture, false);
  47887. BABYLON.Tools.RegisterTopRootEvents([
  47888. { name: "blur", handler: this._onLostFocus }
  47889. ]);
  47890. };
  47891. /**
  47892. * Detach the current controls from the specified dom element.
  47893. * @param element Defines the element to stop listening the inputs from
  47894. */
  47895. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47896. if (this._onLostFocus) {
  47897. BABYLON.Tools.UnregisterTopRootEvents([
  47898. { name: "blur", handler: this._onLostFocus }
  47899. ]);
  47900. }
  47901. if (element && this._observer) {
  47902. this.camera.getScene().onPointerObservable.remove(this._observer);
  47903. this._observer = null;
  47904. if (this._onContextMenu) {
  47905. element.removeEventListener("contextmenu", this._onContextMenu);
  47906. }
  47907. if (this._onMouseMove) {
  47908. element.removeEventListener("mousemove", this._onMouseMove);
  47909. }
  47910. if (this._onGestureStart) {
  47911. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47912. }
  47913. if (this._onGesture) {
  47914. element.removeEventListener("MSGestureChange", this._onGesture);
  47915. }
  47916. this._isPanClick = false;
  47917. this.pinchInwards = true;
  47918. this._onMouseMove = null;
  47919. this._onGestureStart = null;
  47920. this._onGesture = null;
  47921. this._MSGestureHandler = null;
  47922. this._onLostFocus = null;
  47923. this._onContextMenu = null;
  47924. }
  47925. };
  47926. /**
  47927. * Gets the class name of the current intput.
  47928. * @returns the class name
  47929. */
  47930. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47931. return "ArcRotateCameraPointersInput";
  47932. };
  47933. /**
  47934. * Get the friendly name associated with the input class.
  47935. * @returns the input friendly name
  47936. */
  47937. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47938. return "pointers";
  47939. };
  47940. __decorate([
  47941. BABYLON.serialize()
  47942. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47943. __decorate([
  47944. BABYLON.serialize()
  47945. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47946. __decorate([
  47947. BABYLON.serialize()
  47948. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47949. __decorate([
  47950. BABYLON.serialize()
  47951. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47952. __decorate([
  47953. BABYLON.serialize()
  47954. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47955. __decorate([
  47956. BABYLON.serialize()
  47957. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47958. __decorate([
  47959. BABYLON.serialize()
  47960. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47961. __decorate([
  47962. BABYLON.serialize()
  47963. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47964. return ArcRotateCameraPointersInput;
  47965. }());
  47966. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47967. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47968. })(BABYLON || (BABYLON = {}));
  47969. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47970. var BABYLON;
  47971. (function (BABYLON) {
  47972. /**
  47973. * Default Inputs manager for the ArcRotateCamera.
  47974. * It groups all the default supported inputs for ease of use.
  47975. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47976. */
  47977. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47978. __extends(ArcRotateCameraInputsManager, _super);
  47979. /**
  47980. * Instantiates a new ArcRotateCameraInputsManager.
  47981. * @param camera Defines the camera the inputs belong to
  47982. */
  47983. function ArcRotateCameraInputsManager(camera) {
  47984. return _super.call(this, camera) || this;
  47985. }
  47986. /**
  47987. * Add mouse wheel input support to the input manager.
  47988. * @returns the current input manager
  47989. */
  47990. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47991. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47992. return this;
  47993. };
  47994. /**
  47995. * Add pointers input support to the input manager.
  47996. * @returns the current input manager
  47997. */
  47998. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47999. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48000. return this;
  48001. };
  48002. /**
  48003. * Add keyboard input support to the input manager.
  48004. * @returns the current input manager
  48005. */
  48006. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48007. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48008. return this;
  48009. };
  48010. /**
  48011. * Add orientation input support to the input manager.
  48012. * @returns the current input manager
  48013. */
  48014. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48015. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48016. return this;
  48017. };
  48018. return ArcRotateCameraInputsManager;
  48019. }(BABYLON.CameraInputsManager));
  48020. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48021. })(BABYLON || (BABYLON = {}));
  48022. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48023. var BABYLON;
  48024. (function (BABYLON) {
  48025. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48026. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48027. });
  48028. /**
  48029. * This represents an orbital type of camera.
  48030. *
  48031. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  48032. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  48033. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48034. */
  48035. var ArcRotateCamera = /** @class */ (function (_super) {
  48036. __extends(ArcRotateCamera, _super);
  48037. /**
  48038. * Instantiates a new ArcRotateCamera in a given scene
  48039. * @param name Defines the name of the camera
  48040. * @param alpha Defines the camera rotation along the logitudinal axis
  48041. * @param beta Defines the camera rotation along the latitudinal axis
  48042. * @param radius Defines the camera distance from its target
  48043. * @param target Defines the camera target
  48044. * @param scene Defines the scene the camera belongs to
  48045. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48046. */
  48047. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48048. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48049. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48050. /**
  48051. * Current inertia value on the longitudinal axis.
  48052. * The bigger this number the longer it will take for the camera to stop.
  48053. */
  48054. _this.inertialAlphaOffset = 0;
  48055. /**
  48056. * Current inertia value on the latitudinal axis.
  48057. * The bigger this number the longer it will take for the camera to stop.
  48058. */
  48059. _this.inertialBetaOffset = 0;
  48060. /**
  48061. * Current inertia value on the radius axis.
  48062. * The bigger this number the longer it will take for the camera to stop.
  48063. */
  48064. _this.inertialRadiusOffset = 0;
  48065. /**
  48066. * Minimum allowed angle on the longitudinal axis.
  48067. * This can help limiting how the Camera is able to move in the scene.
  48068. */
  48069. _this.lowerAlphaLimit = null;
  48070. /**
  48071. * Maximum allowed angle on the longitudinal axis.
  48072. * This can help limiting how the Camera is able to move in the scene.
  48073. */
  48074. _this.upperAlphaLimit = null;
  48075. /**
  48076. * Minimum allowed angle on the latitudinal axis.
  48077. * This can help limiting how the Camera is able to move in the scene.
  48078. */
  48079. _this.lowerBetaLimit = 0.01;
  48080. /**
  48081. * Maximum allowed angle on the latitudinal axis.
  48082. * This can help limiting how the Camera is able to move in the scene.
  48083. */
  48084. _this.upperBetaLimit = Math.PI;
  48085. /**
  48086. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48087. * This can help limiting how the Camera is able to move in the scene.
  48088. */
  48089. _this.lowerRadiusLimit = null;
  48090. /**
  48091. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48092. * This can help limiting how the Camera is able to move in the scene.
  48093. */
  48094. _this.upperRadiusLimit = null;
  48095. /**
  48096. * Defines the current inertia value used during panning of the camera along the X axis.
  48097. */
  48098. _this.inertialPanningX = 0;
  48099. /**
  48100. * Defines the current inertia value used during panning of the camera along the Y axis.
  48101. */
  48102. _this.inertialPanningY = 0;
  48103. /**
  48104. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48105. * Basically if your fingers moves away from more than this distance you will be considered
  48106. * in pinch mode.
  48107. */
  48108. _this.pinchToPanMaxDistance = 20;
  48109. /**
  48110. * Defines the maximum distance the camera can pan.
  48111. * This could help keeping the cammera always in your scene.
  48112. */
  48113. _this.panningDistanceLimit = null;
  48114. /**
  48115. * Defines the target of the camera before paning.
  48116. */
  48117. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48118. /**
  48119. * Defines the value of the inertia used during panning.
  48120. * 0 would mean stop inertia and one would mean no decelleration at all.
  48121. */
  48122. _this.panningInertia = 0.9;
  48123. //-- end properties for backward compatibility for inputs
  48124. /**
  48125. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48126. */
  48127. _this.zoomOnFactor = 1;
  48128. /**
  48129. * Defines a screen offset for the camera position.
  48130. */
  48131. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48132. /**
  48133. * Allows the camera to be completely reversed.
  48134. * If false the camera can not arrive upside down.
  48135. */
  48136. _this.allowUpsideDown = true;
  48137. /** @hidden */
  48138. _this._viewMatrix = new BABYLON.Matrix();
  48139. /**
  48140. * Defines the allowed panning axis.
  48141. */
  48142. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48143. /**
  48144. * Observable triggered when the mesh target has been changed on the camera.
  48145. */
  48146. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48147. /**
  48148. * Defines whether the camera should check collision with the objects oh the scene.
  48149. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48150. */
  48151. _this.checkCollisions = false;
  48152. /**
  48153. * Defines the collision radius of the camera.
  48154. * This simulates a sphere around the camera.
  48155. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48156. */
  48157. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48158. _this._previousPosition = BABYLON.Vector3.Zero();
  48159. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48160. _this._newPosition = BABYLON.Vector3.Zero();
  48161. _this._computationVector = BABYLON.Vector3.Zero();
  48162. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48163. if (collidedMesh === void 0) { collidedMesh = null; }
  48164. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48165. newPosition.multiplyInPlace(_this._collider._radius);
  48166. }
  48167. if (!collidedMesh) {
  48168. _this._previousPosition.copyFrom(_this.position);
  48169. }
  48170. else {
  48171. _this.setPosition(newPosition);
  48172. if (_this.onCollide) {
  48173. _this.onCollide(collidedMesh);
  48174. }
  48175. }
  48176. // Recompute because of constraints
  48177. var cosa = Math.cos(_this.alpha);
  48178. var sina = Math.sin(_this.alpha);
  48179. var cosb = Math.cos(_this.beta);
  48180. var sinb = Math.sin(_this.beta);
  48181. if (sinb === 0) {
  48182. sinb = 0.0001;
  48183. }
  48184. var target = _this._getTargetPosition();
  48185. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48186. target.addToRef(_this._computationVector, _this._newPosition);
  48187. _this.position.copyFrom(_this._newPosition);
  48188. var up = _this.upVector;
  48189. if (_this.allowUpsideDown && _this.beta < 0) {
  48190. up = up.clone();
  48191. up = up.negate();
  48192. }
  48193. _this._computeViewMatrix(_this.position, target, up);
  48194. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48195. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48196. _this._collisionTriggered = false;
  48197. };
  48198. _this._target = BABYLON.Vector3.Zero();
  48199. if (target) {
  48200. _this.setTarget(target);
  48201. }
  48202. _this.alpha = alpha;
  48203. _this.beta = beta;
  48204. _this.radius = radius;
  48205. _this.getViewMatrix();
  48206. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48207. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48208. return _this;
  48209. }
  48210. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48211. /**
  48212. * Defines the target point of the camera.
  48213. * The camera looks towards it form the radius distance.
  48214. */
  48215. get: function () {
  48216. return this._target;
  48217. },
  48218. set: function (value) {
  48219. this.setTarget(value);
  48220. },
  48221. enumerable: true,
  48222. configurable: true
  48223. });
  48224. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48225. //-- begin properties for backward compatibility for inputs
  48226. /**
  48227. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48228. */
  48229. get: function () {
  48230. var pointers = this.inputs.attached["pointers"];
  48231. if (pointers)
  48232. return pointers.angularSensibilityX;
  48233. return 0;
  48234. },
  48235. set: function (value) {
  48236. var pointers = this.inputs.attached["pointers"];
  48237. if (pointers) {
  48238. pointers.angularSensibilityX = value;
  48239. }
  48240. },
  48241. enumerable: true,
  48242. configurable: true
  48243. });
  48244. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48245. /**
  48246. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48247. */
  48248. get: function () {
  48249. var pointers = this.inputs.attached["pointers"];
  48250. if (pointers)
  48251. return pointers.angularSensibilityY;
  48252. return 0;
  48253. },
  48254. set: function (value) {
  48255. var pointers = this.inputs.attached["pointers"];
  48256. if (pointers) {
  48257. pointers.angularSensibilityY = value;
  48258. }
  48259. },
  48260. enumerable: true,
  48261. configurable: true
  48262. });
  48263. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48264. /**
  48265. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48266. */
  48267. get: function () {
  48268. var pointers = this.inputs.attached["pointers"];
  48269. if (pointers)
  48270. return pointers.pinchPrecision;
  48271. return 0;
  48272. },
  48273. set: function (value) {
  48274. var pointers = this.inputs.attached["pointers"];
  48275. if (pointers) {
  48276. pointers.pinchPrecision = value;
  48277. }
  48278. },
  48279. enumerable: true,
  48280. configurable: true
  48281. });
  48282. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48283. /**
  48284. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48285. * It will be used instead of pinchDeltaPrecision if different from 0.
  48286. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48287. */
  48288. get: function () {
  48289. var pointers = this.inputs.attached["pointers"];
  48290. if (pointers)
  48291. return pointers.pinchDeltaPercentage;
  48292. return 0;
  48293. },
  48294. set: function (value) {
  48295. var pointers = this.inputs.attached["pointers"];
  48296. if (pointers) {
  48297. pointers.pinchDeltaPercentage = value;
  48298. }
  48299. },
  48300. enumerable: true,
  48301. configurable: true
  48302. });
  48303. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48304. /**
  48305. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48306. */
  48307. get: function () {
  48308. var pointers = this.inputs.attached["pointers"];
  48309. if (pointers)
  48310. return pointers.panningSensibility;
  48311. return 0;
  48312. },
  48313. set: function (value) {
  48314. var pointers = this.inputs.attached["pointers"];
  48315. if (pointers) {
  48316. pointers.panningSensibility = value;
  48317. }
  48318. },
  48319. enumerable: true,
  48320. configurable: true
  48321. });
  48322. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48323. /**
  48324. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48325. */
  48326. get: function () {
  48327. var keyboard = this.inputs.attached["keyboard"];
  48328. if (keyboard)
  48329. return keyboard.keysUp;
  48330. return [];
  48331. },
  48332. set: function (value) {
  48333. var keyboard = this.inputs.attached["keyboard"];
  48334. if (keyboard)
  48335. keyboard.keysUp = value;
  48336. },
  48337. enumerable: true,
  48338. configurable: true
  48339. });
  48340. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48341. /**
  48342. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48343. */
  48344. get: function () {
  48345. var keyboard = this.inputs.attached["keyboard"];
  48346. if (keyboard)
  48347. return keyboard.keysDown;
  48348. return [];
  48349. },
  48350. set: function (value) {
  48351. var keyboard = this.inputs.attached["keyboard"];
  48352. if (keyboard)
  48353. keyboard.keysDown = value;
  48354. },
  48355. enumerable: true,
  48356. configurable: true
  48357. });
  48358. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48359. /**
  48360. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48361. */
  48362. get: function () {
  48363. var keyboard = this.inputs.attached["keyboard"];
  48364. if (keyboard)
  48365. return keyboard.keysLeft;
  48366. return [];
  48367. },
  48368. set: function (value) {
  48369. var keyboard = this.inputs.attached["keyboard"];
  48370. if (keyboard)
  48371. keyboard.keysLeft = value;
  48372. },
  48373. enumerable: true,
  48374. configurable: true
  48375. });
  48376. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48377. /**
  48378. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48379. */
  48380. get: function () {
  48381. var keyboard = this.inputs.attached["keyboard"];
  48382. if (keyboard)
  48383. return keyboard.keysRight;
  48384. return [];
  48385. },
  48386. set: function (value) {
  48387. var keyboard = this.inputs.attached["keyboard"];
  48388. if (keyboard)
  48389. keyboard.keysRight = value;
  48390. },
  48391. enumerable: true,
  48392. configurable: true
  48393. });
  48394. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48395. /**
  48396. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48397. */
  48398. get: function () {
  48399. var mousewheel = this.inputs.attached["mousewheel"];
  48400. if (mousewheel)
  48401. return mousewheel.wheelPrecision;
  48402. return 0;
  48403. },
  48404. set: function (value) {
  48405. var mousewheel = this.inputs.attached["mousewheel"];
  48406. if (mousewheel)
  48407. mousewheel.wheelPrecision = value;
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48413. /**
  48414. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48415. * It will be used instead of pinchDeltaPrecision if different from 0.
  48416. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48417. */
  48418. get: function () {
  48419. var mousewheel = this.inputs.attached["mousewheel"];
  48420. if (mousewheel)
  48421. return mousewheel.wheelDeltaPercentage;
  48422. return 0;
  48423. },
  48424. set: function (value) {
  48425. var mousewheel = this.inputs.attached["mousewheel"];
  48426. if (mousewheel)
  48427. mousewheel.wheelDeltaPercentage = value;
  48428. },
  48429. enumerable: true,
  48430. configurable: true
  48431. });
  48432. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48433. /**
  48434. * Gets the bouncing behavior of the camera if it has been enabled.
  48435. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48436. */
  48437. get: function () {
  48438. return this._bouncingBehavior;
  48439. },
  48440. enumerable: true,
  48441. configurable: true
  48442. });
  48443. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48444. /**
  48445. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48446. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48447. */
  48448. get: function () {
  48449. return this._bouncingBehavior != null;
  48450. },
  48451. set: function (value) {
  48452. if (value === this.useBouncingBehavior) {
  48453. return;
  48454. }
  48455. if (value) {
  48456. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48457. this.addBehavior(this._bouncingBehavior);
  48458. }
  48459. else if (this._bouncingBehavior) {
  48460. this.removeBehavior(this._bouncingBehavior);
  48461. this._bouncingBehavior = null;
  48462. }
  48463. },
  48464. enumerable: true,
  48465. configurable: true
  48466. });
  48467. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48468. /**
  48469. * Gets the framing behavior of the camera if it has been enabled.
  48470. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48471. */
  48472. get: function () {
  48473. return this._framingBehavior;
  48474. },
  48475. enumerable: true,
  48476. configurable: true
  48477. });
  48478. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48479. /**
  48480. * Defines if the framing behavior of the camera is enabled on the camera.
  48481. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48482. */
  48483. get: function () {
  48484. return this._framingBehavior != null;
  48485. },
  48486. set: function (value) {
  48487. if (value === this.useFramingBehavior) {
  48488. return;
  48489. }
  48490. if (value) {
  48491. this._framingBehavior = new BABYLON.FramingBehavior();
  48492. this.addBehavior(this._framingBehavior);
  48493. }
  48494. else if (this._framingBehavior) {
  48495. this.removeBehavior(this._framingBehavior);
  48496. this._framingBehavior = null;
  48497. }
  48498. },
  48499. enumerable: true,
  48500. configurable: true
  48501. });
  48502. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48503. /**
  48504. * Gets the auto rotation behavior of the camera if it has been enabled.
  48505. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48506. */
  48507. get: function () {
  48508. return this._autoRotationBehavior;
  48509. },
  48510. enumerable: true,
  48511. configurable: true
  48512. });
  48513. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48514. /**
  48515. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48516. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48517. */
  48518. get: function () {
  48519. return this._autoRotationBehavior != null;
  48520. },
  48521. set: function (value) {
  48522. if (value === this.useAutoRotationBehavior) {
  48523. return;
  48524. }
  48525. if (value) {
  48526. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48527. this.addBehavior(this._autoRotationBehavior);
  48528. }
  48529. else if (this._autoRotationBehavior) {
  48530. this.removeBehavior(this._autoRotationBehavior);
  48531. this._autoRotationBehavior = null;
  48532. }
  48533. },
  48534. enumerable: true,
  48535. configurable: true
  48536. });
  48537. // Cache
  48538. /** @hidden */
  48539. ArcRotateCamera.prototype._initCache = function () {
  48540. _super.prototype._initCache.call(this);
  48541. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48542. this._cache.alpha = undefined;
  48543. this._cache.beta = undefined;
  48544. this._cache.radius = undefined;
  48545. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48546. };
  48547. /** @hidden */
  48548. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48549. if (!ignoreParentClass) {
  48550. _super.prototype._updateCache.call(this);
  48551. }
  48552. this._cache._target.copyFrom(this._getTargetPosition());
  48553. this._cache.alpha = this.alpha;
  48554. this._cache.beta = this.beta;
  48555. this._cache.radius = this.radius;
  48556. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48557. };
  48558. ArcRotateCamera.prototype._getTargetPosition = function () {
  48559. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48560. var pos = this._targetHost.getAbsolutePosition();
  48561. if (this._targetBoundingCenter) {
  48562. pos.addToRef(this._targetBoundingCenter, this._target);
  48563. }
  48564. else {
  48565. this._target.copyFrom(pos);
  48566. }
  48567. }
  48568. var lockedTargetPosition = this._getLockedTargetPosition();
  48569. if (lockedTargetPosition) {
  48570. return lockedTargetPosition;
  48571. }
  48572. return this._target;
  48573. };
  48574. /**
  48575. * Stores the current state of the camera (alpha, beta, radius and target)
  48576. * @returns the camera itself
  48577. */
  48578. ArcRotateCamera.prototype.storeState = function () {
  48579. this._storedAlpha = this.alpha;
  48580. this._storedBeta = this.beta;
  48581. this._storedRadius = this.radius;
  48582. this._storedTarget = this._getTargetPosition().clone();
  48583. return _super.prototype.storeState.call(this);
  48584. };
  48585. /**
  48586. * @hidden
  48587. * Restored camera state. You must call storeState() first
  48588. */
  48589. ArcRotateCamera.prototype._restoreStateValues = function () {
  48590. if (!_super.prototype._restoreStateValues.call(this)) {
  48591. return false;
  48592. }
  48593. this.alpha = this._storedAlpha;
  48594. this.beta = this._storedBeta;
  48595. this.radius = this._storedRadius;
  48596. this.setTarget(this._storedTarget.clone());
  48597. this.inertialAlphaOffset = 0;
  48598. this.inertialBetaOffset = 0;
  48599. this.inertialRadiusOffset = 0;
  48600. this.inertialPanningX = 0;
  48601. this.inertialPanningY = 0;
  48602. return true;
  48603. };
  48604. // Synchronized
  48605. /** @hidden */
  48606. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48607. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48608. return false;
  48609. return this._cache._target.equals(this._getTargetPosition())
  48610. && this._cache.alpha === this.alpha
  48611. && this._cache.beta === this.beta
  48612. && this._cache.radius === this.radius
  48613. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48614. };
  48615. /**
  48616. * Attached controls to the current camera.
  48617. * @param element Defines the element the controls should be listened from
  48618. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48619. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  48620. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  48621. */
  48622. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48623. var _this = this;
  48624. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48625. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48626. this._useCtrlForPanning = useCtrlForPanning;
  48627. this._panningMouseButton = panningMouseButton;
  48628. this.inputs.attachElement(element, noPreventDefault);
  48629. this._reset = function () {
  48630. _this.inertialAlphaOffset = 0;
  48631. _this.inertialBetaOffset = 0;
  48632. _this.inertialRadiusOffset = 0;
  48633. _this.inertialPanningX = 0;
  48634. _this.inertialPanningY = 0;
  48635. };
  48636. };
  48637. /**
  48638. * Detach the current controls from the camera.
  48639. * The camera will stop reacting to inputs.
  48640. * @param element Defines the element to stop listening the inputs from
  48641. */
  48642. ArcRotateCamera.prototype.detachControl = function (element) {
  48643. this.inputs.detachElement(element);
  48644. if (this._reset) {
  48645. this._reset();
  48646. }
  48647. };
  48648. /** @hidden */
  48649. ArcRotateCamera.prototype._checkInputs = function () {
  48650. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48651. if (this._collisionTriggered) {
  48652. return;
  48653. }
  48654. this.inputs.checkInputs();
  48655. // Inertia
  48656. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48657. var inertialAlphaOffset = this.inertialAlphaOffset;
  48658. if (this.beta <= 0)
  48659. inertialAlphaOffset *= -1;
  48660. if (this.getScene().useRightHandedSystem)
  48661. inertialAlphaOffset *= -1;
  48662. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48663. inertialAlphaOffset *= -1;
  48664. this.alpha += inertialAlphaOffset;
  48665. this.beta += this.inertialBetaOffset;
  48666. this.radius -= this.inertialRadiusOffset;
  48667. this.inertialAlphaOffset *= this.inertia;
  48668. this.inertialBetaOffset *= this.inertia;
  48669. this.inertialRadiusOffset *= this.inertia;
  48670. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48671. this.inertialAlphaOffset = 0;
  48672. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48673. this.inertialBetaOffset = 0;
  48674. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48675. this.inertialRadiusOffset = 0;
  48676. }
  48677. // Panning inertia
  48678. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48679. if (!this._localDirection) {
  48680. this._localDirection = BABYLON.Vector3.Zero();
  48681. this._transformedDirection = BABYLON.Vector3.Zero();
  48682. }
  48683. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48684. this._localDirection.multiplyInPlace(this.panningAxis);
  48685. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48686. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48687. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48688. if (!this.panningAxis.y) {
  48689. this._transformedDirection.y = 0;
  48690. }
  48691. if (!this._targetHost) {
  48692. if (this.panningDistanceLimit) {
  48693. this._transformedDirection.addInPlace(this._target);
  48694. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48695. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48696. this._target.copyFrom(this._transformedDirection);
  48697. }
  48698. }
  48699. else {
  48700. this._target.addInPlace(this._transformedDirection);
  48701. }
  48702. }
  48703. this.inertialPanningX *= this.panningInertia;
  48704. this.inertialPanningY *= this.panningInertia;
  48705. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48706. this.inertialPanningX = 0;
  48707. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48708. this.inertialPanningY = 0;
  48709. }
  48710. // Limits
  48711. this._checkLimits();
  48712. _super.prototype._checkInputs.call(this);
  48713. };
  48714. ArcRotateCamera.prototype._checkLimits = function () {
  48715. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48716. if (this.allowUpsideDown && this.beta > Math.PI) {
  48717. this.beta = this.beta - (2 * Math.PI);
  48718. }
  48719. }
  48720. else {
  48721. if (this.beta < this.lowerBetaLimit) {
  48722. this.beta = this.lowerBetaLimit;
  48723. }
  48724. }
  48725. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48726. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48727. this.beta = this.beta + (2 * Math.PI);
  48728. }
  48729. }
  48730. else {
  48731. if (this.beta > this.upperBetaLimit) {
  48732. this.beta = this.upperBetaLimit;
  48733. }
  48734. }
  48735. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48736. this.alpha = this.lowerAlphaLimit;
  48737. }
  48738. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48739. this.alpha = this.upperAlphaLimit;
  48740. }
  48741. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48742. this.radius = this.lowerRadiusLimit;
  48743. }
  48744. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48745. this.radius = this.upperRadiusLimit;
  48746. }
  48747. };
  48748. /**
  48749. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48750. */
  48751. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48752. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48753. this.radius = this._computationVector.length();
  48754. if (this.radius === 0) {
  48755. this.radius = 0.0001; // Just to avoid division by zero
  48756. }
  48757. // Alpha
  48758. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48759. if (this._computationVector.z < 0) {
  48760. this.alpha = 2 * Math.PI - this.alpha;
  48761. }
  48762. // Beta
  48763. this.beta = Math.acos(this._computationVector.y / this.radius);
  48764. this._checkLimits();
  48765. };
  48766. /**
  48767. * Use a position to define the current camera related information like aplha, beta and radius
  48768. * @param position Defines the position to set the camera at
  48769. */
  48770. ArcRotateCamera.prototype.setPosition = function (position) {
  48771. if (this.position.equals(position)) {
  48772. return;
  48773. }
  48774. this.position.copyFrom(position);
  48775. this.rebuildAnglesAndRadius();
  48776. };
  48777. /**
  48778. * Defines the target the camera should look at.
  48779. * This will automatically adapt alpha beta and radius to fit within the new target.
  48780. * @param target Defines the new target as a Vector or a mesh
  48781. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48782. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48783. */
  48784. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48785. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48786. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48787. if (target.getBoundingInfo) {
  48788. if (toBoundingCenter) {
  48789. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48790. }
  48791. else {
  48792. this._targetBoundingCenter = null;
  48793. }
  48794. this._targetHost = target;
  48795. this._target = this._getTargetPosition();
  48796. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48797. }
  48798. else {
  48799. var newTarget = target;
  48800. var currentTarget = this._getTargetPosition();
  48801. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48802. return;
  48803. }
  48804. this._targetHost = null;
  48805. this._target = newTarget;
  48806. this._targetBoundingCenter = null;
  48807. this.onMeshTargetChangedObservable.notifyObservers(null);
  48808. }
  48809. this.rebuildAnglesAndRadius();
  48810. };
  48811. /** @hidden */
  48812. ArcRotateCamera.prototype._getViewMatrix = function () {
  48813. // Compute
  48814. var cosa = Math.cos(this.alpha);
  48815. var sina = Math.sin(this.alpha);
  48816. var cosb = Math.cos(this.beta);
  48817. var sinb = Math.sin(this.beta);
  48818. if (sinb === 0) {
  48819. sinb = 0.0001;
  48820. }
  48821. var target = this._getTargetPosition();
  48822. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48823. target.addToRef(this._computationVector, this._newPosition);
  48824. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48825. if (!this._collider) {
  48826. this._collider = new BABYLON.Collider();
  48827. }
  48828. this._collider._radius = this.collisionRadius;
  48829. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48830. this._collisionTriggered = true;
  48831. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48832. }
  48833. else {
  48834. this.position.copyFrom(this._newPosition);
  48835. var up = this.upVector;
  48836. if (this.allowUpsideDown && sinb < 0) {
  48837. up = up.clone();
  48838. up = up.negate();
  48839. }
  48840. this._computeViewMatrix(this.position, target, up);
  48841. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48842. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48843. }
  48844. this._currentTarget = target;
  48845. return this._viewMatrix;
  48846. };
  48847. /**
  48848. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  48849. * @param meshes Defines the mesh to zoom on
  48850. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  48851. */
  48852. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48853. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48854. meshes = meshes || this.getScene().meshes;
  48855. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48856. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48857. this.radius = distance * this.zoomOnFactor;
  48858. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48859. };
  48860. /**
  48861. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  48862. * The target will be changed but the radius
  48863. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  48864. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  48865. */
  48866. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48867. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48868. var meshesOrMinMaxVector;
  48869. var distance;
  48870. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48871. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48872. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48873. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48874. }
  48875. else { //minMaxVector and distance
  48876. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48877. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48878. distance = minMaxVectorAndDistance.distance;
  48879. }
  48880. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48881. if (!doNotUpdateMaxZ) {
  48882. this.maxZ = distance * 2;
  48883. }
  48884. };
  48885. /**
  48886. * @override
  48887. * Override Camera.createRigCamera
  48888. */
  48889. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48890. var alphaShift = 0;
  48891. switch (this.cameraRigMode) {
  48892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48895. case BABYLON.Camera.RIG_MODE_VR:
  48896. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48897. break;
  48898. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48899. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48900. break;
  48901. }
  48902. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48903. rigCam._cameraRigParams = {};
  48904. return rigCam;
  48905. };
  48906. /**
  48907. * @hidden
  48908. * @override
  48909. * Override Camera._updateRigCameras
  48910. */
  48911. ArcRotateCamera.prototype._updateRigCameras = function () {
  48912. var camLeft = this._rigCameras[0];
  48913. var camRight = this._rigCameras[1];
  48914. camLeft.beta = camRight.beta = this.beta;
  48915. camLeft.radius = camRight.radius = this.radius;
  48916. switch (this.cameraRigMode) {
  48917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48920. case BABYLON.Camera.RIG_MODE_VR:
  48921. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48922. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48923. break;
  48924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48925. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48926. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48927. break;
  48928. }
  48929. _super.prototype._updateRigCameras.call(this);
  48930. };
  48931. /**
  48932. * Destroy the camera and release the current resources hold by it.
  48933. */
  48934. ArcRotateCamera.prototype.dispose = function () {
  48935. this.inputs.clear();
  48936. _super.prototype.dispose.call(this);
  48937. };
  48938. /**
  48939. * Gets the current object class name.
  48940. * @return the class name
  48941. */
  48942. ArcRotateCamera.prototype.getClassName = function () {
  48943. return "ArcRotateCamera";
  48944. };
  48945. __decorate([
  48946. BABYLON.serialize()
  48947. ], ArcRotateCamera.prototype, "alpha", void 0);
  48948. __decorate([
  48949. BABYLON.serialize()
  48950. ], ArcRotateCamera.prototype, "beta", void 0);
  48951. __decorate([
  48952. BABYLON.serialize()
  48953. ], ArcRotateCamera.prototype, "radius", void 0);
  48954. __decorate([
  48955. BABYLON.serializeAsVector3("target")
  48956. ], ArcRotateCamera.prototype, "_target", void 0);
  48957. __decorate([
  48958. BABYLON.serialize()
  48959. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48960. __decorate([
  48961. BABYLON.serialize()
  48962. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48963. __decorate([
  48964. BABYLON.serialize()
  48965. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48966. __decorate([
  48967. BABYLON.serialize()
  48968. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48969. __decorate([
  48970. BABYLON.serialize()
  48971. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48972. __decorate([
  48973. BABYLON.serialize()
  48974. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48975. __decorate([
  48976. BABYLON.serialize()
  48977. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48978. __decorate([
  48979. BABYLON.serialize()
  48980. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48981. __decorate([
  48982. BABYLON.serialize()
  48983. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48984. __decorate([
  48985. BABYLON.serialize()
  48986. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48987. __decorate([
  48988. BABYLON.serialize()
  48989. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48990. __decorate([
  48991. BABYLON.serialize()
  48992. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48993. __decorate([
  48994. BABYLON.serialize()
  48995. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48996. __decorate([
  48997. BABYLON.serializeAsVector3()
  48998. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48999. __decorate([
  49000. BABYLON.serialize()
  49001. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49002. __decorate([
  49003. BABYLON.serialize()
  49004. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49005. __decorate([
  49006. BABYLON.serialize()
  49007. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49008. __decorate([
  49009. BABYLON.serialize()
  49010. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49011. return ArcRotateCamera;
  49012. }(BABYLON.TargetCamera));
  49013. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49014. })(BABYLON || (BABYLON = {}));
  49015. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49016. var BABYLON;
  49017. (function (BABYLON) {
  49018. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49019. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49020. });
  49021. /**
  49022. * The HemisphericLight simulates the ambient environment light,
  49023. * so the passed direction is the light reflection direction, not the incoming direction.
  49024. */
  49025. var HemisphericLight = /** @class */ (function (_super) {
  49026. __extends(HemisphericLight, _super);
  49027. /**
  49028. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49029. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49030. * The HemisphericLight can't cast shadows.
  49031. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49032. * @param name The friendly name of the light
  49033. * @param direction The direction of the light reflection
  49034. * @param scene The scene the light belongs to
  49035. */
  49036. function HemisphericLight(name, direction, scene) {
  49037. var _this = _super.call(this, name, scene) || this;
  49038. /**
  49039. * The groundColor is the light in the opposite direction to the one specified during creation.
  49040. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  49041. */
  49042. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49043. _this.direction = direction || BABYLON.Vector3.Up();
  49044. return _this;
  49045. }
  49046. HemisphericLight.prototype._buildUniformLayout = function () {
  49047. this._uniformBuffer.addUniform("vLightData", 4);
  49048. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49049. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49050. this._uniformBuffer.addUniform("vLightGround", 3);
  49051. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49052. this._uniformBuffer.addUniform("depthValues", 2);
  49053. this._uniformBuffer.create();
  49054. };
  49055. /**
  49056. * Returns the string "HemisphericLight".
  49057. * @return The class name
  49058. */
  49059. HemisphericLight.prototype.getClassName = function () {
  49060. return "HemisphericLight";
  49061. };
  49062. /**
  49063. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49064. * Returns the updated direction.
  49065. * @param target The target the direction should point to
  49066. * @return The computed direction
  49067. */
  49068. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49069. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49070. return this.direction;
  49071. };
  49072. /**
  49073. * Returns the shadow generator associated to the light.
  49074. * @returns Always null for hemispheric lights because it does not support shadows.
  49075. */
  49076. HemisphericLight.prototype.getShadowGenerator = function () {
  49077. return null;
  49078. };
  49079. /**
  49080. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49081. * @param effect The effect to update
  49082. * @param lightIndex The index of the light in the effect to update
  49083. * @returns The hemispheric light
  49084. */
  49085. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49086. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49087. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49088. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49089. return this;
  49090. };
  49091. /**
  49092. * Computes the world matrix of the node
  49093. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49094. * @param useWasUpdatedFlag defines a reserved property
  49095. * @returns the world matrix
  49096. */
  49097. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49098. if (!this._worldMatrix) {
  49099. this._worldMatrix = BABYLON.Matrix.Identity();
  49100. }
  49101. return this._worldMatrix;
  49102. };
  49103. /**
  49104. * Returns the integer 3.
  49105. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49106. */
  49107. HemisphericLight.prototype.getTypeID = function () {
  49108. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49109. };
  49110. /**
  49111. * Prepares the list of defines specific to the light type.
  49112. * @param defines the list of defines
  49113. * @param lightIndex defines the index of the light for the effect
  49114. */
  49115. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49116. defines["HEMILIGHT" + lightIndex] = true;
  49117. };
  49118. __decorate([
  49119. BABYLON.serializeAsColor3()
  49120. ], HemisphericLight.prototype, "groundColor", void 0);
  49121. __decorate([
  49122. BABYLON.serializeAsVector3()
  49123. ], HemisphericLight.prototype, "direction", void 0);
  49124. return HemisphericLight;
  49125. }(BABYLON.Light));
  49126. BABYLON.HemisphericLight = HemisphericLight;
  49127. })(BABYLON || (BABYLON = {}));
  49128. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49129. var BABYLON;
  49130. (function (BABYLON) {
  49131. /**
  49132. * Base implementation IShadowLight
  49133. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49134. */
  49135. var ShadowLight = /** @class */ (function (_super) {
  49136. __extends(ShadowLight, _super);
  49137. function ShadowLight() {
  49138. var _this = _super !== null && _super.apply(this, arguments) || this;
  49139. _this._needProjectionMatrixCompute = true;
  49140. return _this;
  49141. }
  49142. ShadowLight.prototype._setPosition = function (value) {
  49143. this._position = value;
  49144. };
  49145. Object.defineProperty(ShadowLight.prototype, "position", {
  49146. /**
  49147. * Sets the position the shadow will be casted from. Also use as the light position for both
  49148. * point and spot lights.
  49149. */
  49150. get: function () {
  49151. return this._position;
  49152. },
  49153. /**
  49154. * Sets the position the shadow will be casted from. Also use as the light position for both
  49155. * point and spot lights.
  49156. */
  49157. set: function (value) {
  49158. this._setPosition(value);
  49159. },
  49160. enumerable: true,
  49161. configurable: true
  49162. });
  49163. ShadowLight.prototype._setDirection = function (value) {
  49164. this._direction = value;
  49165. };
  49166. Object.defineProperty(ShadowLight.prototype, "direction", {
  49167. /**
  49168. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49169. * Also use as the light direction on spot and directional lights.
  49170. */
  49171. get: function () {
  49172. return this._direction;
  49173. },
  49174. /**
  49175. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49176. * Also use as the light direction on spot and directional lights.
  49177. */
  49178. set: function (value) {
  49179. this._setDirection(value);
  49180. },
  49181. enumerable: true,
  49182. configurable: true
  49183. });
  49184. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49185. /**
  49186. * Gets the shadow projection clipping minimum z value.
  49187. */
  49188. get: function () {
  49189. return this._shadowMinZ;
  49190. },
  49191. /**
  49192. * Sets the shadow projection clipping minimum z value.
  49193. */
  49194. set: function (value) {
  49195. this._shadowMinZ = value;
  49196. this.forceProjectionMatrixCompute();
  49197. },
  49198. enumerable: true,
  49199. configurable: true
  49200. });
  49201. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49202. /**
  49203. * Sets the shadow projection clipping maximum z value.
  49204. */
  49205. get: function () {
  49206. return this._shadowMaxZ;
  49207. },
  49208. /**
  49209. * Gets the shadow projection clipping maximum z value.
  49210. */
  49211. set: function (value) {
  49212. this._shadowMaxZ = value;
  49213. this.forceProjectionMatrixCompute();
  49214. },
  49215. enumerable: true,
  49216. configurable: true
  49217. });
  49218. /**
  49219. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49220. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49221. */
  49222. ShadowLight.prototype.computeTransformedInformation = function () {
  49223. if (this.parent && this.parent.getWorldMatrix) {
  49224. if (!this.transformedPosition) {
  49225. this.transformedPosition = BABYLON.Vector3.Zero();
  49226. }
  49227. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49228. // In case the direction is present.
  49229. if (this.direction) {
  49230. if (!this.transformedDirection) {
  49231. this.transformedDirection = BABYLON.Vector3.Zero();
  49232. }
  49233. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49234. }
  49235. return true;
  49236. }
  49237. return false;
  49238. };
  49239. /**
  49240. * Return the depth scale used for the shadow map.
  49241. * @returns the depth scale.
  49242. */
  49243. ShadowLight.prototype.getDepthScale = function () {
  49244. return 50.0;
  49245. };
  49246. /**
  49247. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49248. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49249. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49250. */
  49251. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49252. return this.transformedDirection ? this.transformedDirection : this.direction;
  49253. };
  49254. /**
  49255. * Returns the ShadowLight absolute position in the World.
  49256. * @returns the position vector in world space
  49257. */
  49258. ShadowLight.prototype.getAbsolutePosition = function () {
  49259. return this.transformedPosition ? this.transformedPosition : this.position;
  49260. };
  49261. /**
  49262. * Sets the ShadowLight direction toward the passed target.
  49263. * @param target The point tot target in local space
  49264. * @returns the updated ShadowLight direction
  49265. */
  49266. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49267. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49268. return this.direction;
  49269. };
  49270. /**
  49271. * Returns the light rotation in euler definition.
  49272. * @returns the x y z rotation in local space.
  49273. */
  49274. ShadowLight.prototype.getRotation = function () {
  49275. this.direction.normalize();
  49276. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49277. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49278. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49279. };
  49280. /**
  49281. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49282. * @returns true if a cube texture needs to be use
  49283. */
  49284. ShadowLight.prototype.needCube = function () {
  49285. return false;
  49286. };
  49287. /**
  49288. * Detects if the projection matrix requires to be recomputed this frame.
  49289. * @returns true if it requires to be recomputed otherwise, false.
  49290. */
  49291. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49292. return this._needProjectionMatrixCompute;
  49293. };
  49294. /**
  49295. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49296. */
  49297. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49298. this._needProjectionMatrixCompute = true;
  49299. };
  49300. /** @hidden */
  49301. ShadowLight.prototype._initCache = function () {
  49302. _super.prototype._initCache.call(this);
  49303. this._cache.position = BABYLON.Vector3.Zero();
  49304. };
  49305. /** @hidden */
  49306. ShadowLight.prototype._isSynchronized = function () {
  49307. if (!this._cache.position.equals(this.position))
  49308. return false;
  49309. return true;
  49310. };
  49311. /**
  49312. * Computes the world matrix of the node
  49313. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49314. * @returns the world matrix
  49315. */
  49316. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49317. if (!force && this.isSynchronized()) {
  49318. this._currentRenderId = this.getScene().getRenderId();
  49319. return this._worldMatrix;
  49320. }
  49321. this._updateCache();
  49322. this._cache.position.copyFrom(this.position);
  49323. if (!this._worldMatrix) {
  49324. this._worldMatrix = BABYLON.Matrix.Identity();
  49325. }
  49326. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49327. if (this.parent && this.parent.getWorldMatrix) {
  49328. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49329. this._markSyncedWithParent();
  49330. }
  49331. // Cache the determinant
  49332. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49333. return this._worldMatrix;
  49334. };
  49335. /**
  49336. * Gets the minZ used for shadow according to both the scene and the light.
  49337. * @param activeCamera The camera we are returning the min for
  49338. * @returns the depth min z
  49339. */
  49340. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49341. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49342. };
  49343. /**
  49344. * Gets the maxZ used for shadow according to both the scene and the light.
  49345. * @param activeCamera The camera we are returning the max for
  49346. * @returns the depth max z
  49347. */
  49348. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49349. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49350. };
  49351. /**
  49352. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49353. * @param matrix The materix to updated with the projection information
  49354. * @param viewMatrix The transform matrix of the light
  49355. * @param renderList The list of mesh to render in the map
  49356. * @returns The current light
  49357. */
  49358. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49359. if (this.customProjectionMatrixBuilder) {
  49360. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49361. }
  49362. else {
  49363. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49364. }
  49365. return this;
  49366. };
  49367. __decorate([
  49368. BABYLON.serializeAsVector3()
  49369. ], ShadowLight.prototype, "position", null);
  49370. __decorate([
  49371. BABYLON.serializeAsVector3()
  49372. ], ShadowLight.prototype, "direction", null);
  49373. __decorate([
  49374. BABYLON.serialize()
  49375. ], ShadowLight.prototype, "shadowMinZ", null);
  49376. __decorate([
  49377. BABYLON.serialize()
  49378. ], ShadowLight.prototype, "shadowMaxZ", null);
  49379. return ShadowLight;
  49380. }(BABYLON.Light));
  49381. BABYLON.ShadowLight = ShadowLight;
  49382. })(BABYLON || (BABYLON = {}));
  49383. //# sourceMappingURL=babylon.shadowLight.js.map
  49384. var BABYLON;
  49385. (function (BABYLON) {
  49386. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49387. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49388. });
  49389. /**
  49390. * A point light is a light defined by an unique point in world space.
  49391. * The light is emitted in every direction from this point.
  49392. * A good example of a point light is a standard light bulb.
  49393. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49394. */
  49395. var PointLight = /** @class */ (function (_super) {
  49396. __extends(PointLight, _super);
  49397. /**
  49398. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49399. * A PointLight emits the light in every direction.
  49400. * It can cast shadows.
  49401. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49402. * ```javascript
  49403. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49404. * ```
  49405. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49406. * @param name The light friendly name
  49407. * @param position The position of the point light in the scene
  49408. * @param scene The scene the lights belongs to
  49409. */
  49410. function PointLight(name, position, scene) {
  49411. var _this = _super.call(this, name, scene) || this;
  49412. _this._shadowAngle = Math.PI / 2;
  49413. _this.position = position;
  49414. return _this;
  49415. }
  49416. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49417. /**
  49418. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49419. * This specifies what angle the shadow will use to be created.
  49420. *
  49421. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49422. */
  49423. get: function () {
  49424. return this._shadowAngle;
  49425. },
  49426. /**
  49427. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49428. * This specifies what angle the shadow will use to be created.
  49429. *
  49430. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49431. */
  49432. set: function (value) {
  49433. this._shadowAngle = value;
  49434. this.forceProjectionMatrixCompute();
  49435. },
  49436. enumerable: true,
  49437. configurable: true
  49438. });
  49439. Object.defineProperty(PointLight.prototype, "direction", {
  49440. /**
  49441. * Gets the direction if it has been set.
  49442. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49443. */
  49444. get: function () {
  49445. return this._direction;
  49446. },
  49447. /**
  49448. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49449. */
  49450. set: function (value) {
  49451. var previousNeedCube = this.needCube();
  49452. this._direction = value;
  49453. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49454. this._shadowGenerator.recreateShadowMap();
  49455. }
  49456. },
  49457. enumerable: true,
  49458. configurable: true
  49459. });
  49460. /**
  49461. * Returns the string "PointLight"
  49462. * @returns the class name
  49463. */
  49464. PointLight.prototype.getClassName = function () {
  49465. return "PointLight";
  49466. };
  49467. /**
  49468. * Returns the integer 0.
  49469. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49470. */
  49471. PointLight.prototype.getTypeID = function () {
  49472. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49473. };
  49474. /**
  49475. * Specifies wether or not the shadowmap should be a cube texture.
  49476. * @returns true if the shadowmap needs to be a cube texture.
  49477. */
  49478. PointLight.prototype.needCube = function () {
  49479. return !this.direction;
  49480. };
  49481. /**
  49482. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49483. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49484. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49485. */
  49486. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49487. if (this.direction) {
  49488. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49489. }
  49490. else {
  49491. switch (faceIndex) {
  49492. case 0:
  49493. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49494. case 1:
  49495. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49496. case 2:
  49497. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49498. case 3:
  49499. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49500. case 4:
  49501. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49502. case 5:
  49503. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49504. }
  49505. }
  49506. return BABYLON.Vector3.Zero();
  49507. };
  49508. /**
  49509. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49510. * - fov = PI / 2
  49511. * - aspect ratio : 1.0
  49512. * - z-near and far equal to the active camera minZ and maxZ.
  49513. * Returns the PointLight.
  49514. */
  49515. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49516. var activeCamera = this.getScene().activeCamera;
  49517. if (!activeCamera) {
  49518. return;
  49519. }
  49520. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49521. };
  49522. PointLight.prototype._buildUniformLayout = function () {
  49523. this._uniformBuffer.addUniform("vLightData", 4);
  49524. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49525. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49526. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49527. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49528. this._uniformBuffer.addUniform("depthValues", 2);
  49529. this._uniformBuffer.create();
  49530. };
  49531. /**
  49532. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49533. * @param effect The effect to update
  49534. * @param lightIndex The index of the light in the effect to update
  49535. * @returns The point light
  49536. */
  49537. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49538. if (this.computeTransformedInformation()) {
  49539. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49540. }
  49541. else {
  49542. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49543. }
  49544. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49545. return this;
  49546. };
  49547. /**
  49548. * Prepares the list of defines specific to the light type.
  49549. * @param defines the list of defines
  49550. * @param lightIndex defines the index of the light for the effect
  49551. */
  49552. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49553. defines["POINTLIGHT" + lightIndex] = true;
  49554. };
  49555. __decorate([
  49556. BABYLON.serialize()
  49557. ], PointLight.prototype, "shadowAngle", null);
  49558. return PointLight;
  49559. }(BABYLON.ShadowLight));
  49560. BABYLON.PointLight = PointLight;
  49561. })(BABYLON || (BABYLON = {}));
  49562. //# sourceMappingURL=babylon.pointLight.js.map
  49563. var BABYLON;
  49564. (function (BABYLON) {
  49565. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49566. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49567. });
  49568. /**
  49569. * A directional light is defined by a direction (what a surprise!).
  49570. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49571. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  49572. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49573. */
  49574. var DirectionalLight = /** @class */ (function (_super) {
  49575. __extends(DirectionalLight, _super);
  49576. /**
  49577. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49578. * The directional light is emitted from everywhere in the given direction.
  49579. * It can cast shawdows.
  49580. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49581. * @param name The friendly name of the light
  49582. * @param direction The direction of the light
  49583. * @param scene The scene the light belongs to
  49584. */
  49585. function DirectionalLight(name, direction, scene) {
  49586. var _this = _super.call(this, name, scene) || this;
  49587. _this._shadowFrustumSize = 0;
  49588. _this._shadowOrthoScale = 0.1;
  49589. /**
  49590. * Automatically compute the projection matrix to best fit (including all the casters)
  49591. * on each frame.
  49592. */
  49593. _this.autoUpdateExtends = true;
  49594. // Cache
  49595. _this._orthoLeft = Number.MAX_VALUE;
  49596. _this._orthoRight = Number.MIN_VALUE;
  49597. _this._orthoTop = Number.MIN_VALUE;
  49598. _this._orthoBottom = Number.MAX_VALUE;
  49599. _this.position = direction.scale(-1.0);
  49600. _this.direction = direction;
  49601. return _this;
  49602. }
  49603. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49604. /**
  49605. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49606. */
  49607. get: function () {
  49608. return this._shadowFrustumSize;
  49609. },
  49610. /**
  49611. * Specifies a fix frustum size for the shadow generation.
  49612. */
  49613. set: function (value) {
  49614. this._shadowFrustumSize = value;
  49615. this.forceProjectionMatrixCompute();
  49616. },
  49617. enumerable: true,
  49618. configurable: true
  49619. });
  49620. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49621. /**
  49622. * Gets the shadow projection scale against the optimal computed one.
  49623. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49624. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49625. */
  49626. get: function () {
  49627. return this._shadowOrthoScale;
  49628. },
  49629. /**
  49630. * Sets the shadow projection scale against the optimal computed one.
  49631. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49632. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49633. */
  49634. set: function (value) {
  49635. this._shadowOrthoScale = value;
  49636. this.forceProjectionMatrixCompute();
  49637. },
  49638. enumerable: true,
  49639. configurable: true
  49640. });
  49641. /**
  49642. * Returns the string "DirectionalLight".
  49643. * @return The class name
  49644. */
  49645. DirectionalLight.prototype.getClassName = function () {
  49646. return "DirectionalLight";
  49647. };
  49648. /**
  49649. * Returns the integer 1.
  49650. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49651. */
  49652. DirectionalLight.prototype.getTypeID = function () {
  49653. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49654. };
  49655. /**
  49656. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49657. * Returns the DirectionalLight Shadow projection matrix.
  49658. */
  49659. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49660. if (this.shadowFrustumSize > 0) {
  49661. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49662. }
  49663. else {
  49664. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49665. }
  49666. };
  49667. /**
  49668. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49669. * Returns the DirectionalLight Shadow projection matrix.
  49670. */
  49671. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49672. var activeCamera = this.getScene().activeCamera;
  49673. if (!activeCamera) {
  49674. return;
  49675. }
  49676. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49677. };
  49678. /**
  49679. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49680. * Returns the DirectionalLight Shadow projection matrix.
  49681. */
  49682. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49683. var activeCamera = this.getScene().activeCamera;
  49684. if (!activeCamera) {
  49685. return;
  49686. }
  49687. // Check extends
  49688. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49689. var tempVector3 = BABYLON.Vector3.Zero();
  49690. this._orthoLeft = Number.MAX_VALUE;
  49691. this._orthoRight = Number.MIN_VALUE;
  49692. this._orthoTop = Number.MIN_VALUE;
  49693. this._orthoBottom = Number.MAX_VALUE;
  49694. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49695. var mesh = renderList[meshIndex];
  49696. if (!mesh) {
  49697. continue;
  49698. }
  49699. var boundingInfo = mesh.getBoundingInfo();
  49700. var boundingBox = boundingInfo.boundingBox;
  49701. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49702. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49703. if (tempVector3.x < this._orthoLeft)
  49704. this._orthoLeft = tempVector3.x;
  49705. if (tempVector3.y < this._orthoBottom)
  49706. this._orthoBottom = tempVector3.y;
  49707. if (tempVector3.x > this._orthoRight)
  49708. this._orthoRight = tempVector3.x;
  49709. if (tempVector3.y > this._orthoTop)
  49710. this._orthoTop = tempVector3.y;
  49711. }
  49712. }
  49713. }
  49714. var xOffset = this._orthoRight - this._orthoLeft;
  49715. var yOffset = this._orthoTop - this._orthoBottom;
  49716. 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);
  49717. };
  49718. DirectionalLight.prototype._buildUniformLayout = function () {
  49719. this._uniformBuffer.addUniform("vLightData", 4);
  49720. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49721. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49722. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49723. this._uniformBuffer.addUniform("depthValues", 2);
  49724. this._uniformBuffer.create();
  49725. };
  49726. /**
  49727. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49728. * @param effect The effect to update
  49729. * @param lightIndex The index of the light in the effect to update
  49730. * @returns The directional light
  49731. */
  49732. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49733. if (this.computeTransformedInformation()) {
  49734. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49735. return this;
  49736. }
  49737. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49738. return this;
  49739. };
  49740. /**
  49741. * Gets the minZ used for shadow according to both the scene and the light.
  49742. *
  49743. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49744. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49745. * @param activeCamera The camera we are returning the min for
  49746. * @returns the depth min z
  49747. */
  49748. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49749. return 1;
  49750. };
  49751. /**
  49752. * Gets the maxZ used for shadow according to both the scene and the light.
  49753. *
  49754. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49755. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49756. * @param activeCamera The camera we are returning the max for
  49757. * @returns the depth max z
  49758. */
  49759. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49760. return 1;
  49761. };
  49762. /**
  49763. * Prepares the list of defines specific to the light type.
  49764. * @param defines the list of defines
  49765. * @param lightIndex defines the index of the light for the effect
  49766. */
  49767. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49768. defines["DIRLIGHT" + lightIndex] = true;
  49769. };
  49770. __decorate([
  49771. BABYLON.serialize()
  49772. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49773. __decorate([
  49774. BABYLON.serialize()
  49775. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49776. __decorate([
  49777. BABYLON.serialize()
  49778. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49779. return DirectionalLight;
  49780. }(BABYLON.ShadowLight));
  49781. BABYLON.DirectionalLight = DirectionalLight;
  49782. })(BABYLON || (BABYLON = {}));
  49783. //# sourceMappingURL=babylon.directionalLight.js.map
  49784. var BABYLON;
  49785. (function (BABYLON) {
  49786. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49787. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49788. });
  49789. /**
  49790. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49791. * These values define a cone of light starting from the position, emitting toward the direction.
  49792. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49793. * and the exponent defines the speed of the decay of the light with distance (reach).
  49794. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49795. */
  49796. var SpotLight = /** @class */ (function (_super) {
  49797. __extends(SpotLight, _super);
  49798. /**
  49799. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49800. * It can cast shadows.
  49801. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49802. * @param name The light friendly name
  49803. * @param position The position of the spot light in the scene
  49804. * @param direction The direction of the light in the scene
  49805. * @param angle The cone angle of the light in Radians
  49806. * @param exponent The light decay speed with the distance from the emission spot
  49807. * @param scene The scene the lights belongs to
  49808. */
  49809. function SpotLight(name, position, direction, angle, exponent, scene) {
  49810. var _this = _super.call(this, name, scene) || this;
  49811. _this._innerAngle = 0;
  49812. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49813. _this._projectionTextureLightNear = 1e-6;
  49814. _this._projectionTextureLightFar = 1000.0;
  49815. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49816. _this._projectionTextureViewLightDirty = true;
  49817. _this._projectionTextureProjectionLightDirty = true;
  49818. _this._projectionTextureDirty = true;
  49819. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49820. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49821. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49822. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  49823. _this.position = position;
  49824. _this.direction = direction;
  49825. _this.angle = angle;
  49826. _this.exponent = exponent;
  49827. return _this;
  49828. }
  49829. Object.defineProperty(SpotLight.prototype, "angle", {
  49830. /**
  49831. * Gets the cone angle of the spot light in Radians.
  49832. */
  49833. get: function () {
  49834. return this._angle;
  49835. },
  49836. /**
  49837. * Sets the cone angle of the spot light in Radians.
  49838. */
  49839. set: function (value) {
  49840. this._angle = value;
  49841. this._cosHalfAngle = Math.cos(value * 0.5);
  49842. this._projectionTextureProjectionLightDirty = true;
  49843. this.forceProjectionMatrixCompute();
  49844. this._computeAngleValues();
  49845. },
  49846. enumerable: true,
  49847. configurable: true
  49848. });
  49849. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49850. /**
  49851. * Only used in gltf falloff mode, this defines the angle where
  49852. * the directional falloff will start before cutting at angle which could be seen
  49853. * as outer angle.
  49854. */
  49855. get: function () {
  49856. return this._innerAngle;
  49857. },
  49858. /**
  49859. * Only used in gltf falloff mode, this defines the angle where
  49860. * the directional falloff will start before cutting at angle which could be seen
  49861. * as outer angle.
  49862. */
  49863. set: function (value) {
  49864. this._innerAngle = value;
  49865. this._computeAngleValues();
  49866. },
  49867. enumerable: true,
  49868. configurable: true
  49869. });
  49870. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49871. /**
  49872. * Allows scaling the angle of the light for shadow generation only.
  49873. */
  49874. get: function () {
  49875. return this._shadowAngleScale;
  49876. },
  49877. /**
  49878. * Allows scaling the angle of the light for shadow generation only.
  49879. */
  49880. set: function (value) {
  49881. this._shadowAngleScale = value;
  49882. this.forceProjectionMatrixCompute();
  49883. },
  49884. enumerable: true,
  49885. configurable: true
  49886. });
  49887. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49888. /**
  49889. * Allows reading the projecton texture
  49890. */
  49891. get: function () {
  49892. return this._projectionTextureMatrix;
  49893. },
  49894. enumerable: true,
  49895. configurable: true
  49896. });
  49897. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49898. /**
  49899. * Gets the near clip of the Spotlight for texture projection.
  49900. */
  49901. get: function () {
  49902. return this._projectionTextureLightNear;
  49903. },
  49904. /**
  49905. * Sets the near clip of the Spotlight for texture projection.
  49906. */
  49907. set: function (value) {
  49908. this._projectionTextureLightNear = value;
  49909. this._projectionTextureProjectionLightDirty = true;
  49910. },
  49911. enumerable: true,
  49912. configurable: true
  49913. });
  49914. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49915. /**
  49916. * Gets the far clip of the Spotlight for texture projection.
  49917. */
  49918. get: function () {
  49919. return this._projectionTextureLightFar;
  49920. },
  49921. /**
  49922. * Sets the far clip of the Spotlight for texture projection.
  49923. */
  49924. set: function (value) {
  49925. this._projectionTextureLightFar = value;
  49926. this._projectionTextureProjectionLightDirty = true;
  49927. },
  49928. enumerable: true,
  49929. configurable: true
  49930. });
  49931. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49932. /**
  49933. * Gets the Up vector of the Spotlight for texture projection.
  49934. */
  49935. get: function () {
  49936. return this._projectionTextureUpDirection;
  49937. },
  49938. /**
  49939. * Sets the Up vector of the Spotlight for texture projection.
  49940. */
  49941. set: function (value) {
  49942. this._projectionTextureUpDirection = value;
  49943. this._projectionTextureProjectionLightDirty = true;
  49944. },
  49945. enumerable: true,
  49946. configurable: true
  49947. });
  49948. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49949. /**
  49950. * Gets the projection texture of the light.
  49951. */
  49952. get: function () {
  49953. return this._projectionTexture;
  49954. },
  49955. /**
  49956. * Sets the projection texture of the light.
  49957. */
  49958. set: function (value) {
  49959. this._projectionTexture = value;
  49960. this._projectionTextureDirty = true;
  49961. },
  49962. enumerable: true,
  49963. configurable: true
  49964. });
  49965. /**
  49966. * Returns the string "SpotLight".
  49967. * @returns the class name
  49968. */
  49969. SpotLight.prototype.getClassName = function () {
  49970. return "SpotLight";
  49971. };
  49972. /**
  49973. * Returns the integer 2.
  49974. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49975. */
  49976. SpotLight.prototype.getTypeID = function () {
  49977. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49978. };
  49979. /**
  49980. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49981. */
  49982. SpotLight.prototype._setDirection = function (value) {
  49983. _super.prototype._setDirection.call(this, value);
  49984. this._projectionTextureViewLightDirty = true;
  49985. };
  49986. /**
  49987. * Overrides the position setter to recompute the projection texture view light Matrix.
  49988. */
  49989. SpotLight.prototype._setPosition = function (value) {
  49990. _super.prototype._setPosition.call(this, value);
  49991. this._projectionTextureViewLightDirty = true;
  49992. };
  49993. /**
  49994. * 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.
  49995. * Returns the SpotLight.
  49996. */
  49997. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49998. var activeCamera = this.getScene().activeCamera;
  49999. if (!activeCamera) {
  50000. return;
  50001. }
  50002. this._shadowAngleScale = this._shadowAngleScale || 1;
  50003. var angle = this._shadowAngleScale * this._angle;
  50004. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50005. };
  50006. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50007. this._projectionTextureViewLightDirty = false;
  50008. this._projectionTextureDirty = true;
  50009. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50010. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50011. };
  50012. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50013. this._projectionTextureProjectionLightDirty = false;
  50014. this._projectionTextureDirty = true;
  50015. var light_far = this.projectionTextureLightFar;
  50016. var light_near = this.projectionTextureLightNear;
  50017. var P = light_far / (light_far - light_near);
  50018. var Q = -P * light_near;
  50019. var S = 1.0 / Math.tan(this._angle / 2.0);
  50020. var A = 1.0;
  50021. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  50022. };
  50023. /**
  50024. * Main function for light texture projection matrix computing.
  50025. */
  50026. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50027. this._projectionTextureDirty = false;
  50028. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50029. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50030. };
  50031. SpotLight.prototype._buildUniformLayout = function () {
  50032. this._uniformBuffer.addUniform("vLightData", 4);
  50033. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50034. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50035. this._uniformBuffer.addUniform("vLightDirection", 3);
  50036. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50037. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50038. this._uniformBuffer.addUniform("depthValues", 2);
  50039. this._uniformBuffer.create();
  50040. };
  50041. SpotLight.prototype._computeAngleValues = function () {
  50042. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50043. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50044. };
  50045. /**
  50046. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50047. * @param effect The effect to update
  50048. * @param lightIndex The index of the light in the effect to update
  50049. * @returns The spot light
  50050. */
  50051. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50052. var normalizeDirection;
  50053. if (this.computeTransformedInformation()) {
  50054. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50055. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50056. }
  50057. else {
  50058. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50059. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50060. }
  50061. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50062. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50063. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50064. if (this._projectionTextureViewLightDirty) {
  50065. this._computeProjectionTextureViewLightMatrix();
  50066. }
  50067. if (this._projectionTextureProjectionLightDirty) {
  50068. this._computeProjectionTextureProjectionLightMatrix();
  50069. }
  50070. if (this._projectionTextureDirty) {
  50071. this._computeProjectionTextureMatrix();
  50072. }
  50073. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50074. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50075. }
  50076. return this;
  50077. };
  50078. /**
  50079. * Disposes the light and the associated resources.
  50080. */
  50081. SpotLight.prototype.dispose = function () {
  50082. _super.prototype.dispose.call(this);
  50083. if (this._projectionTexture) {
  50084. this._projectionTexture.dispose();
  50085. }
  50086. };
  50087. /**
  50088. * Prepares the list of defines specific to the light type.
  50089. * @param defines the list of defines
  50090. * @param lightIndex defines the index of the light for the effect
  50091. */
  50092. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50093. defines["SPOTLIGHT" + lightIndex] = true;
  50094. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50095. };
  50096. __decorate([
  50097. BABYLON.serialize()
  50098. ], SpotLight.prototype, "angle", null);
  50099. __decorate([
  50100. BABYLON.serialize()
  50101. ], SpotLight.prototype, "innerAngle", null);
  50102. __decorate([
  50103. BABYLON.serialize()
  50104. ], SpotLight.prototype, "shadowAngleScale", null);
  50105. __decorate([
  50106. BABYLON.serialize()
  50107. ], SpotLight.prototype, "exponent", void 0);
  50108. __decorate([
  50109. BABYLON.serialize()
  50110. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50111. __decorate([
  50112. BABYLON.serialize()
  50113. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50114. __decorate([
  50115. BABYLON.serialize()
  50116. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50117. __decorate([
  50118. BABYLON.serializeAsTexture("projectedLightTexture")
  50119. ], SpotLight.prototype, "_projectionTexture", void 0);
  50120. return SpotLight;
  50121. }(BABYLON.ShadowLight));
  50122. BABYLON.SpotLight = SpotLight;
  50123. })(BABYLON || (BABYLON = {}));
  50124. //# sourceMappingURL=babylon.spotLight.js.map
  50125. var BABYLON;
  50126. (function (BABYLON) {
  50127. /**
  50128. * Class used to override all child animations of a given target
  50129. */
  50130. var AnimationPropertiesOverride = /** @class */ (function () {
  50131. function AnimationPropertiesOverride() {
  50132. /**
  50133. * Gets or sets a value indicating if animation blending must be used
  50134. */
  50135. this.enableBlending = false;
  50136. /**
  50137. * Gets or sets the blending speed to use when enableBlending is true
  50138. */
  50139. this.blendingSpeed = 0.01;
  50140. /**
  50141. * Gets or sets the default loop mode to use
  50142. */
  50143. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50144. }
  50145. return AnimationPropertiesOverride;
  50146. }());
  50147. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50148. })(BABYLON || (BABYLON = {}));
  50149. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50150. var BABYLON;
  50151. (function (BABYLON) {
  50152. /**
  50153. * Represents the range of an animation
  50154. */
  50155. var AnimationRange = /** @class */ (function () {
  50156. /**
  50157. * Initializes the range of an animation
  50158. * @param name The name of the animation range
  50159. * @param from The starting frame of the animation
  50160. * @param to The ending frame of the animation
  50161. */
  50162. function AnimationRange(
  50163. /**The name of the animation range**/
  50164. name,
  50165. /**The starting frame of the animation */
  50166. from,
  50167. /**The ending frame of the animation*/
  50168. to) {
  50169. this.name = name;
  50170. this.from = from;
  50171. this.to = to;
  50172. }
  50173. /**
  50174. * Makes a copy of the animation range
  50175. * @returns A copy of the animation range
  50176. */
  50177. AnimationRange.prototype.clone = function () {
  50178. return new AnimationRange(this.name, this.from, this.to);
  50179. };
  50180. return AnimationRange;
  50181. }());
  50182. BABYLON.AnimationRange = AnimationRange;
  50183. /**
  50184. * Composed of a frame, and an action function
  50185. */
  50186. var AnimationEvent = /** @class */ (function () {
  50187. /**
  50188. * Initializes the animation event
  50189. * @param frame The frame for which the event is triggered
  50190. * @param action The event to perform when triggered
  50191. * @param onlyOnce Specifies if the event should be triggered only once
  50192. */
  50193. function AnimationEvent(
  50194. /** The frame for which the event is triggered **/
  50195. frame,
  50196. /** The event to perform when triggered **/
  50197. action,
  50198. /** Specifies if the event should be triggered only once**/
  50199. onlyOnce) {
  50200. this.frame = frame;
  50201. this.action = action;
  50202. this.onlyOnce = onlyOnce;
  50203. /**
  50204. * Specifies if the animation event is done
  50205. */
  50206. this.isDone = false;
  50207. }
  50208. /** @hidden */
  50209. AnimationEvent.prototype._clone = function () {
  50210. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50211. };
  50212. return AnimationEvent;
  50213. }());
  50214. BABYLON.AnimationEvent = AnimationEvent;
  50215. /**
  50216. * A cursor which tracks a point on a path
  50217. */
  50218. var PathCursor = /** @class */ (function () {
  50219. /**
  50220. * Initializes the path cursor
  50221. * @param path The path to track
  50222. */
  50223. function PathCursor(path) {
  50224. this.path = path;
  50225. /**
  50226. * Stores path cursor callbacks for when an onchange event is triggered
  50227. */
  50228. this._onchange = new Array();
  50229. /**
  50230. * The value of the path cursor
  50231. */
  50232. this.value = 0;
  50233. /**
  50234. * The animation array of the path cursor
  50235. */
  50236. this.animations = new Array();
  50237. }
  50238. /**
  50239. * Gets the cursor point on the path
  50240. * @returns A point on the path cursor at the cursor location
  50241. */
  50242. PathCursor.prototype.getPoint = function () {
  50243. var point = this.path.getPointAtLengthPosition(this.value);
  50244. return new BABYLON.Vector3(point.x, 0, point.y);
  50245. };
  50246. /**
  50247. * Moves the cursor ahead by the step amount
  50248. * @param step The amount to move the cursor forward
  50249. * @returns This path cursor
  50250. */
  50251. PathCursor.prototype.moveAhead = function (step) {
  50252. if (step === void 0) { step = 0.002; }
  50253. this.move(step);
  50254. return this;
  50255. };
  50256. /**
  50257. * Moves the cursor behind by the step amount
  50258. * @param step The amount to move the cursor back
  50259. * @returns This path cursor
  50260. */
  50261. PathCursor.prototype.moveBack = function (step) {
  50262. if (step === void 0) { step = 0.002; }
  50263. this.move(-step);
  50264. return this;
  50265. };
  50266. /**
  50267. * Moves the cursor by the step amount
  50268. * If the step amount is greater than one, an exception is thrown
  50269. * @param step The amount to move the cursor
  50270. * @returns This path cursor
  50271. */
  50272. PathCursor.prototype.move = function (step) {
  50273. if (Math.abs(step) > 1) {
  50274. throw "step size should be less than 1.";
  50275. }
  50276. this.value += step;
  50277. this.ensureLimits();
  50278. this.raiseOnChange();
  50279. return this;
  50280. };
  50281. /**
  50282. * Ensures that the value is limited between zero and one
  50283. * @returns This path cursor
  50284. */
  50285. PathCursor.prototype.ensureLimits = function () {
  50286. while (this.value > 1) {
  50287. this.value -= 1;
  50288. }
  50289. while (this.value < 0) {
  50290. this.value += 1;
  50291. }
  50292. return this;
  50293. };
  50294. /**
  50295. * Runs onchange callbacks on change (used by the animation engine)
  50296. * @returns This path cursor
  50297. */
  50298. PathCursor.prototype.raiseOnChange = function () {
  50299. var _this = this;
  50300. this._onchange.forEach(function (f) { return f(_this); });
  50301. return this;
  50302. };
  50303. /**
  50304. * Executes a function on change
  50305. * @param f A path cursor onchange callback
  50306. * @returns This path cursor
  50307. */
  50308. PathCursor.prototype.onchange = function (f) {
  50309. this._onchange.push(f);
  50310. return this;
  50311. };
  50312. return PathCursor;
  50313. }());
  50314. BABYLON.PathCursor = PathCursor;
  50315. /**
  50316. * Enum for the animation key frame interpolation type
  50317. */
  50318. var AnimationKeyInterpolation;
  50319. (function (AnimationKeyInterpolation) {
  50320. /**
  50321. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50322. */
  50323. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50324. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50325. /**
  50326. * Class used to store any kind of animation
  50327. */
  50328. var Animation = /** @class */ (function () {
  50329. /**
  50330. * Initializes the animation
  50331. * @param name Name of the animation
  50332. * @param targetProperty Property to animate
  50333. * @param framePerSecond The frames per second of the animation
  50334. * @param dataType The data type of the animation
  50335. * @param loopMode The loop mode of the animation
  50336. * @param enableBlendings Specifies if blending should be enabled
  50337. */
  50338. function Animation(
  50339. /**Name of the animation */
  50340. name,
  50341. /**Property to animate */
  50342. targetProperty,
  50343. /**The frames per second of the animation */
  50344. framePerSecond,
  50345. /**The data type of the animation */
  50346. dataType,
  50347. /**The loop mode of the animation */
  50348. loopMode,
  50349. /**Specifies if blending should be enabled */
  50350. enableBlending) {
  50351. this.name = name;
  50352. this.targetProperty = targetProperty;
  50353. this.framePerSecond = framePerSecond;
  50354. this.dataType = dataType;
  50355. this.loopMode = loopMode;
  50356. this.enableBlending = enableBlending;
  50357. /**
  50358. * @hidden Internal use only
  50359. */
  50360. this._runtimeAnimations = new Array();
  50361. /**
  50362. * The set of event that will be linked to this animation
  50363. */
  50364. this._events = new Array();
  50365. /**
  50366. * Stores the blending speed of the animation
  50367. */
  50368. this.blendingSpeed = 0.01;
  50369. /**
  50370. * Stores the animation ranges for the animation
  50371. */
  50372. this._ranges = {};
  50373. this.targetPropertyPath = targetProperty.split(".");
  50374. this.dataType = dataType;
  50375. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50376. }
  50377. /**
  50378. * @hidden Internal use
  50379. */
  50380. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50381. var dataType = undefined;
  50382. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50383. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50384. }
  50385. else if (from instanceof BABYLON.Quaternion) {
  50386. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50387. }
  50388. else if (from instanceof BABYLON.Vector3) {
  50389. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50390. }
  50391. else if (from instanceof BABYLON.Vector2) {
  50392. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50393. }
  50394. else if (from instanceof BABYLON.Color3) {
  50395. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50396. }
  50397. else if (from instanceof BABYLON.Size) {
  50398. dataType = Animation.ANIMATIONTYPE_SIZE;
  50399. }
  50400. if (dataType == undefined) {
  50401. return null;
  50402. }
  50403. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50404. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50405. animation.setKeys(keys);
  50406. if (easingFunction !== undefined) {
  50407. animation.setEasingFunction(easingFunction);
  50408. }
  50409. return animation;
  50410. };
  50411. /**
  50412. * Sets up an animation
  50413. * @param property The property to animate
  50414. * @param animationType The animation type to apply
  50415. * @param framePerSecond The frames per second of the animation
  50416. * @param easingFunction The easing function used in the animation
  50417. * @returns The created animation
  50418. */
  50419. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50420. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50421. animation.setEasingFunction(easingFunction);
  50422. return animation;
  50423. };
  50424. /**
  50425. * Create and start an animation on a node
  50426. * @param name defines the name of the global animation that will be run on all nodes
  50427. * @param node defines the root node where the animation will take place
  50428. * @param targetProperty defines property to animate
  50429. * @param framePerSecond defines the number of frame per second yo use
  50430. * @param totalFrame defines the number of frames in total
  50431. * @param from defines the initial value
  50432. * @param to defines the final value
  50433. * @param loopMode defines which loop mode you want to use (off by default)
  50434. * @param easingFunction defines the easing function to use (linear by default)
  50435. * @param onAnimationEnd defines the callback to call when animation end
  50436. * @returns the animatable created for this animation
  50437. */
  50438. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50439. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50440. if (!animation) {
  50441. return null;
  50442. }
  50443. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50444. };
  50445. /**
  50446. * Create and start an animation on a node and its descendants
  50447. * @param name defines the name of the global animation that will be run on all nodes
  50448. * @param node defines the root node where the animation will take place
  50449. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50450. * @param targetProperty defines property to animate
  50451. * @param framePerSecond defines the number of frame per second to use
  50452. * @param totalFrame defines the number of frames in total
  50453. * @param from defines the initial value
  50454. * @param to defines the final value
  50455. * @param loopMode defines which loop mode you want to use (off by default)
  50456. * @param easingFunction defines the easing function to use (linear by default)
  50457. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50458. * @returns the list of animatables created for all nodes
  50459. * @example https://www.babylonjs-playground.com/#MH0VLI
  50460. */
  50461. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50462. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50463. if (!animation) {
  50464. return null;
  50465. }
  50466. var scene = node.getScene();
  50467. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50468. };
  50469. /**
  50470. * Creates a new animation, merges it with the existing animations and starts it
  50471. * @param name Name of the animation
  50472. * @param node Node which contains the scene that begins the animations
  50473. * @param targetProperty Specifies which property to animate
  50474. * @param framePerSecond The frames per second of the animation
  50475. * @param totalFrame The total number of frames
  50476. * @param from The frame at the beginning of the animation
  50477. * @param to The frame at the end of the animation
  50478. * @param loopMode Specifies the loop mode of the animation
  50479. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50480. * @param onAnimationEnd Callback to run once the animation is complete
  50481. * @returns Nullable animation
  50482. */
  50483. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50484. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50485. if (!animation) {
  50486. return null;
  50487. }
  50488. node.animations.push(animation);
  50489. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50490. };
  50491. /**
  50492. * Transition property of an host to the target Value
  50493. * @param property The property to transition
  50494. * @param targetValue The target Value of the property
  50495. * @param host The object where the property to animate belongs
  50496. * @param scene Scene used to run the animation
  50497. * @param frameRate Framerate (in frame/s) to use
  50498. * @param transition The transition type we want to use
  50499. * @param duration The duration of the animation, in milliseconds
  50500. * @param onAnimationEnd Callback trigger at the end of the animation
  50501. * @returns Nullable animation
  50502. */
  50503. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50504. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50505. if (duration <= 0) {
  50506. host[property] = targetValue;
  50507. if (onAnimationEnd) {
  50508. onAnimationEnd();
  50509. }
  50510. return null;
  50511. }
  50512. var endFrame = frameRate * (duration / 1000);
  50513. transition.setKeys([{
  50514. frame: 0,
  50515. value: host[property].clone ? host[property].clone() : host[property]
  50516. },
  50517. {
  50518. frame: endFrame,
  50519. value: targetValue
  50520. }]);
  50521. if (!host.animations) {
  50522. host.animations = [];
  50523. }
  50524. host.animations.push(transition);
  50525. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50526. animation.onAnimationEnd = onAnimationEnd;
  50527. return animation;
  50528. };
  50529. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50530. /**
  50531. * Return the array of runtime animations currently using this animation
  50532. */
  50533. get: function () {
  50534. return this._runtimeAnimations;
  50535. },
  50536. enumerable: true,
  50537. configurable: true
  50538. });
  50539. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50540. /**
  50541. * Specifies if any of the runtime animations are currently running
  50542. */
  50543. get: function () {
  50544. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50545. var runtimeAnimation = _a[_i];
  50546. if (!runtimeAnimation.isStopped) {
  50547. return true;
  50548. }
  50549. }
  50550. return false;
  50551. },
  50552. enumerable: true,
  50553. configurable: true
  50554. });
  50555. // Methods
  50556. /**
  50557. * Converts the animation to a string
  50558. * @param fullDetails support for multiple levels of logging within scene loading
  50559. * @returns String form of the animation
  50560. */
  50561. Animation.prototype.toString = function (fullDetails) {
  50562. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50563. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50564. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50565. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50566. if (fullDetails) {
  50567. ret += ", Ranges: {";
  50568. var first = true;
  50569. for (var name in this._ranges) {
  50570. if (first) {
  50571. ret += ", ";
  50572. first = false;
  50573. }
  50574. ret += name;
  50575. }
  50576. ret += "}";
  50577. }
  50578. return ret;
  50579. };
  50580. /**
  50581. * Add an event to this animation
  50582. * @param event Event to add
  50583. */
  50584. Animation.prototype.addEvent = function (event) {
  50585. this._events.push(event);
  50586. };
  50587. /**
  50588. * Remove all events found at the given frame
  50589. * @param frame The frame to remove events from
  50590. */
  50591. Animation.prototype.removeEvents = function (frame) {
  50592. for (var index = 0; index < this._events.length; index++) {
  50593. if (this._events[index].frame === frame) {
  50594. this._events.splice(index, 1);
  50595. index--;
  50596. }
  50597. }
  50598. };
  50599. /**
  50600. * Retrieves all the events from the animation
  50601. * @returns Events from the animation
  50602. */
  50603. Animation.prototype.getEvents = function () {
  50604. return this._events;
  50605. };
  50606. /**
  50607. * Creates an animation range
  50608. * @param name Name of the animation range
  50609. * @param from Starting frame of the animation range
  50610. * @param to Ending frame of the animation
  50611. */
  50612. Animation.prototype.createRange = function (name, from, to) {
  50613. // check name not already in use; could happen for bones after serialized
  50614. if (!this._ranges[name]) {
  50615. this._ranges[name] = new AnimationRange(name, from, to);
  50616. }
  50617. };
  50618. /**
  50619. * Deletes an animation range by name
  50620. * @param name Name of the animation range to delete
  50621. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50622. */
  50623. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50624. if (deleteFrames === void 0) { deleteFrames = true; }
  50625. var range = this._ranges[name];
  50626. if (!range) {
  50627. return;
  50628. }
  50629. if (deleteFrames) {
  50630. var from = range.from;
  50631. var to = range.to;
  50632. // this loop MUST go high to low for multiple splices to work
  50633. for (var key = this._keys.length - 1; key >= 0; key--) {
  50634. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50635. this._keys.splice(key, 1);
  50636. }
  50637. }
  50638. }
  50639. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50640. };
  50641. /**
  50642. * Gets the animation range by name, or null if not defined
  50643. * @param name Name of the animation range
  50644. * @returns Nullable animation range
  50645. */
  50646. Animation.prototype.getRange = function (name) {
  50647. return this._ranges[name];
  50648. };
  50649. /**
  50650. * Gets the key frames from the animation
  50651. * @returns The key frames of the animation
  50652. */
  50653. Animation.prototype.getKeys = function () {
  50654. return this._keys;
  50655. };
  50656. /**
  50657. * Gets the highest frame rate of the animation
  50658. * @returns Highest frame rate of the animation
  50659. */
  50660. Animation.prototype.getHighestFrame = function () {
  50661. var ret = 0;
  50662. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50663. if (ret < this._keys[key].frame) {
  50664. ret = this._keys[key].frame;
  50665. }
  50666. }
  50667. return ret;
  50668. };
  50669. /**
  50670. * Gets the easing function of the animation
  50671. * @returns Easing function of the animation
  50672. */
  50673. Animation.prototype.getEasingFunction = function () {
  50674. return this._easingFunction;
  50675. };
  50676. /**
  50677. * Sets the easing function of the animation
  50678. * @param easingFunction A custom mathematical formula for animation
  50679. */
  50680. Animation.prototype.setEasingFunction = function (easingFunction) {
  50681. this._easingFunction = easingFunction;
  50682. };
  50683. /**
  50684. * Interpolates a scalar linearly
  50685. * @param startValue Start value of the animation curve
  50686. * @param endValue End value of the animation curve
  50687. * @param gradient Scalar amount to interpolate
  50688. * @returns Interpolated scalar value
  50689. */
  50690. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50691. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50692. };
  50693. /**
  50694. * Interpolates a scalar cubically
  50695. * @param startValue Start value of the animation curve
  50696. * @param outTangent End tangent of the animation
  50697. * @param endValue End value of the animation curve
  50698. * @param inTangent Start tangent of the animation curve
  50699. * @param gradient Scalar amount to interpolate
  50700. * @returns Interpolated scalar value
  50701. */
  50702. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50703. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50704. };
  50705. /**
  50706. * Interpolates a quaternion using a spherical linear interpolation
  50707. * @param startValue Start value of the animation curve
  50708. * @param endValue End value of the animation curve
  50709. * @param gradient Scalar amount to interpolate
  50710. * @returns Interpolated quaternion value
  50711. */
  50712. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50713. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50714. };
  50715. /**
  50716. * Interpolates a quaternion cubically
  50717. * @param startValue Start value of the animation curve
  50718. * @param outTangent End tangent of the animation curve
  50719. * @param endValue End value of the animation curve
  50720. * @param inTangent Start tangent of the animation curve
  50721. * @param gradient Scalar amount to interpolate
  50722. * @returns Interpolated quaternion value
  50723. */
  50724. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50725. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50726. };
  50727. /**
  50728. * Interpolates a Vector3 linearl
  50729. * @param startValue Start value of the animation curve
  50730. * @param endValue End value of the animation curve
  50731. * @param gradient Scalar amount to interpolate
  50732. * @returns Interpolated scalar value
  50733. */
  50734. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50735. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50736. };
  50737. /**
  50738. * Interpolates a Vector3 cubically
  50739. * @param startValue Start value of the animation curve
  50740. * @param outTangent End tangent of the animation
  50741. * @param endValue End value of the animation curve
  50742. * @param inTangent Start tangent of the animation curve
  50743. * @param gradient Scalar amount to interpolate
  50744. * @returns InterpolatedVector3 value
  50745. */
  50746. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50747. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50748. };
  50749. /**
  50750. * Interpolates a Vector2 linearly
  50751. * @param startValue Start value of the animation curve
  50752. * @param endValue End value of the animation curve
  50753. * @param gradient Scalar amount to interpolate
  50754. * @returns Interpolated Vector2 value
  50755. */
  50756. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50757. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50758. };
  50759. /**
  50760. * Interpolates a Vector2 cubically
  50761. * @param startValue Start value of the animation curve
  50762. * @param outTangent End tangent of the animation
  50763. * @param endValue End value of the animation curve
  50764. * @param inTangent Start tangent of the animation curve
  50765. * @param gradient Scalar amount to interpolate
  50766. * @returns Interpolated Vector2 value
  50767. */
  50768. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50769. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50770. };
  50771. /**
  50772. * Interpolates a size linearly
  50773. * @param startValue Start value of the animation curve
  50774. * @param endValue End value of the animation curve
  50775. * @param gradient Scalar amount to interpolate
  50776. * @returns Interpolated Size value
  50777. */
  50778. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50779. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50780. };
  50781. /**
  50782. * Interpolates a Color3 linearly
  50783. * @param startValue Start value of the animation curve
  50784. * @param endValue End value of the animation curve
  50785. * @param gradient Scalar amount to interpolate
  50786. * @returns Interpolated Color3 value
  50787. */
  50788. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50789. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50790. };
  50791. /**
  50792. * @hidden Internal use only
  50793. */
  50794. Animation.prototype._getKeyValue = function (value) {
  50795. if (typeof value === "function") {
  50796. return value();
  50797. }
  50798. return value;
  50799. };
  50800. /**
  50801. * @hidden Internal use only
  50802. */
  50803. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50804. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50805. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50806. }
  50807. var keys = this.getKeys();
  50808. // Try to get a hash to find the right key
  50809. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  50810. if (keys[startKeyIndex].frame >= currentFrame) {
  50811. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50812. startKeyIndex--;
  50813. }
  50814. }
  50815. for (var key = startKeyIndex; key < keys.length; key++) {
  50816. var endKey = keys[key + 1];
  50817. if (endKey.frame >= currentFrame) {
  50818. var startKey = keys[key];
  50819. var startValue = this._getKeyValue(startKey.value);
  50820. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50821. return startValue;
  50822. }
  50823. var endValue = this._getKeyValue(endKey.value);
  50824. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50825. var frameDelta = endKey.frame - startKey.frame;
  50826. // gradient : percent of currentFrame between the frame inf and the frame sup
  50827. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50828. // check for easingFunction and correction of gradient
  50829. var easingFunction = this.getEasingFunction();
  50830. if (easingFunction != null) {
  50831. gradient = easingFunction.ease(gradient);
  50832. }
  50833. switch (this.dataType) {
  50834. // Float
  50835. case Animation.ANIMATIONTYPE_FLOAT:
  50836. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50837. switch (loopMode) {
  50838. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50839. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50840. return floatValue;
  50841. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50842. return offsetValue * repeatCount + floatValue;
  50843. }
  50844. break;
  50845. // Quaternion
  50846. case Animation.ANIMATIONTYPE_QUATERNION:
  50847. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50848. switch (loopMode) {
  50849. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50850. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50851. return quatValue;
  50852. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50853. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50854. }
  50855. return quatValue;
  50856. // Vector3
  50857. case Animation.ANIMATIONTYPE_VECTOR3:
  50858. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50859. switch (loopMode) {
  50860. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50861. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50862. return vec3Value;
  50863. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50864. return vec3Value.add(offsetValue.scale(repeatCount));
  50865. }
  50866. // Vector2
  50867. case Animation.ANIMATIONTYPE_VECTOR2:
  50868. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50869. switch (loopMode) {
  50870. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50871. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50872. return vec2Value;
  50873. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50874. return vec2Value.add(offsetValue.scale(repeatCount));
  50875. }
  50876. // Size
  50877. case Animation.ANIMATIONTYPE_SIZE:
  50878. switch (loopMode) {
  50879. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50880. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50881. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50882. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50883. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50884. }
  50885. // Color3
  50886. case Animation.ANIMATIONTYPE_COLOR3:
  50887. switch (loopMode) {
  50888. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50889. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50890. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50891. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50892. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50893. }
  50894. // Matrix
  50895. case Animation.ANIMATIONTYPE_MATRIX:
  50896. switch (loopMode) {
  50897. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50898. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50899. if (Animation.AllowMatricesInterpolation) {
  50900. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50901. }
  50902. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50903. return startValue;
  50904. }
  50905. default:
  50906. break;
  50907. }
  50908. break;
  50909. }
  50910. }
  50911. return this._getKeyValue(keys[keys.length - 1].value);
  50912. };
  50913. /**
  50914. * Defines the function to use to interpolate matrices
  50915. * @param startValue defines the start matrix
  50916. * @param endValue defines the end matrix
  50917. * @param gradient defines the gradient between both matrices
  50918. * @param result defines an optional target matrix where to store the interpolation
  50919. * @returns the interpolated matrix
  50920. */
  50921. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50922. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50923. if (result) {
  50924. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50925. return result;
  50926. }
  50927. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50928. }
  50929. if (result) {
  50930. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50931. return result;
  50932. }
  50933. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50934. };
  50935. /**
  50936. * Makes a copy of the animation
  50937. * @returns Cloned animation
  50938. */
  50939. Animation.prototype.clone = function () {
  50940. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50941. clone.enableBlending = this.enableBlending;
  50942. clone.blendingSpeed = this.blendingSpeed;
  50943. if (this._keys) {
  50944. clone.setKeys(this._keys);
  50945. }
  50946. if (this._ranges) {
  50947. clone._ranges = {};
  50948. for (var name in this._ranges) {
  50949. var range = this._ranges[name];
  50950. if (!range) {
  50951. continue;
  50952. }
  50953. clone._ranges[name] = range.clone();
  50954. }
  50955. }
  50956. return clone;
  50957. };
  50958. /**
  50959. * Sets the key frames of the animation
  50960. * @param values The animation key frames to set
  50961. */
  50962. Animation.prototype.setKeys = function (values) {
  50963. this._keys = values.slice(0);
  50964. };
  50965. /**
  50966. * Serializes the animation to an object
  50967. * @returns Serialized object
  50968. */
  50969. Animation.prototype.serialize = function () {
  50970. var serializationObject = {};
  50971. serializationObject.name = this.name;
  50972. serializationObject.property = this.targetProperty;
  50973. serializationObject.framePerSecond = this.framePerSecond;
  50974. serializationObject.dataType = this.dataType;
  50975. serializationObject.loopBehavior = this.loopMode;
  50976. serializationObject.enableBlending = this.enableBlending;
  50977. serializationObject.blendingSpeed = this.blendingSpeed;
  50978. var dataType = this.dataType;
  50979. serializationObject.keys = [];
  50980. var keys = this.getKeys();
  50981. for (var index = 0; index < keys.length; index++) {
  50982. var animationKey = keys[index];
  50983. var key = {};
  50984. key.frame = animationKey.frame;
  50985. switch (dataType) {
  50986. case Animation.ANIMATIONTYPE_FLOAT:
  50987. key.values = [animationKey.value];
  50988. break;
  50989. case Animation.ANIMATIONTYPE_QUATERNION:
  50990. case Animation.ANIMATIONTYPE_MATRIX:
  50991. case Animation.ANIMATIONTYPE_VECTOR3:
  50992. case Animation.ANIMATIONTYPE_COLOR3:
  50993. key.values = animationKey.value.asArray();
  50994. break;
  50995. }
  50996. serializationObject.keys.push(key);
  50997. }
  50998. serializationObject.ranges = [];
  50999. for (var name in this._ranges) {
  51000. var source = this._ranges[name];
  51001. if (!source) {
  51002. continue;
  51003. }
  51004. var range = {};
  51005. range.name = name;
  51006. range.from = source.from;
  51007. range.to = source.to;
  51008. serializationObject.ranges.push(range);
  51009. }
  51010. return serializationObject;
  51011. };
  51012. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51013. /**
  51014. * Get the float animation type
  51015. */
  51016. get: function () {
  51017. return Animation._ANIMATIONTYPE_FLOAT;
  51018. },
  51019. enumerable: true,
  51020. configurable: true
  51021. });
  51022. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51023. /**
  51024. * Get the Vector3 animation type
  51025. */
  51026. get: function () {
  51027. return Animation._ANIMATIONTYPE_VECTOR3;
  51028. },
  51029. enumerable: true,
  51030. configurable: true
  51031. });
  51032. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51033. /**
  51034. * Get the Vector2 animation type
  51035. */
  51036. get: function () {
  51037. return Animation._ANIMATIONTYPE_VECTOR2;
  51038. },
  51039. enumerable: true,
  51040. configurable: true
  51041. });
  51042. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51043. /**
  51044. * Get the Size animation type
  51045. */
  51046. get: function () {
  51047. return Animation._ANIMATIONTYPE_SIZE;
  51048. },
  51049. enumerable: true,
  51050. configurable: true
  51051. });
  51052. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51053. /**
  51054. * Get the Quaternion animation type
  51055. */
  51056. get: function () {
  51057. return Animation._ANIMATIONTYPE_QUATERNION;
  51058. },
  51059. enumerable: true,
  51060. configurable: true
  51061. });
  51062. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51063. /**
  51064. * Get the Matrix animation type
  51065. */
  51066. get: function () {
  51067. return Animation._ANIMATIONTYPE_MATRIX;
  51068. },
  51069. enumerable: true,
  51070. configurable: true
  51071. });
  51072. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51073. /**
  51074. * Get the Color3 animation type
  51075. */
  51076. get: function () {
  51077. return Animation._ANIMATIONTYPE_COLOR3;
  51078. },
  51079. enumerable: true,
  51080. configurable: true
  51081. });
  51082. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51083. /**
  51084. * Get the Relative Loop Mode
  51085. */
  51086. get: function () {
  51087. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51088. },
  51089. enumerable: true,
  51090. configurable: true
  51091. });
  51092. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51093. /**
  51094. * Get the Cycle Loop Mode
  51095. */
  51096. get: function () {
  51097. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51098. },
  51099. enumerable: true,
  51100. configurable: true
  51101. });
  51102. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51103. /**
  51104. * Get the Constant Loop Mode
  51105. */
  51106. get: function () {
  51107. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51108. },
  51109. enumerable: true,
  51110. configurable: true
  51111. });
  51112. /** @hidden */
  51113. Animation._UniversalLerp = function (left, right, amount) {
  51114. var constructor = left.constructor;
  51115. if (constructor.Lerp) { // Lerp supported
  51116. return constructor.Lerp(left, right, amount);
  51117. }
  51118. else if (constructor.Slerp) { // Slerp supported
  51119. return constructor.Slerp(left, right, amount);
  51120. }
  51121. else if (left.toFixed) { // Number
  51122. return left * (1.0 - amount) + amount * right;
  51123. }
  51124. else { // Blending not supported
  51125. return right;
  51126. }
  51127. };
  51128. /**
  51129. * Parses an animation object and creates an animation
  51130. * @param parsedAnimation Parsed animation object
  51131. * @returns Animation object
  51132. */
  51133. Animation.Parse = function (parsedAnimation) {
  51134. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51135. var dataType = parsedAnimation.dataType;
  51136. var keys = [];
  51137. var data;
  51138. var index;
  51139. if (parsedAnimation.enableBlending) {
  51140. animation.enableBlending = parsedAnimation.enableBlending;
  51141. }
  51142. if (parsedAnimation.blendingSpeed) {
  51143. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51144. }
  51145. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51146. var key = parsedAnimation.keys[index];
  51147. var inTangent;
  51148. var outTangent;
  51149. switch (dataType) {
  51150. case Animation.ANIMATIONTYPE_FLOAT:
  51151. data = key.values[0];
  51152. if (key.values.length >= 1) {
  51153. inTangent = key.values[1];
  51154. }
  51155. if (key.values.length >= 2) {
  51156. outTangent = key.values[2];
  51157. }
  51158. break;
  51159. case Animation.ANIMATIONTYPE_QUATERNION:
  51160. data = BABYLON.Quaternion.FromArray(key.values);
  51161. if (key.values.length >= 8) {
  51162. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51163. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51164. inTangent = _inTangent;
  51165. }
  51166. }
  51167. if (key.values.length >= 12) {
  51168. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51169. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51170. outTangent = _outTangent;
  51171. }
  51172. }
  51173. break;
  51174. case Animation.ANIMATIONTYPE_MATRIX:
  51175. data = BABYLON.Matrix.FromArray(key.values);
  51176. break;
  51177. case Animation.ANIMATIONTYPE_COLOR3:
  51178. data = BABYLON.Color3.FromArray(key.values);
  51179. break;
  51180. case Animation.ANIMATIONTYPE_VECTOR3:
  51181. default:
  51182. data = BABYLON.Vector3.FromArray(key.values);
  51183. break;
  51184. }
  51185. var keyData = {};
  51186. keyData.frame = key.frame;
  51187. keyData.value = data;
  51188. if (inTangent != undefined) {
  51189. keyData.inTangent = inTangent;
  51190. }
  51191. if (outTangent != undefined) {
  51192. keyData.outTangent = outTangent;
  51193. }
  51194. keys.push(keyData);
  51195. }
  51196. animation.setKeys(keys);
  51197. if (parsedAnimation.ranges) {
  51198. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51199. data = parsedAnimation.ranges[index];
  51200. animation.createRange(data.name, data.from, data.to);
  51201. }
  51202. }
  51203. return animation;
  51204. };
  51205. /**
  51206. * Appends the serialized animations from the source animations
  51207. * @param source Source containing the animations
  51208. * @param destination Target to store the animations
  51209. */
  51210. Animation.AppendSerializedAnimations = function (source, destination) {
  51211. if (source.animations) {
  51212. destination.animations = [];
  51213. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51214. var animation = source.animations[animationIndex];
  51215. destination.animations.push(animation.serialize());
  51216. }
  51217. }
  51218. };
  51219. /**
  51220. * Use matrix interpolation instead of using direct key value when animating matrices
  51221. */
  51222. Animation.AllowMatricesInterpolation = false;
  51223. /**
  51224. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51225. */
  51226. Animation.AllowMatrixDecomposeForInterpolation = true;
  51227. // Statics
  51228. /**
  51229. * Float animation type
  51230. */
  51231. Animation._ANIMATIONTYPE_FLOAT = 0;
  51232. /**
  51233. * Vector3 animation type
  51234. */
  51235. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51236. /**
  51237. * Quaternion animation type
  51238. */
  51239. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51240. /**
  51241. * Matrix animation type
  51242. */
  51243. Animation._ANIMATIONTYPE_MATRIX = 3;
  51244. /**
  51245. * Color3 animation type
  51246. */
  51247. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51248. /**
  51249. * Vector2 animation type
  51250. */
  51251. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51252. /**
  51253. * Size animation type
  51254. */
  51255. Animation._ANIMATIONTYPE_SIZE = 6;
  51256. /**
  51257. * Relative Loop Mode
  51258. */
  51259. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51260. /**
  51261. * Cycle Loop Mode
  51262. */
  51263. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51264. /**
  51265. * Constant Loop Mode
  51266. */
  51267. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51268. return Animation;
  51269. }());
  51270. BABYLON.Animation = Animation;
  51271. })(BABYLON || (BABYLON = {}));
  51272. //# sourceMappingURL=babylon.animation.js.map
  51273. var BABYLON;
  51274. (function (BABYLON) {
  51275. /**
  51276. * This class defines the direct association between an animation and a target
  51277. */
  51278. var TargetedAnimation = /** @class */ (function () {
  51279. function TargetedAnimation() {
  51280. }
  51281. return TargetedAnimation;
  51282. }());
  51283. BABYLON.TargetedAnimation = TargetedAnimation;
  51284. /**
  51285. * Use this class to create coordinated animations on multiple targets
  51286. */
  51287. var AnimationGroup = /** @class */ (function () {
  51288. /**
  51289. * Instantiates a new Animation Group.
  51290. * This helps managing several animations at once.
  51291. * @see http://doc.babylonjs.com/how_to/group
  51292. * @param name Defines the name of the group
  51293. * @param scene Defines the scene the group belongs to
  51294. */
  51295. function AnimationGroup(
  51296. /** The name of the animation group */
  51297. name, scene) {
  51298. if (scene === void 0) { scene = null; }
  51299. this.name = name;
  51300. this._targetedAnimations = new Array();
  51301. this._animatables = new Array();
  51302. this._from = Number.MAX_VALUE;
  51303. this._to = -Number.MAX_VALUE;
  51304. this._speedRatio = 1;
  51305. /**
  51306. * This observable will notify when one animation have ended.
  51307. */
  51308. this.onAnimationEndObservable = new BABYLON.Observable();
  51309. /**
  51310. * This observable will notify when all animations have ended.
  51311. */
  51312. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51313. /**
  51314. * This observable will notify when all animations have paused.
  51315. */
  51316. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51317. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51318. this._scene.animationGroups.push(this);
  51319. }
  51320. Object.defineProperty(AnimationGroup.prototype, "from", {
  51321. /**
  51322. * Gets the first frame
  51323. */
  51324. get: function () {
  51325. return this._from;
  51326. },
  51327. enumerable: true,
  51328. configurable: true
  51329. });
  51330. Object.defineProperty(AnimationGroup.prototype, "to", {
  51331. /**
  51332. * Gets the last frame
  51333. */
  51334. get: function () {
  51335. return this._to;
  51336. },
  51337. enumerable: true,
  51338. configurable: true
  51339. });
  51340. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51341. /**
  51342. * Define if the animations are started
  51343. */
  51344. get: function () {
  51345. return this._isStarted;
  51346. },
  51347. enumerable: true,
  51348. configurable: true
  51349. });
  51350. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51351. /**
  51352. * Gets or sets the speed ratio to use for all animations
  51353. */
  51354. get: function () {
  51355. return this._speedRatio;
  51356. },
  51357. /**
  51358. * Gets or sets the speed ratio to use for all animations
  51359. */
  51360. set: function (value) {
  51361. if (this._speedRatio === value) {
  51362. return;
  51363. }
  51364. this._speedRatio = value;
  51365. for (var index = 0; index < this._animatables.length; index++) {
  51366. var animatable = this._animatables[index];
  51367. animatable.speedRatio = this._speedRatio;
  51368. }
  51369. },
  51370. enumerable: true,
  51371. configurable: true
  51372. });
  51373. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51374. /**
  51375. * Gets the targeted animations for this animation group
  51376. */
  51377. get: function () {
  51378. return this._targetedAnimations;
  51379. },
  51380. enumerable: true,
  51381. configurable: true
  51382. });
  51383. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51384. /**
  51385. * returning the list of animatables controlled by this animation group.
  51386. */
  51387. get: function () {
  51388. return this._animatables;
  51389. },
  51390. enumerable: true,
  51391. configurable: true
  51392. });
  51393. /**
  51394. * Add an animation (with its target) in the group
  51395. * @param animation defines the animation we want to add
  51396. * @param target defines the target of the animation
  51397. * @returns the {BABYLON.TargetedAnimation} object
  51398. */
  51399. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51400. var targetedAnimation = {
  51401. animation: animation,
  51402. target: target
  51403. };
  51404. var keys = animation.getKeys();
  51405. if (this._from > keys[0].frame) {
  51406. this._from = keys[0].frame;
  51407. }
  51408. if (this._to < keys[keys.length - 1].frame) {
  51409. this._to = keys[keys.length - 1].frame;
  51410. }
  51411. this._targetedAnimations.push(targetedAnimation);
  51412. return targetedAnimation;
  51413. };
  51414. /**
  51415. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51416. * It can add constant keys at begin or end
  51417. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51418. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51419. * @returns the animation group
  51420. */
  51421. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51422. if (beginFrame === void 0) { beginFrame = null; }
  51423. if (endFrame === void 0) { endFrame = null; }
  51424. if (beginFrame == null)
  51425. beginFrame = this._from;
  51426. if (endFrame == null)
  51427. endFrame = this._to;
  51428. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51429. var targetedAnimation = this._targetedAnimations[index];
  51430. var keys = targetedAnimation.animation.getKeys();
  51431. var startKey = keys[0];
  51432. var endKey = keys[keys.length - 1];
  51433. if (startKey.frame > beginFrame) {
  51434. var newKey = {
  51435. frame: beginFrame,
  51436. value: startKey.value,
  51437. inTangent: startKey.inTangent,
  51438. outTangent: startKey.outTangent,
  51439. interpolation: startKey.interpolation
  51440. };
  51441. keys.splice(0, 0, newKey);
  51442. }
  51443. if (endKey.frame < endFrame) {
  51444. var newKey = {
  51445. frame: endFrame,
  51446. value: endKey.value,
  51447. inTangent: endKey.outTangent,
  51448. outTangent: endKey.outTangent,
  51449. interpolation: endKey.interpolation
  51450. };
  51451. keys.push(newKey);
  51452. }
  51453. }
  51454. this._from = beginFrame;
  51455. this._to = endFrame;
  51456. return this;
  51457. };
  51458. /**
  51459. * Start all animations on given targets
  51460. * @param loop defines if animations must loop
  51461. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51462. * @param from defines the from key (optional)
  51463. * @param to defines the to key (optional)
  51464. * @returns the current animation group
  51465. */
  51466. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51467. var _this = this;
  51468. if (loop === void 0) { loop = false; }
  51469. if (speedRatio === void 0) { speedRatio = 1; }
  51470. if (this._isStarted || this._targetedAnimations.length === 0) {
  51471. return this;
  51472. }
  51473. var _loop_1 = function (targetedAnimation) {
  51474. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51475. animatable.onAnimationEnd = function () {
  51476. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51477. _this._checkAnimationGroupEnded(animatable);
  51478. };
  51479. this_1._animatables.push(animatable);
  51480. };
  51481. var this_1 = this;
  51482. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51483. var targetedAnimation = _a[_i];
  51484. _loop_1(targetedAnimation);
  51485. }
  51486. this._speedRatio = speedRatio;
  51487. this._isStarted = true;
  51488. return this;
  51489. };
  51490. /**
  51491. * Pause all animations
  51492. * @returns the animation group
  51493. */
  51494. AnimationGroup.prototype.pause = function () {
  51495. if (!this._isStarted) {
  51496. return this;
  51497. }
  51498. for (var index = 0; index < this._animatables.length; index++) {
  51499. var animatable = this._animatables[index];
  51500. animatable.pause();
  51501. }
  51502. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51503. return this;
  51504. };
  51505. /**
  51506. * Play all animations to initial state
  51507. * This function will start() the animations if they were not started or will restart() them if they were paused
  51508. * @param loop defines if animations must loop
  51509. * @returns the animation group
  51510. */
  51511. AnimationGroup.prototype.play = function (loop) {
  51512. // only if all animatables are ready and exist
  51513. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51514. if (loop !== undefined) {
  51515. for (var index = 0; index < this._animatables.length; index++) {
  51516. var animatable = this._animatables[index];
  51517. animatable.loopAnimation = loop;
  51518. }
  51519. }
  51520. this.restart();
  51521. }
  51522. else {
  51523. this.stop();
  51524. this.start(loop, this._speedRatio);
  51525. }
  51526. return this;
  51527. };
  51528. /**
  51529. * Reset all animations to initial state
  51530. * @returns the animation group
  51531. */
  51532. AnimationGroup.prototype.reset = function () {
  51533. if (!this._isStarted) {
  51534. return this;
  51535. }
  51536. for (var index = 0; index < this._animatables.length; index++) {
  51537. var animatable = this._animatables[index];
  51538. animatable.reset();
  51539. }
  51540. return this;
  51541. };
  51542. /**
  51543. * Restart animations from key 0
  51544. * @returns the animation group
  51545. */
  51546. AnimationGroup.prototype.restart = function () {
  51547. if (!this._isStarted) {
  51548. return this;
  51549. }
  51550. for (var index = 0; index < this._animatables.length; index++) {
  51551. var animatable = this._animatables[index];
  51552. animatable.restart();
  51553. }
  51554. return this;
  51555. };
  51556. /**
  51557. * Stop all animations
  51558. * @returns the animation group
  51559. */
  51560. AnimationGroup.prototype.stop = function () {
  51561. if (!this._isStarted) {
  51562. return this;
  51563. }
  51564. var list = this._animatables.slice();
  51565. for (var index = 0; index < list.length; index++) {
  51566. list[index].stop();
  51567. }
  51568. this._isStarted = false;
  51569. return this;
  51570. };
  51571. /**
  51572. * Set animation weight for all animatables
  51573. * @param weight defines the weight to use
  51574. * @return the animationGroup
  51575. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51576. */
  51577. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51578. for (var index = 0; index < this._animatables.length; index++) {
  51579. var animatable = this._animatables[index];
  51580. animatable.weight = weight;
  51581. }
  51582. return this;
  51583. };
  51584. /**
  51585. * Synchronize and normalize all animatables with a source animatable
  51586. * @param root defines the root animatable to synchronize with
  51587. * @return the animationGroup
  51588. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51589. */
  51590. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51591. for (var index = 0; index < this._animatables.length; index++) {
  51592. var animatable = this._animatables[index];
  51593. animatable.syncWith(root);
  51594. }
  51595. return this;
  51596. };
  51597. /**
  51598. * Goes to a specific frame in this animation group
  51599. * @param frame the frame number to go to
  51600. * @return the animationGroup
  51601. */
  51602. AnimationGroup.prototype.goToFrame = function (frame) {
  51603. if (!this._isStarted) {
  51604. return this;
  51605. }
  51606. for (var index = 0; index < this._animatables.length; index++) {
  51607. var animatable = this._animatables[index];
  51608. animatable.goToFrame(frame);
  51609. }
  51610. return this;
  51611. };
  51612. /**
  51613. * Dispose all associated resources
  51614. */
  51615. AnimationGroup.prototype.dispose = function () {
  51616. this._targetedAnimations = [];
  51617. this._animatables = [];
  51618. var index = this._scene.animationGroups.indexOf(this);
  51619. if (index > -1) {
  51620. this._scene.animationGroups.splice(index, 1);
  51621. }
  51622. };
  51623. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51624. // animatable should be taken out of the array
  51625. var idx = this._animatables.indexOf(animatable);
  51626. if (idx > -1) {
  51627. this._animatables.splice(idx, 1);
  51628. }
  51629. // all animatables were removed? animation group ended!
  51630. if (this._animatables.length === 0) {
  51631. this._isStarted = false;
  51632. this.onAnimationGroupEndObservable.notifyObservers(this);
  51633. }
  51634. };
  51635. // Statics
  51636. /**
  51637. * Returns a new AnimationGroup object parsed from the source provided.
  51638. * @param parsedAnimationGroup defines the source
  51639. * @param scene defines the scene that will receive the animationGroup
  51640. * @returns a new AnimationGroup
  51641. */
  51642. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  51643. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  51644. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  51645. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  51646. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  51647. var id = targetedAnimation.targetId;
  51648. var targetNode = scene.getNodeByID(id);
  51649. if (targetNode != null)
  51650. animationGroup.addTargetedAnimation(animation, targetNode);
  51651. }
  51652. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  51653. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51654. return animationGroup;
  51655. };
  51656. /**
  51657. * Returns the string "AnimationGroup"
  51658. * @returns "AnimationGroup"
  51659. */
  51660. AnimationGroup.prototype.getClassName = function () {
  51661. return "AnimationGroup";
  51662. };
  51663. /**
  51664. * Creates a detailled string about the object
  51665. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51666. * @returns a string representing the object
  51667. */
  51668. AnimationGroup.prototype.toString = function (fullDetails) {
  51669. var ret = "Name: " + this.name;
  51670. ret += ", type: " + this.getClassName();
  51671. if (fullDetails) {
  51672. ret += ", from: " + this._from;
  51673. ret += ", to: " + this._to;
  51674. ret += ", isStarted: " + this._isStarted;
  51675. ret += ", speedRatio: " + this._speedRatio;
  51676. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51677. ret += ", animatables length: " + this._animatables;
  51678. }
  51679. return ret;
  51680. };
  51681. return AnimationGroup;
  51682. }());
  51683. BABYLON.AnimationGroup = AnimationGroup;
  51684. })(BABYLON || (BABYLON = {}));
  51685. //# sourceMappingURL=babylon.animationGroup.js.map
  51686. var BABYLON;
  51687. (function (BABYLON) {
  51688. // Static values to help the garbage collector
  51689. // Quaternion
  51690. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51691. // Vector3
  51692. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51693. // Vector2
  51694. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51695. // Size
  51696. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51697. // Color3
  51698. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51699. /**
  51700. * Defines a runtime animation
  51701. */
  51702. var RuntimeAnimation = /** @class */ (function () {
  51703. /**
  51704. * Create a new RuntimeAnimation object
  51705. * @param target defines the target of the animation
  51706. * @param animation defines the source animation object
  51707. * @param scene defines the hosting scene
  51708. * @param host defines the initiating Animatable
  51709. */
  51710. function RuntimeAnimation(target, animation, scene, host) {
  51711. var _this = this;
  51712. this._events = new Array();
  51713. /**
  51714. * The current frame of the runtime animation
  51715. */
  51716. this._currentFrame = 0;
  51717. /**
  51718. * The original value of the runtime animation
  51719. */
  51720. this._originalValue = new Array();
  51721. /**
  51722. * The offsets cache of the runtime animation
  51723. */
  51724. this._offsetsCache = {};
  51725. /**
  51726. * The high limits cache of the runtime animation
  51727. */
  51728. this._highLimitsCache = {};
  51729. /**
  51730. * Specifies if the runtime animation has been stopped
  51731. */
  51732. this._stopped = false;
  51733. /**
  51734. * The blending factor of the runtime animation
  51735. */
  51736. this._blendingFactor = 0;
  51737. /**
  51738. * The target path of the runtime animation
  51739. */
  51740. this._targetPath = "";
  51741. /**
  51742. * The weight of the runtime animation
  51743. */
  51744. this._weight = 1.0;
  51745. /**
  51746. * The ratio offset of the runtime animation
  51747. */
  51748. this._ratioOffset = 0;
  51749. /**
  51750. * The previous delay of the runtime animation
  51751. */
  51752. this._previousDelay = 0;
  51753. /**
  51754. * The previous ratio of the runtime animation
  51755. */
  51756. this._previousRatio = 0;
  51757. this._animation = animation;
  51758. this._target = target;
  51759. this._scene = scene;
  51760. this._host = host;
  51761. animation._runtimeAnimations.push(this);
  51762. // Cloning events locally
  51763. var events = animation.getEvents();
  51764. if (events && events.length > 0) {
  51765. events.forEach(function (e) {
  51766. _this._events.push(e._clone());
  51767. });
  51768. }
  51769. }
  51770. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51771. /**
  51772. * Gets the current frame of the runtime animation
  51773. */
  51774. get: function () {
  51775. return this._currentFrame;
  51776. },
  51777. enumerable: true,
  51778. configurable: true
  51779. });
  51780. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51781. /**
  51782. * Gets the weight of the runtime animation
  51783. */
  51784. get: function () {
  51785. return this._weight;
  51786. },
  51787. enumerable: true,
  51788. configurable: true
  51789. });
  51790. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51791. /**
  51792. * Gets the current value of the runtime animation
  51793. */
  51794. get: function () {
  51795. return this._currentValue;
  51796. },
  51797. enumerable: true,
  51798. configurable: true
  51799. });
  51800. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51801. /**
  51802. * Gets the target path of the runtime animation
  51803. */
  51804. get: function () {
  51805. return this._targetPath;
  51806. },
  51807. enumerable: true,
  51808. configurable: true
  51809. });
  51810. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51811. /**
  51812. * Gets the actual target of the runtime animation
  51813. */
  51814. get: function () {
  51815. return this._activeTarget;
  51816. },
  51817. enumerable: true,
  51818. configurable: true
  51819. });
  51820. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51821. /**
  51822. * Gets the animation from the runtime animation
  51823. */
  51824. get: function () {
  51825. return this._animation;
  51826. },
  51827. enumerable: true,
  51828. configurable: true
  51829. });
  51830. /**
  51831. * Resets the runtime animation to the beginning
  51832. * @param restoreOriginal defines whether to restore the target property to the original value
  51833. */
  51834. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51835. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51836. if (restoreOriginal) {
  51837. if (this._target instanceof Array) {
  51838. var index = 0;
  51839. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51840. var target = _a[_i];
  51841. if (this._originalValue[index] !== undefined) {
  51842. this._setValue(target, this._originalValue[index], -1);
  51843. }
  51844. index++;
  51845. }
  51846. }
  51847. else {
  51848. if (this._originalValue[0] !== undefined) {
  51849. this._setValue(this._target, this._originalValue[0], -1);
  51850. }
  51851. }
  51852. }
  51853. this._offsetsCache = {};
  51854. this._highLimitsCache = {};
  51855. this._currentFrame = 0;
  51856. this._blendingFactor = 0;
  51857. this._originalValue = new Array();
  51858. // Events
  51859. for (var index = 0; index < this._events.length; index++) {
  51860. this._events[index].isDone = false;
  51861. }
  51862. };
  51863. /**
  51864. * Specifies if the runtime animation is stopped
  51865. * @returns Boolean specifying if the runtime animation is stopped
  51866. */
  51867. RuntimeAnimation.prototype.isStopped = function () {
  51868. return this._stopped;
  51869. };
  51870. /**
  51871. * Disposes of the runtime animation
  51872. */
  51873. RuntimeAnimation.prototype.dispose = function () {
  51874. var index = this._animation.runtimeAnimations.indexOf(this);
  51875. if (index > -1) {
  51876. this._animation.runtimeAnimations.splice(index, 1);
  51877. }
  51878. };
  51879. /**
  51880. * Interpolates the animation from the current frame
  51881. * @param currentFrame The frame to interpolate the animation to
  51882. * @param repeatCount The number of times that the animation should loop
  51883. * @param loopMode The type of looping mode to use
  51884. * @param offsetValue Animation offset value
  51885. * @param highLimitValue The high limit value
  51886. * @returns The interpolated value
  51887. */
  51888. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51889. this._currentFrame = currentFrame;
  51890. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51891. this._workValue = BABYLON.Matrix.Zero();
  51892. }
  51893. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51894. };
  51895. /**
  51896. * Apply the interpolated value to the target
  51897. * @param currentValue defines the value computed by the animation
  51898. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51899. */
  51900. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51901. if (weight === void 0) { weight = 1.0; }
  51902. if (this._target instanceof Array) {
  51903. var index = 0;
  51904. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51905. var target = _a[_i];
  51906. this._setValue(target, currentValue, weight, index);
  51907. index++;
  51908. }
  51909. }
  51910. else {
  51911. this._setValue(this._target, currentValue, weight);
  51912. }
  51913. };
  51914. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51915. if (targetIndex === void 0) { targetIndex = 0; }
  51916. // Set value
  51917. var path;
  51918. var destination;
  51919. var targetPropertyPath = this._animation.targetPropertyPath;
  51920. if (targetPropertyPath.length > 1) {
  51921. var property = target[targetPropertyPath[0]];
  51922. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51923. property = property[targetPropertyPath[index]];
  51924. }
  51925. path = targetPropertyPath[targetPropertyPath.length - 1];
  51926. destination = property;
  51927. }
  51928. else {
  51929. path = targetPropertyPath[0];
  51930. destination = target;
  51931. }
  51932. this._targetPath = path;
  51933. this._activeTarget = destination;
  51934. this._weight = weight;
  51935. if (this._originalValue[targetIndex] === undefined) {
  51936. var originalValue = void 0;
  51937. if (destination.getRestPose && path === "_matrix") { // For bones
  51938. originalValue = destination.getRestPose();
  51939. }
  51940. else {
  51941. originalValue = destination[path];
  51942. }
  51943. if (originalValue && originalValue.clone) {
  51944. this._originalValue[targetIndex] = originalValue.clone();
  51945. }
  51946. else {
  51947. this._originalValue[targetIndex] = originalValue;
  51948. }
  51949. }
  51950. // Blending
  51951. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51952. if (enableBlending && this._blendingFactor <= 1.0) {
  51953. if (!this._originalBlendValue) {
  51954. var originalValue = destination[path];
  51955. if (originalValue.clone) {
  51956. this._originalBlendValue = originalValue.clone();
  51957. }
  51958. else {
  51959. this._originalBlendValue = originalValue;
  51960. }
  51961. }
  51962. if (this._originalBlendValue.m) { // Matrix
  51963. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51964. if (this._currentValue) {
  51965. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51966. }
  51967. else {
  51968. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51969. }
  51970. }
  51971. else {
  51972. if (this._currentValue) {
  51973. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51974. }
  51975. else {
  51976. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51977. }
  51978. }
  51979. }
  51980. else {
  51981. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51982. }
  51983. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51984. this._blendingFactor += blendingSpeed;
  51985. }
  51986. else {
  51987. this._currentValue = currentValue;
  51988. }
  51989. if (weight !== -1.0) {
  51990. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51991. }
  51992. else {
  51993. destination[path] = this._currentValue;
  51994. }
  51995. if (target.markAsDirty) {
  51996. target.markAsDirty(this._animation.targetProperty);
  51997. }
  51998. };
  51999. /**
  52000. * Gets the loop pmode of the runtime animation
  52001. * @returns Loop Mode
  52002. */
  52003. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52004. if (this._target && this._target.animationPropertiesOverride) {
  52005. return this._target.animationPropertiesOverride.loopMode;
  52006. }
  52007. return this._animation.loopMode;
  52008. };
  52009. /**
  52010. * Move the current animation to a given frame
  52011. * @param frame defines the frame to move to
  52012. */
  52013. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52014. var keys = this._animation.getKeys();
  52015. if (frame < keys[0].frame) {
  52016. frame = keys[0].frame;
  52017. }
  52018. else if (frame > keys[keys.length - 1].frame) {
  52019. frame = keys[keys.length - 1].frame;
  52020. }
  52021. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52022. this.setValue(currentValue, -1);
  52023. };
  52024. /**
  52025. * @hidden Internal use only
  52026. */
  52027. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52028. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52029. this._ratioOffset = this._previousRatio - newRatio;
  52030. };
  52031. /**
  52032. * Execute the current animation
  52033. * @param delay defines the delay to add to the current frame
  52034. * @param from defines the lower bound of the animation range
  52035. * @param to defines the upper bound of the animation range
  52036. * @param loop defines if the current animation must loop
  52037. * @param speedRatio defines the current speed ratio
  52038. * @param weight defines the weight of the animation (default is -1 so no weight)
  52039. * @returns a boolean indicating if the animation is running
  52040. */
  52041. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52042. if (weight === void 0) { weight = -1.0; }
  52043. var targetPropertyPath = this._animation.targetPropertyPath;
  52044. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52045. this._stopped = true;
  52046. return false;
  52047. }
  52048. var returnValue = true;
  52049. var keys = this._animation.getKeys();
  52050. // Adding a start key at frame 0 if missing
  52051. if (keys[0].frame !== 0) {
  52052. var newKey = { frame: 0, value: keys[0].value };
  52053. keys.splice(0, 0, newKey);
  52054. }
  52055. // Adding a duplicate key when there is only one key at frame zero
  52056. else if (keys.length === 1) {
  52057. var newKey = { frame: 0.001, value: keys[0].value };
  52058. keys.push(newKey);
  52059. }
  52060. // Check limits
  52061. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52062. from = keys[0].frame;
  52063. }
  52064. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52065. to = keys[keys.length - 1].frame;
  52066. }
  52067. //to and from cannot be the same key
  52068. if (from === to) {
  52069. if (from > keys[0].frame) {
  52070. from--;
  52071. }
  52072. else if (to < keys[keys.length - 1].frame) {
  52073. to++;
  52074. }
  52075. }
  52076. // Compute ratio
  52077. var range = to - from;
  52078. var offsetValue;
  52079. // ratio represents the frame delta between from and to
  52080. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52081. var highLimitValue = 0;
  52082. this._previousDelay = delay;
  52083. this._previousRatio = ratio;
  52084. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52085. returnValue = false;
  52086. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52087. }
  52088. else {
  52089. // Get max value if required
  52090. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52091. var keyOffset = to.toString() + from.toString();
  52092. if (!this._offsetsCache[keyOffset]) {
  52093. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52094. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52095. switch (this._animation.dataType) {
  52096. // Float
  52097. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52098. this._offsetsCache[keyOffset] = toValue - fromValue;
  52099. break;
  52100. // Quaternion
  52101. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52102. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52103. break;
  52104. // Vector3
  52105. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52106. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52107. // Vector2
  52108. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52109. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52110. // Size
  52111. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52112. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52113. // Color3
  52114. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52115. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52116. default:
  52117. break;
  52118. }
  52119. this._highLimitsCache[keyOffset] = toValue;
  52120. }
  52121. highLimitValue = this._highLimitsCache[keyOffset];
  52122. offsetValue = this._offsetsCache[keyOffset];
  52123. }
  52124. }
  52125. if (offsetValue === undefined) {
  52126. switch (this._animation.dataType) {
  52127. // Float
  52128. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52129. offsetValue = 0;
  52130. break;
  52131. // Quaternion
  52132. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52133. offsetValue = _staticOffsetValueQuaternion;
  52134. break;
  52135. // Vector3
  52136. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52137. offsetValue = _staticOffsetValueVector3;
  52138. break;
  52139. // Vector2
  52140. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52141. offsetValue = _staticOffsetValueVector2;
  52142. break;
  52143. // Size
  52144. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52145. offsetValue = _staticOffsetValueSize;
  52146. break;
  52147. // Color3
  52148. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52149. offsetValue = _staticOffsetValueColor3;
  52150. }
  52151. }
  52152. // Compute value
  52153. var repeatCount = (ratio / range) >> 0;
  52154. var currentFrame = returnValue ? from + ratio % range : to;
  52155. // Need to normalize?
  52156. if (this._host && this._host.syncRoot) {
  52157. var syncRoot = this._host.syncRoot;
  52158. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52159. currentFrame = from + (to - from) * hostNormalizedFrame;
  52160. }
  52161. // Reset events if looping
  52162. var events = this._events;
  52163. if (range > 0 && this.currentFrame > currentFrame ||
  52164. range < 0 && this.currentFrame < currentFrame) {
  52165. // Need to reset animation events
  52166. for (var index = 0; index < events.length; index++) {
  52167. if (!events[index].onlyOnce) {
  52168. // reset event, the animation is looping
  52169. events[index].isDone = false;
  52170. }
  52171. }
  52172. }
  52173. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52174. // Set value
  52175. this.setValue(currentValue, weight);
  52176. // Check events
  52177. for (var index = 0; index < events.length; index++) {
  52178. // Make sure current frame has passed event frame and that event frame is within the current range
  52179. // Also, handle both forward and reverse animations
  52180. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52181. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52182. var event = events[index];
  52183. if (!event.isDone) {
  52184. // If event should be done only once, remove it.
  52185. if (event.onlyOnce) {
  52186. events.splice(index, 1);
  52187. index--;
  52188. }
  52189. event.isDone = true;
  52190. event.action(currentFrame);
  52191. } // Don't do anything if the event has already be done.
  52192. }
  52193. }
  52194. if (!returnValue) {
  52195. this._stopped = true;
  52196. }
  52197. return returnValue;
  52198. };
  52199. return RuntimeAnimation;
  52200. }());
  52201. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52202. })(BABYLON || (BABYLON = {}));
  52203. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52204. var BABYLON;
  52205. (function (BABYLON) {
  52206. /**
  52207. * Class used to store an actual running animation
  52208. */
  52209. var Animatable = /** @class */ (function () {
  52210. /**
  52211. * Creates a new Animatable
  52212. * @param scene defines the hosting scene
  52213. * @param target defines the target object
  52214. * @param fromFrame defines the starting frame number (default is 0)
  52215. * @param toFrame defines the ending frame number (default is 100)
  52216. * @param loopAnimation defines if the animation must loop (default is false)
  52217. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52218. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52219. * @param animations defines a group of animation to add to the new Animatable
  52220. */
  52221. function Animatable(scene,
  52222. /** defines the target object */
  52223. target,
  52224. /** defines the starting frame number (default is 0) */
  52225. fromFrame,
  52226. /** defines the ending frame number (default is 100) */
  52227. toFrame,
  52228. /** defines if the animation must loop (default is false) */
  52229. loopAnimation, speedRatio,
  52230. /** defines a callback to call when animation ends if it is not looping */
  52231. onAnimationEnd, animations) {
  52232. if (fromFrame === void 0) { fromFrame = 0; }
  52233. if (toFrame === void 0) { toFrame = 100; }
  52234. if (loopAnimation === void 0) { loopAnimation = false; }
  52235. if (speedRatio === void 0) { speedRatio = 1.0; }
  52236. this.target = target;
  52237. this.fromFrame = fromFrame;
  52238. this.toFrame = toFrame;
  52239. this.loopAnimation = loopAnimation;
  52240. this.onAnimationEnd = onAnimationEnd;
  52241. this._localDelayOffset = null;
  52242. this._pausedDelay = null;
  52243. this._runtimeAnimations = new Array();
  52244. this._paused = false;
  52245. this._speedRatio = 1;
  52246. this._weight = -1.0;
  52247. /**
  52248. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52249. * This will only apply for non looping animation (default is true)
  52250. */
  52251. this.disposeOnEnd = true;
  52252. /**
  52253. * Gets a boolean indicating if the animation has started
  52254. */
  52255. this.animationStarted = false;
  52256. /**
  52257. * Observer raised when the animation ends
  52258. */
  52259. this.onAnimationEndObservable = new BABYLON.Observable();
  52260. this._scene = scene;
  52261. if (animations) {
  52262. this.appendAnimations(target, animations);
  52263. }
  52264. this._speedRatio = speedRatio;
  52265. scene._activeAnimatables.push(this);
  52266. }
  52267. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52268. /**
  52269. * Gets the root Animatable used to synchronize and normalize animations
  52270. */
  52271. get: function () {
  52272. return this._syncRoot;
  52273. },
  52274. enumerable: true,
  52275. configurable: true
  52276. });
  52277. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52278. /**
  52279. * Gets the current frame of the first RuntimeAnimation
  52280. * Used to synchronize Animatables
  52281. */
  52282. get: function () {
  52283. if (this._runtimeAnimations.length === 0) {
  52284. return 0;
  52285. }
  52286. return this._runtimeAnimations[0].currentFrame;
  52287. },
  52288. enumerable: true,
  52289. configurable: true
  52290. });
  52291. Object.defineProperty(Animatable.prototype, "weight", {
  52292. /**
  52293. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52294. */
  52295. get: function () {
  52296. return this._weight;
  52297. },
  52298. set: function (value) {
  52299. if (value === -1) { // -1 is ok and means no weight
  52300. this._weight = -1;
  52301. return;
  52302. }
  52303. // Else weight must be in [0, 1] range
  52304. this._weight = Math.min(Math.max(value, 0), 1.0);
  52305. },
  52306. enumerable: true,
  52307. configurable: true
  52308. });
  52309. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52310. /**
  52311. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52312. */
  52313. get: function () {
  52314. return this._speedRatio;
  52315. },
  52316. set: function (value) {
  52317. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52318. var animation = this._runtimeAnimations[index];
  52319. animation._prepareForSpeedRatioChange(value);
  52320. }
  52321. this._speedRatio = value;
  52322. },
  52323. enumerable: true,
  52324. configurable: true
  52325. });
  52326. // Methods
  52327. /**
  52328. * Synchronize and normalize current Animatable with a source Animatable
  52329. * This is useful when using animation weights and when animations are not of the same length
  52330. * @param root defines the root Animatable to synchronize with
  52331. * @returns the current Animatable
  52332. */
  52333. Animatable.prototype.syncWith = function (root) {
  52334. this._syncRoot = root;
  52335. if (root) {
  52336. // Make sure this animatable will animate after the root
  52337. var index = this._scene._activeAnimatables.indexOf(this);
  52338. if (index > -1) {
  52339. this._scene._activeAnimatables.splice(index, 1);
  52340. this._scene._activeAnimatables.push(this);
  52341. }
  52342. }
  52343. return this;
  52344. };
  52345. /**
  52346. * Gets the list of runtime animations
  52347. * @returns an array of RuntimeAnimation
  52348. */
  52349. Animatable.prototype.getAnimations = function () {
  52350. return this._runtimeAnimations;
  52351. };
  52352. /**
  52353. * Adds more animations to the current animatable
  52354. * @param target defines the target of the animations
  52355. * @param animations defines the new animations to add
  52356. */
  52357. Animatable.prototype.appendAnimations = function (target, animations) {
  52358. for (var index = 0; index < animations.length; index++) {
  52359. var animation = animations[index];
  52360. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52361. }
  52362. };
  52363. /**
  52364. * Gets the source animation for a specific property
  52365. * @param property defines the propertyu to look for
  52366. * @returns null or the source animation for the given property
  52367. */
  52368. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52369. var runtimeAnimations = this._runtimeAnimations;
  52370. for (var index = 0; index < runtimeAnimations.length; index++) {
  52371. if (runtimeAnimations[index].animation.targetProperty === property) {
  52372. return runtimeAnimations[index].animation;
  52373. }
  52374. }
  52375. return null;
  52376. };
  52377. /**
  52378. * Gets the runtime animation for a specific property
  52379. * @param property defines the propertyu to look for
  52380. * @returns null or the runtime animation for the given property
  52381. */
  52382. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52383. var runtimeAnimations = this._runtimeAnimations;
  52384. for (var index = 0; index < runtimeAnimations.length; index++) {
  52385. if (runtimeAnimations[index].animation.targetProperty === property) {
  52386. return runtimeAnimations[index];
  52387. }
  52388. }
  52389. return null;
  52390. };
  52391. /**
  52392. * Resets the animatable to its original state
  52393. */
  52394. Animatable.prototype.reset = function () {
  52395. var runtimeAnimations = this._runtimeAnimations;
  52396. for (var index = 0; index < runtimeAnimations.length; index++) {
  52397. runtimeAnimations[index].reset(true);
  52398. }
  52399. this._localDelayOffset = null;
  52400. this._pausedDelay = null;
  52401. };
  52402. /**
  52403. * Allows the animatable to blend with current running animations
  52404. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52405. * @param blendingSpeed defines the blending speed to use
  52406. */
  52407. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52408. var runtimeAnimations = this._runtimeAnimations;
  52409. for (var index = 0; index < runtimeAnimations.length; index++) {
  52410. runtimeAnimations[index].animation.enableBlending = true;
  52411. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52412. }
  52413. };
  52414. /**
  52415. * Disable animation blending
  52416. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52417. */
  52418. Animatable.prototype.disableBlending = function () {
  52419. var runtimeAnimations = this._runtimeAnimations;
  52420. for (var index = 0; index < runtimeAnimations.length; index++) {
  52421. runtimeAnimations[index].animation.enableBlending = false;
  52422. }
  52423. };
  52424. /**
  52425. * Jump directly to a given frame
  52426. * @param frame defines the frame to jump to
  52427. */
  52428. Animatable.prototype.goToFrame = function (frame) {
  52429. var runtimeAnimations = this._runtimeAnimations;
  52430. if (runtimeAnimations[0]) {
  52431. var fps = runtimeAnimations[0].animation.framePerSecond;
  52432. var currentFrame = runtimeAnimations[0].currentFrame;
  52433. var adjustTime = frame - currentFrame;
  52434. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52435. if (this._localDelayOffset === null) {
  52436. this._localDelayOffset = 0;
  52437. }
  52438. this._localDelayOffset -= delay;
  52439. }
  52440. for (var index = 0; index < runtimeAnimations.length; index++) {
  52441. runtimeAnimations[index].goToFrame(frame);
  52442. }
  52443. };
  52444. /**
  52445. * Pause the animation
  52446. */
  52447. Animatable.prototype.pause = function () {
  52448. if (this._paused) {
  52449. return;
  52450. }
  52451. this._paused = true;
  52452. };
  52453. /**
  52454. * Restart the animation
  52455. */
  52456. Animatable.prototype.restart = function () {
  52457. this._paused = false;
  52458. };
  52459. Animatable.prototype._raiseOnAnimationEnd = function () {
  52460. if (this.onAnimationEnd) {
  52461. this.onAnimationEnd();
  52462. }
  52463. this.onAnimationEndObservable.notifyObservers(this);
  52464. };
  52465. /**
  52466. * Stop and delete the current animation
  52467. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52468. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  52469. */
  52470. Animatable.prototype.stop = function (animationName, targetMask) {
  52471. if (animationName || targetMask) {
  52472. var idx = this._scene._activeAnimatables.indexOf(this);
  52473. if (idx > -1) {
  52474. var runtimeAnimations = this._runtimeAnimations;
  52475. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52476. var runtimeAnimation = runtimeAnimations[index];
  52477. if (animationName && runtimeAnimation.animation.name != animationName) {
  52478. continue;
  52479. }
  52480. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52481. continue;
  52482. }
  52483. runtimeAnimation.dispose();
  52484. runtimeAnimations.splice(index, 1);
  52485. }
  52486. if (runtimeAnimations.length == 0) {
  52487. this._scene._activeAnimatables.splice(idx, 1);
  52488. this._raiseOnAnimationEnd();
  52489. }
  52490. }
  52491. }
  52492. else {
  52493. var index = this._scene._activeAnimatables.indexOf(this);
  52494. if (index > -1) {
  52495. this._scene._activeAnimatables.splice(index, 1);
  52496. var runtimeAnimations = this._runtimeAnimations;
  52497. for (var index = 0; index < runtimeAnimations.length; index++) {
  52498. runtimeAnimations[index].dispose();
  52499. }
  52500. this._raiseOnAnimationEnd();
  52501. }
  52502. }
  52503. };
  52504. /**
  52505. * Wait asynchronously for the animation to end
  52506. * @returns a promise which will be fullfilled when the animation ends
  52507. */
  52508. Animatable.prototype.waitAsync = function () {
  52509. var _this = this;
  52510. return new Promise(function (resolve, reject) {
  52511. _this.onAnimationEndObservable.add(function () {
  52512. resolve(_this);
  52513. }, undefined, undefined, _this, true);
  52514. });
  52515. };
  52516. /** @hidden */
  52517. Animatable.prototype._animate = function (delay) {
  52518. if (this._paused) {
  52519. this.animationStarted = false;
  52520. if (this._pausedDelay === null) {
  52521. this._pausedDelay = delay;
  52522. }
  52523. return true;
  52524. }
  52525. if (this._localDelayOffset === null) {
  52526. this._localDelayOffset = delay;
  52527. this._pausedDelay = null;
  52528. }
  52529. else if (this._pausedDelay !== null) {
  52530. this._localDelayOffset += delay - this._pausedDelay;
  52531. this._pausedDelay = null;
  52532. }
  52533. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52534. return true;
  52535. }
  52536. // Animating
  52537. var running = false;
  52538. var runtimeAnimations = this._runtimeAnimations;
  52539. var index;
  52540. for (index = 0; index < runtimeAnimations.length; index++) {
  52541. var animation = runtimeAnimations[index];
  52542. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52543. running = running || isRunning;
  52544. }
  52545. this.animationStarted = running;
  52546. if (!running) {
  52547. if (this.disposeOnEnd) {
  52548. // Remove from active animatables
  52549. index = this._scene._activeAnimatables.indexOf(this);
  52550. this._scene._activeAnimatables.splice(index, 1);
  52551. // Dispose all runtime animations
  52552. for (index = 0; index < runtimeAnimations.length; index++) {
  52553. runtimeAnimations[index].dispose();
  52554. }
  52555. }
  52556. this._raiseOnAnimationEnd();
  52557. if (this.disposeOnEnd) {
  52558. this.onAnimationEnd = null;
  52559. this.onAnimationEndObservable.clear();
  52560. }
  52561. }
  52562. return running;
  52563. };
  52564. return Animatable;
  52565. }());
  52566. BABYLON.Animatable = Animatable;
  52567. })(BABYLON || (BABYLON = {}));
  52568. //# sourceMappingURL=babylon.animatable.js.map
  52569. var BABYLON;
  52570. (function (BABYLON) {
  52571. /**
  52572. * Base class used for every default easing function.
  52573. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52574. */
  52575. var EasingFunction = /** @class */ (function () {
  52576. function EasingFunction() {
  52577. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52578. }
  52579. /**
  52580. * Sets the easing mode of the current function.
  52581. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  52582. */
  52583. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52584. var n = Math.min(Math.max(easingMode, 0), 2);
  52585. this._easingMode = n;
  52586. };
  52587. /**
  52588. * Gets the current easing mode.
  52589. * @returns the easing mode
  52590. */
  52591. EasingFunction.prototype.getEasingMode = function () {
  52592. return this._easingMode;
  52593. };
  52594. /**
  52595. * @hidden
  52596. */
  52597. EasingFunction.prototype.easeInCore = function (gradient) {
  52598. throw new Error('You must implement this method');
  52599. };
  52600. /**
  52601. * Given an input gradient between 0 and 1, this returns the corrseponding value
  52602. * of the easing function.
  52603. * @param gradient Defines the value between 0 and 1 we want the easing value for
  52604. * @returns the corresponding value on the curve defined by the easing function
  52605. */
  52606. EasingFunction.prototype.ease = function (gradient) {
  52607. switch (this._easingMode) {
  52608. case EasingFunction.EASINGMODE_EASEIN:
  52609. return this.easeInCore(gradient);
  52610. case EasingFunction.EASINGMODE_EASEOUT:
  52611. return (1 - this.easeInCore(1 - gradient));
  52612. }
  52613. if (gradient >= 0.5) {
  52614. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52615. }
  52616. return (this.easeInCore(gradient * 2) * 0.5);
  52617. };
  52618. /**
  52619. * Interpolation follows the mathematical formula associated with the easing function.
  52620. */
  52621. EasingFunction.EASINGMODE_EASEIN = 0;
  52622. /**
  52623. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  52624. */
  52625. EasingFunction.EASINGMODE_EASEOUT = 1;
  52626. /**
  52627. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  52628. */
  52629. EasingFunction.EASINGMODE_EASEINOUT = 2;
  52630. return EasingFunction;
  52631. }());
  52632. BABYLON.EasingFunction = EasingFunction;
  52633. /**
  52634. * Easing function with a circle shape (see link below).
  52635. * @see https://easings.net/#easeInCirc
  52636. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52637. */
  52638. var CircleEase = /** @class */ (function (_super) {
  52639. __extends(CircleEase, _super);
  52640. function CircleEase() {
  52641. return _super !== null && _super.apply(this, arguments) || this;
  52642. }
  52643. /** @hidden */
  52644. CircleEase.prototype.easeInCore = function (gradient) {
  52645. gradient = Math.max(0, Math.min(1, gradient));
  52646. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52647. };
  52648. return CircleEase;
  52649. }(EasingFunction));
  52650. BABYLON.CircleEase = CircleEase;
  52651. /**
  52652. * Easing function with a ease back shape (see link below).
  52653. * @see https://easings.net/#easeInBack
  52654. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52655. */
  52656. var BackEase = /** @class */ (function (_super) {
  52657. __extends(BackEase, _super);
  52658. /**
  52659. * Instantiates a back ease easing
  52660. * @see https://easings.net/#easeInBack
  52661. * @param amplitude Defines the amplitude of the function
  52662. */
  52663. function BackEase(
  52664. /** Defines the amplitude of the function */
  52665. amplitude) {
  52666. if (amplitude === void 0) { amplitude = 1; }
  52667. var _this = _super.call(this) || this;
  52668. _this.amplitude = amplitude;
  52669. return _this;
  52670. }
  52671. /** @hidden */
  52672. BackEase.prototype.easeInCore = function (gradient) {
  52673. var num = Math.max(0, this.amplitude);
  52674. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52675. };
  52676. return BackEase;
  52677. }(EasingFunction));
  52678. BABYLON.BackEase = BackEase;
  52679. /**
  52680. * Easing function with a bouncing shape (see link below).
  52681. * @see https://easings.net/#easeInBounce
  52682. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52683. */
  52684. var BounceEase = /** @class */ (function (_super) {
  52685. __extends(BounceEase, _super);
  52686. /**
  52687. * Instantiates a bounce easing
  52688. * @see https://easings.net/#easeInBounce
  52689. * @param bounces Defines the number of bounces
  52690. * @param bounciness Defines the amplitude of the bounce
  52691. */
  52692. function BounceEase(
  52693. /** Defines the number of bounces */
  52694. bounces,
  52695. /** Defines the amplitude of the bounce */
  52696. bounciness) {
  52697. if (bounces === void 0) { bounces = 3; }
  52698. if (bounciness === void 0) { bounciness = 2; }
  52699. var _this = _super.call(this) || this;
  52700. _this.bounces = bounces;
  52701. _this.bounciness = bounciness;
  52702. return _this;
  52703. }
  52704. /** @hidden */
  52705. BounceEase.prototype.easeInCore = function (gradient) {
  52706. var y = Math.max(0.0, this.bounces);
  52707. var bounciness = this.bounciness;
  52708. if (bounciness <= 1.0) {
  52709. bounciness = 1.001;
  52710. }
  52711. var num9 = Math.pow(bounciness, y);
  52712. var num5 = 1.0 - bounciness;
  52713. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52714. var num15 = gradient * num4;
  52715. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52716. var num3 = Math.floor(num65);
  52717. var num13 = num3 + 1.0;
  52718. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52719. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52720. var num7 = (num8 + num12) * 0.5;
  52721. var num6 = gradient - num7;
  52722. var num2 = num7 - num8;
  52723. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52724. };
  52725. return BounceEase;
  52726. }(EasingFunction));
  52727. BABYLON.BounceEase = BounceEase;
  52728. /**
  52729. * Easing function with a power of 3 shape (see link below).
  52730. * @see https://easings.net/#easeInCubic
  52731. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52732. */
  52733. var CubicEase = /** @class */ (function (_super) {
  52734. __extends(CubicEase, _super);
  52735. function CubicEase() {
  52736. return _super !== null && _super.apply(this, arguments) || this;
  52737. }
  52738. /** @hidden */
  52739. CubicEase.prototype.easeInCore = function (gradient) {
  52740. return (gradient * gradient * gradient);
  52741. };
  52742. return CubicEase;
  52743. }(EasingFunction));
  52744. BABYLON.CubicEase = CubicEase;
  52745. /**
  52746. * Easing function with an elastic shape (see link below).
  52747. * @see https://easings.net/#easeInElastic
  52748. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52749. */
  52750. var ElasticEase = /** @class */ (function (_super) {
  52751. __extends(ElasticEase, _super);
  52752. /**
  52753. * Instantiates an elastic easing function
  52754. * @see https://easings.net/#easeInElastic
  52755. * @param oscillations Defines the number of oscillations
  52756. * @param springiness Defines the amplitude of the oscillations
  52757. */
  52758. function ElasticEase(
  52759. /** Defines the number of oscillations*/
  52760. oscillations,
  52761. /** Defines the amplitude of the oscillations*/
  52762. springiness) {
  52763. if (oscillations === void 0) { oscillations = 3; }
  52764. if (springiness === void 0) { springiness = 3; }
  52765. var _this = _super.call(this) || this;
  52766. _this.oscillations = oscillations;
  52767. _this.springiness = springiness;
  52768. return _this;
  52769. }
  52770. /** @hidden */
  52771. ElasticEase.prototype.easeInCore = function (gradient) {
  52772. var num2;
  52773. var num3 = Math.max(0.0, this.oscillations);
  52774. var num = Math.max(0.0, this.springiness);
  52775. if (num == 0) {
  52776. num2 = gradient;
  52777. }
  52778. else {
  52779. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52780. }
  52781. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52782. };
  52783. return ElasticEase;
  52784. }(EasingFunction));
  52785. BABYLON.ElasticEase = ElasticEase;
  52786. /**
  52787. * Easing function with an exponential shape (see link below).
  52788. * @see https://easings.net/#easeInExpo
  52789. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52790. */
  52791. var ExponentialEase = /** @class */ (function (_super) {
  52792. __extends(ExponentialEase, _super);
  52793. /**
  52794. * Instantiates an exponential easing function
  52795. * @see https://easings.net/#easeInExpo
  52796. * @param exponent Defines the exponent of the function
  52797. */
  52798. function ExponentialEase(
  52799. /** Defines the exponent of the function */
  52800. exponent) {
  52801. if (exponent === void 0) { exponent = 2; }
  52802. var _this = _super.call(this) || this;
  52803. _this.exponent = exponent;
  52804. return _this;
  52805. }
  52806. /** @hidden */
  52807. ExponentialEase.prototype.easeInCore = function (gradient) {
  52808. if (this.exponent <= 0) {
  52809. return gradient;
  52810. }
  52811. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52812. };
  52813. return ExponentialEase;
  52814. }(EasingFunction));
  52815. BABYLON.ExponentialEase = ExponentialEase;
  52816. /**
  52817. * Easing function with a power shape (see link below).
  52818. * @see https://easings.net/#easeInQuad
  52819. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52820. */
  52821. var PowerEase = /** @class */ (function (_super) {
  52822. __extends(PowerEase, _super);
  52823. /**
  52824. * Instantiates an power base easing function
  52825. * @see https://easings.net/#easeInQuad
  52826. * @param power Defines the power of the function
  52827. */
  52828. function PowerEase(
  52829. /** Defines the power of the function */
  52830. power) {
  52831. if (power === void 0) { power = 2; }
  52832. var _this = _super.call(this) || this;
  52833. _this.power = power;
  52834. return _this;
  52835. }
  52836. /** @hidden */
  52837. PowerEase.prototype.easeInCore = function (gradient) {
  52838. var y = Math.max(0.0, this.power);
  52839. return Math.pow(gradient, y);
  52840. };
  52841. return PowerEase;
  52842. }(EasingFunction));
  52843. BABYLON.PowerEase = PowerEase;
  52844. /**
  52845. * Easing function with a power of 2 shape (see link below).
  52846. * @see https://easings.net/#easeInQuad
  52847. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52848. */
  52849. var QuadraticEase = /** @class */ (function (_super) {
  52850. __extends(QuadraticEase, _super);
  52851. function QuadraticEase() {
  52852. return _super !== null && _super.apply(this, arguments) || this;
  52853. }
  52854. /** @hidden */
  52855. QuadraticEase.prototype.easeInCore = function (gradient) {
  52856. return (gradient * gradient);
  52857. };
  52858. return QuadraticEase;
  52859. }(EasingFunction));
  52860. BABYLON.QuadraticEase = QuadraticEase;
  52861. /**
  52862. * Easing function with a power of 4 shape (see link below).
  52863. * @see https://easings.net/#easeInQuart
  52864. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52865. */
  52866. var QuarticEase = /** @class */ (function (_super) {
  52867. __extends(QuarticEase, _super);
  52868. function QuarticEase() {
  52869. return _super !== null && _super.apply(this, arguments) || this;
  52870. }
  52871. /** @hidden */
  52872. QuarticEase.prototype.easeInCore = function (gradient) {
  52873. return (gradient * gradient * gradient * gradient);
  52874. };
  52875. return QuarticEase;
  52876. }(EasingFunction));
  52877. BABYLON.QuarticEase = QuarticEase;
  52878. /**
  52879. * Easing function with a power of 5 shape (see link below).
  52880. * @see https://easings.net/#easeInQuint
  52881. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52882. */
  52883. var QuinticEase = /** @class */ (function (_super) {
  52884. __extends(QuinticEase, _super);
  52885. function QuinticEase() {
  52886. return _super !== null && _super.apply(this, arguments) || this;
  52887. }
  52888. /** @hidden */
  52889. QuinticEase.prototype.easeInCore = function (gradient) {
  52890. return (gradient * gradient * gradient * gradient * gradient);
  52891. };
  52892. return QuinticEase;
  52893. }(EasingFunction));
  52894. BABYLON.QuinticEase = QuinticEase;
  52895. /**
  52896. * Easing function with a sin shape (see link below).
  52897. * @see https://easings.net/#easeInSine
  52898. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52899. */
  52900. var SineEase = /** @class */ (function (_super) {
  52901. __extends(SineEase, _super);
  52902. function SineEase() {
  52903. return _super !== null && _super.apply(this, arguments) || this;
  52904. }
  52905. /** @hidden */
  52906. SineEase.prototype.easeInCore = function (gradient) {
  52907. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52908. };
  52909. return SineEase;
  52910. }(EasingFunction));
  52911. BABYLON.SineEase = SineEase;
  52912. /**
  52913. * Easing function with a bezier shape (see link below).
  52914. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  52915. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52916. */
  52917. var BezierCurveEase = /** @class */ (function (_super) {
  52918. __extends(BezierCurveEase, _super);
  52919. /**
  52920. * Instantiates a bezier function
  52921. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  52922. * @param x1 Defines the x component of the start tangent in the bezier curve
  52923. * @param y1 Defines the y component of the start tangent in the bezier curve
  52924. * @param x2 Defines the x component of the end tangent in the bezier curve
  52925. * @param y2 Defines the y component of the end tangent in the bezier curve
  52926. */
  52927. function BezierCurveEase(
  52928. /** Defines the x component of the start tangent in the bezier curve */
  52929. x1,
  52930. /** Defines the y component of the start tangent in the bezier curve */
  52931. y1,
  52932. /** Defines the x component of the end tangent in the bezier curve */
  52933. x2,
  52934. /** Defines the y component of the end tangent in the bezier curve */
  52935. y2) {
  52936. if (x1 === void 0) { x1 = 0; }
  52937. if (y1 === void 0) { y1 = 0; }
  52938. if (x2 === void 0) { x2 = 1; }
  52939. if (y2 === void 0) { y2 = 1; }
  52940. var _this = _super.call(this) || this;
  52941. _this.x1 = x1;
  52942. _this.y1 = y1;
  52943. _this.x2 = x2;
  52944. _this.y2 = y2;
  52945. return _this;
  52946. }
  52947. /** @hidden */
  52948. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52949. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52950. };
  52951. return BezierCurveEase;
  52952. }(EasingFunction));
  52953. BABYLON.BezierCurveEase = BezierCurveEase;
  52954. })(BABYLON || (BABYLON = {}));
  52955. //# sourceMappingURL=babylon.easing.js.map
  52956. var BABYLON;
  52957. (function (BABYLON) {
  52958. /**
  52959. * A Condition applied to an Action
  52960. */
  52961. var Condition = /** @class */ (function () {
  52962. /**
  52963. * Creates a new Condition
  52964. * @param actionManager the manager of the action the condition is applied to
  52965. */
  52966. function Condition(actionManager) {
  52967. this._actionManager = actionManager;
  52968. }
  52969. /**
  52970. * Check if the current condition is valid
  52971. * @returns a boolean
  52972. */
  52973. Condition.prototype.isValid = function () {
  52974. return true;
  52975. };
  52976. /**
  52977. * Internal only
  52978. * @hidden
  52979. */
  52980. Condition.prototype._getProperty = function (propertyPath) {
  52981. return this._actionManager._getProperty(propertyPath);
  52982. };
  52983. /**
  52984. * Internal only
  52985. * @hidden
  52986. */
  52987. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52988. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52989. };
  52990. /**
  52991. * Serialize placeholder for child classes
  52992. * @returns the serialized object
  52993. */
  52994. Condition.prototype.serialize = function () {
  52995. };
  52996. /**
  52997. * Internal only
  52998. * @hidden
  52999. */
  53000. Condition.prototype._serialize = function (serializedCondition) {
  53001. return {
  53002. type: 2,
  53003. children: [],
  53004. name: serializedCondition.name,
  53005. properties: serializedCondition.properties
  53006. };
  53007. };
  53008. return Condition;
  53009. }());
  53010. BABYLON.Condition = Condition;
  53011. /**
  53012. * Defines specific conditional operators as extensions of Condition
  53013. */
  53014. var ValueCondition = /** @class */ (function (_super) {
  53015. __extends(ValueCondition, _super);
  53016. /**
  53017. * Creates a new ValueCondition
  53018. * @param actionManager manager for the action the condition applies to
  53019. * @param target for the action
  53020. * @param propertyPath path to specify the property of the target the conditional operator uses
  53021. * @param value the value compared by the conditional operator against the current value of the property
  53022. * @param operator the conditional operator, default ValueCondition.IsEqual
  53023. */
  53024. function ValueCondition(actionManager, target,
  53025. /** path to specify the property of the target the conditional operator uses */
  53026. propertyPath,
  53027. /** the value compared by the conditional operator against the current value of the property */
  53028. value,
  53029. /** the conditional operator, default ValueCondition.IsEqual */
  53030. operator) {
  53031. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53032. var _this = _super.call(this, actionManager) || this;
  53033. _this.propertyPath = propertyPath;
  53034. _this.value = value;
  53035. _this.operator = operator;
  53036. _this._target = target;
  53037. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53038. _this._property = _this._getProperty(_this.propertyPath);
  53039. return _this;
  53040. }
  53041. Object.defineProperty(ValueCondition, "IsEqual", {
  53042. /**
  53043. * returns the number for IsEqual
  53044. */
  53045. get: function () {
  53046. return ValueCondition._IsEqual;
  53047. },
  53048. enumerable: true,
  53049. configurable: true
  53050. });
  53051. Object.defineProperty(ValueCondition, "IsDifferent", {
  53052. /**
  53053. * Returns the number for IsDifferent
  53054. */
  53055. get: function () {
  53056. return ValueCondition._IsDifferent;
  53057. },
  53058. enumerable: true,
  53059. configurable: true
  53060. });
  53061. Object.defineProperty(ValueCondition, "IsGreater", {
  53062. /**
  53063. * Returns the number for IsGreater
  53064. */
  53065. get: function () {
  53066. return ValueCondition._IsGreater;
  53067. },
  53068. enumerable: true,
  53069. configurable: true
  53070. });
  53071. Object.defineProperty(ValueCondition, "IsLesser", {
  53072. /**
  53073. * Returns the number for IsLesser
  53074. */
  53075. get: function () {
  53076. return ValueCondition._IsLesser;
  53077. },
  53078. enumerable: true,
  53079. configurable: true
  53080. });
  53081. /**
  53082. * Compares the given value with the property value for the specified conditional operator
  53083. * @returns the result of the comparison
  53084. */
  53085. ValueCondition.prototype.isValid = function () {
  53086. switch (this.operator) {
  53087. case ValueCondition.IsGreater:
  53088. return this._effectiveTarget[this._property] > this.value;
  53089. case ValueCondition.IsLesser:
  53090. return this._effectiveTarget[this._property] < this.value;
  53091. case ValueCondition.IsEqual:
  53092. case ValueCondition.IsDifferent:
  53093. var check;
  53094. if (this.value.equals) {
  53095. check = this.value.equals(this._effectiveTarget[this._property]);
  53096. }
  53097. else {
  53098. check = this.value === this._effectiveTarget[this._property];
  53099. }
  53100. return this.operator === ValueCondition.IsEqual ? check : !check;
  53101. }
  53102. return false;
  53103. };
  53104. /**
  53105. * Serialize the ValueCondition into a JSON compatible object
  53106. * @returns serialization object
  53107. */
  53108. ValueCondition.prototype.serialize = function () {
  53109. return this._serialize({
  53110. name: "ValueCondition",
  53111. properties: [
  53112. BABYLON.Action._GetTargetProperty(this._target),
  53113. { name: "propertyPath", value: this.propertyPath },
  53114. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53115. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53116. ]
  53117. });
  53118. };
  53119. /**
  53120. * Gets the name of the conditional operator for the ValueCondition
  53121. * @param operator the conditional operator
  53122. * @returns the name
  53123. */
  53124. ValueCondition.GetOperatorName = function (operator) {
  53125. switch (operator) {
  53126. case ValueCondition._IsEqual: return "IsEqual";
  53127. case ValueCondition._IsDifferent: return "IsDifferent";
  53128. case ValueCondition._IsGreater: return "IsGreater";
  53129. case ValueCondition._IsLesser: return "IsLesser";
  53130. default: return "";
  53131. }
  53132. };
  53133. /**
  53134. * Internal only
  53135. * @hidden
  53136. */
  53137. ValueCondition._IsEqual = 0;
  53138. /**
  53139. * Internal only
  53140. * @hidden
  53141. */
  53142. ValueCondition._IsDifferent = 1;
  53143. /**
  53144. * Internal only
  53145. * @hidden
  53146. */
  53147. ValueCondition._IsGreater = 2;
  53148. /**
  53149. * Internal only
  53150. * @hidden
  53151. */
  53152. ValueCondition._IsLesser = 3;
  53153. return ValueCondition;
  53154. }(Condition));
  53155. BABYLON.ValueCondition = ValueCondition;
  53156. /**
  53157. * Defines a predicate condition as an extension of Condition
  53158. */
  53159. var PredicateCondition = /** @class */ (function (_super) {
  53160. __extends(PredicateCondition, _super);
  53161. /**
  53162. * Creates a new PredicateCondition
  53163. * @param actionManager manager for the action the condition applies to
  53164. * @param predicate defines the predicate function used to validate the condition
  53165. */
  53166. function PredicateCondition(actionManager,
  53167. /** defines the predicate function used to validate the condition */
  53168. predicate) {
  53169. var _this = _super.call(this, actionManager) || this;
  53170. _this.predicate = predicate;
  53171. return _this;
  53172. }
  53173. /**
  53174. * @returns the validity of the predicate condition
  53175. */
  53176. PredicateCondition.prototype.isValid = function () {
  53177. return this.predicate();
  53178. };
  53179. return PredicateCondition;
  53180. }(Condition));
  53181. BABYLON.PredicateCondition = PredicateCondition;
  53182. /**
  53183. * Defines a state condition as an extension of Condition
  53184. */
  53185. var StateCondition = /** @class */ (function (_super) {
  53186. __extends(StateCondition, _super);
  53187. /**
  53188. * Creates a new StateCondition
  53189. * @param actionManager manager for the action the condition applies to
  53190. * @param target of the condition
  53191. * @param value to compare with target state
  53192. */
  53193. function StateCondition(actionManager, target, value) {
  53194. var _this = _super.call(this, actionManager) || this;
  53195. _this.value = value;
  53196. _this._target = target;
  53197. return _this;
  53198. }
  53199. /**
  53200. * @returns the validity of the state
  53201. */
  53202. StateCondition.prototype.isValid = function () {
  53203. return this._target.state === this.value;
  53204. };
  53205. /**
  53206. * Serialize the StateCondition into a JSON compatible object
  53207. * @returns serialization object
  53208. */
  53209. StateCondition.prototype.serialize = function () {
  53210. return this._serialize({
  53211. name: "StateCondition",
  53212. properties: [
  53213. BABYLON.Action._GetTargetProperty(this._target),
  53214. { name: "value", value: this.value }
  53215. ]
  53216. });
  53217. };
  53218. return StateCondition;
  53219. }(Condition));
  53220. BABYLON.StateCondition = StateCondition;
  53221. })(BABYLON || (BABYLON = {}));
  53222. //# sourceMappingURL=babylon.condition.js.map
  53223. var BABYLON;
  53224. (function (BABYLON) {
  53225. /**
  53226. * The action to be carried out following a trigger
  53227. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53228. */
  53229. var Action = /** @class */ (function () {
  53230. /**
  53231. * Creates a new Action
  53232. * @param triggerOptions the trigger, with or without parameters, for the action
  53233. * @param condition an optional determinant of action
  53234. */
  53235. function Action(
  53236. /** the trigger, with or without parameters, for the action */
  53237. triggerOptions, condition) {
  53238. this.triggerOptions = triggerOptions;
  53239. /**
  53240. * An event triggered prior to action being executed.
  53241. */
  53242. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53243. if (triggerOptions.parameter) {
  53244. this.trigger = triggerOptions.trigger;
  53245. this._triggerParameter = triggerOptions.parameter;
  53246. }
  53247. else if (triggerOptions.trigger) {
  53248. this.trigger = triggerOptions.trigger;
  53249. }
  53250. else {
  53251. this.trigger = triggerOptions;
  53252. }
  53253. this._nextActiveAction = this;
  53254. this._condition = condition;
  53255. }
  53256. /**
  53257. * Internal only
  53258. * @hidden
  53259. */
  53260. Action.prototype._prepare = function () {
  53261. };
  53262. /**
  53263. * Gets the trigger parameters
  53264. * @returns the trigger parameters
  53265. */
  53266. Action.prototype.getTriggerParameter = function () {
  53267. return this._triggerParameter;
  53268. };
  53269. /**
  53270. * Internal only - executes current action event
  53271. * @hidden
  53272. */
  53273. Action.prototype._executeCurrent = function (evt) {
  53274. if (this._nextActiveAction._condition) {
  53275. var condition = this._nextActiveAction._condition;
  53276. var currentRenderId = this._actionManager.getScene().getRenderId();
  53277. // We cache the current evaluation for the current frame
  53278. if (condition._evaluationId === currentRenderId) {
  53279. if (!condition._currentResult) {
  53280. return;
  53281. }
  53282. }
  53283. else {
  53284. condition._evaluationId = currentRenderId;
  53285. if (!condition.isValid()) {
  53286. condition._currentResult = false;
  53287. return;
  53288. }
  53289. condition._currentResult = true;
  53290. }
  53291. }
  53292. this.onBeforeExecuteObservable.notifyObservers(this);
  53293. this._nextActiveAction.execute(evt);
  53294. this.skipToNextActiveAction();
  53295. };
  53296. /**
  53297. * Execute placeholder for child classes
  53298. * @param evt optional action event
  53299. */
  53300. Action.prototype.execute = function (evt) {
  53301. };
  53302. /**
  53303. * Skips to next active action
  53304. */
  53305. Action.prototype.skipToNextActiveAction = function () {
  53306. if (this._nextActiveAction._child) {
  53307. if (!this._nextActiveAction._child._actionManager) {
  53308. this._nextActiveAction._child._actionManager = this._actionManager;
  53309. }
  53310. this._nextActiveAction = this._nextActiveAction._child;
  53311. }
  53312. else {
  53313. this._nextActiveAction = this;
  53314. }
  53315. };
  53316. /**
  53317. * Adds action to chain of actions, may be a DoNothingAction
  53318. * @param action defines the next action to execute
  53319. * @returns The action passed in
  53320. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53321. */
  53322. Action.prototype.then = function (action) {
  53323. this._child = action;
  53324. action._actionManager = this._actionManager;
  53325. action._prepare();
  53326. return action;
  53327. };
  53328. /**
  53329. * Internal only
  53330. * @hidden
  53331. */
  53332. Action.prototype._getProperty = function (propertyPath) {
  53333. return this._actionManager._getProperty(propertyPath);
  53334. };
  53335. /**
  53336. * Internal only
  53337. * @hidden
  53338. */
  53339. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53340. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53341. };
  53342. /**
  53343. * Serialize placeholder for child classes
  53344. * @param parent of child
  53345. * @returns the serialized object
  53346. */
  53347. Action.prototype.serialize = function (parent) {
  53348. };
  53349. /**
  53350. * Internal only called by serialize
  53351. * @hidden
  53352. */
  53353. Action.prototype._serialize = function (serializedAction, parent) {
  53354. var serializationObject = {
  53355. type: 1,
  53356. children: [],
  53357. name: serializedAction.name,
  53358. properties: serializedAction.properties || []
  53359. };
  53360. // Serialize child
  53361. if (this._child) {
  53362. this._child.serialize(serializationObject);
  53363. }
  53364. // Check if "this" has a condition
  53365. if (this._condition) {
  53366. var serializedCondition = this._condition.serialize();
  53367. serializedCondition.children.push(serializationObject);
  53368. if (parent) {
  53369. parent.children.push(serializedCondition);
  53370. }
  53371. return serializedCondition;
  53372. }
  53373. if (parent) {
  53374. parent.children.push(serializationObject);
  53375. }
  53376. return serializationObject;
  53377. };
  53378. /**
  53379. * Internal only
  53380. * @hidden
  53381. */
  53382. Action._SerializeValueAsString = function (value) {
  53383. if (typeof value === "number") {
  53384. return value.toString();
  53385. }
  53386. if (typeof value === "boolean") {
  53387. return value ? "true" : "false";
  53388. }
  53389. if (value instanceof BABYLON.Vector2) {
  53390. return value.x + ", " + value.y;
  53391. }
  53392. if (value instanceof BABYLON.Vector3) {
  53393. return value.x + ", " + value.y + ", " + value.z;
  53394. }
  53395. if (value instanceof BABYLON.Color3) {
  53396. return value.r + ", " + value.g + ", " + value.b;
  53397. }
  53398. if (value instanceof BABYLON.Color4) {
  53399. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53400. }
  53401. return value; // string
  53402. };
  53403. /**
  53404. * Internal only
  53405. * @hidden
  53406. */
  53407. Action._GetTargetProperty = function (target) {
  53408. return {
  53409. name: "target",
  53410. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53411. : target instanceof BABYLON.Light ? "LightProperties"
  53412. : target instanceof BABYLON.Camera ? "CameraProperties"
  53413. : "SceneProperties",
  53414. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53415. };
  53416. };
  53417. return Action;
  53418. }());
  53419. BABYLON.Action = Action;
  53420. })(BABYLON || (BABYLON = {}));
  53421. //# sourceMappingURL=babylon.action.js.map
  53422. var BABYLON;
  53423. (function (BABYLON) {
  53424. /**
  53425. * ActionEvent is the event being sent when an action is triggered.
  53426. */
  53427. var ActionEvent = /** @class */ (function () {
  53428. /**
  53429. * Creates a new ActionEvent
  53430. * @param source The mesh or sprite that triggered the action
  53431. * @param pointerX The X mouse cursor position at the time of the event
  53432. * @param pointerY The Y mouse cursor position at the time of the event
  53433. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53434. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53435. * @param additionalData additional data for the event
  53436. */
  53437. function ActionEvent(
  53438. /** The mesh or sprite that triggered the action */
  53439. source,
  53440. /** The X mouse cursor position at the time of the event */
  53441. pointerX,
  53442. /** The Y mouse cursor position at the time of the event */
  53443. pointerY,
  53444. /** The mesh that is currently pointed at (can be null) */
  53445. meshUnderPointer,
  53446. /** the original (browser) event that triggered the ActionEvent */
  53447. sourceEvent,
  53448. /** additional data for the event */
  53449. additionalData) {
  53450. this.source = source;
  53451. this.pointerX = pointerX;
  53452. this.pointerY = pointerY;
  53453. this.meshUnderPointer = meshUnderPointer;
  53454. this.sourceEvent = sourceEvent;
  53455. this.additionalData = additionalData;
  53456. }
  53457. /**
  53458. * Helper function to auto-create an ActionEvent from a source mesh.
  53459. * @param source The source mesh that triggered the event
  53460. * @param evt The original (browser) event
  53461. * @param additionalData additional data for the event
  53462. * @returns the new ActionEvent
  53463. */
  53464. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53465. var scene = source.getScene();
  53466. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53467. };
  53468. /**
  53469. * Helper function to auto-create an ActionEvent from a source sprite
  53470. * @param source The source sprite that triggered the event
  53471. * @param scene Scene associated with the sprite
  53472. * @param evt The original (browser) event
  53473. * @param additionalData additional data for the event
  53474. * @returns the new ActionEvent
  53475. */
  53476. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53477. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53478. };
  53479. /**
  53480. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53481. * @param scene the scene where the event occurred
  53482. * @param evt The original (browser) event
  53483. * @returns the new ActionEvent
  53484. */
  53485. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53486. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53487. };
  53488. /**
  53489. * Helper function to auto-create an ActionEvent from a primitive
  53490. * @param prim defines the target primitive
  53491. * @param pointerPos defines the pointer position
  53492. * @param evt The original (browser) event
  53493. * @param additionalData additional data for the event
  53494. * @returns the new ActionEvent
  53495. */
  53496. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53497. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53498. };
  53499. return ActionEvent;
  53500. }());
  53501. BABYLON.ActionEvent = ActionEvent;
  53502. /**
  53503. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53504. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53505. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53506. */
  53507. var ActionManager = /** @class */ (function () {
  53508. /**
  53509. * Creates a new action manager
  53510. * @param scene defines the hosting scene
  53511. */
  53512. function ActionManager(scene) {
  53513. // Members
  53514. /** Gets the list of actions */
  53515. this.actions = new Array();
  53516. /** Gets the cursor to use when hovering items */
  53517. this.hoverCursor = '';
  53518. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53519. scene.actionManagers.push(this);
  53520. }
  53521. // Methods
  53522. /**
  53523. * Releases all associated resources
  53524. */
  53525. ActionManager.prototype.dispose = function () {
  53526. var index = this._scene.actionManagers.indexOf(this);
  53527. for (var i = 0; i < this.actions.length; i++) {
  53528. var action = this.actions[i];
  53529. ActionManager.Triggers[action.trigger]--;
  53530. if (ActionManager.Triggers[action.trigger] === 0) {
  53531. delete ActionManager.Triggers[action.trigger];
  53532. }
  53533. }
  53534. if (index > -1) {
  53535. this._scene.actionManagers.splice(index, 1);
  53536. }
  53537. };
  53538. /**
  53539. * Gets hosting scene
  53540. * @returns the hosting scene
  53541. */
  53542. ActionManager.prototype.getScene = function () {
  53543. return this._scene;
  53544. };
  53545. /**
  53546. * Does this action manager handles actions of any of the given triggers
  53547. * @param triggers defines the triggers to be tested
  53548. * @return a boolean indicating whether one (or more) of the triggers is handled
  53549. */
  53550. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53551. for (var index = 0; index < this.actions.length; index++) {
  53552. var action = this.actions[index];
  53553. if (triggers.indexOf(action.trigger) > -1) {
  53554. return true;
  53555. }
  53556. }
  53557. return false;
  53558. };
  53559. /**
  53560. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53561. * speed.
  53562. * @param triggerA defines the trigger to be tested
  53563. * @param triggerB defines the trigger to be tested
  53564. * @return a boolean indicating whether one (or more) of the triggers is handled
  53565. */
  53566. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53567. for (var index = 0; index < this.actions.length; index++) {
  53568. var action = this.actions[index];
  53569. if (triggerA == action.trigger || triggerB == action.trigger) {
  53570. return true;
  53571. }
  53572. }
  53573. return false;
  53574. };
  53575. /**
  53576. * Does this action manager handles actions of a given trigger
  53577. * @param trigger defines the trigger to be tested
  53578. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53579. * @return whether the trigger is handled
  53580. */
  53581. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53582. for (var index = 0; index < this.actions.length; index++) {
  53583. var action = this.actions[index];
  53584. if (action.trigger === trigger) {
  53585. if (parameterPredicate) {
  53586. if (parameterPredicate(action.getTriggerParameter())) {
  53587. return true;
  53588. }
  53589. }
  53590. else {
  53591. return true;
  53592. }
  53593. }
  53594. }
  53595. return false;
  53596. };
  53597. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53598. /**
  53599. * Does this action manager has pointer triggers
  53600. */
  53601. get: function () {
  53602. for (var index = 0; index < this.actions.length; index++) {
  53603. var action = this.actions[index];
  53604. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  53605. return true;
  53606. }
  53607. }
  53608. return false;
  53609. },
  53610. enumerable: true,
  53611. configurable: true
  53612. });
  53613. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53614. /**
  53615. * Does this action manager has pick triggers
  53616. */
  53617. get: function () {
  53618. for (var index = 0; index < this.actions.length; index++) {
  53619. var action = this.actions[index];
  53620. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  53621. return true;
  53622. }
  53623. }
  53624. return false;
  53625. },
  53626. enumerable: true,
  53627. configurable: true
  53628. });
  53629. Object.defineProperty(ActionManager, "HasTriggers", {
  53630. /**
  53631. * Does exist one action manager with at least one trigger
  53632. **/
  53633. get: function () {
  53634. for (var t in ActionManager.Triggers) {
  53635. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53636. return true;
  53637. }
  53638. }
  53639. return false;
  53640. },
  53641. enumerable: true,
  53642. configurable: true
  53643. });
  53644. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53645. /**
  53646. * Does exist one action manager with at least one pick trigger
  53647. **/
  53648. get: function () {
  53649. for (var t in ActionManager.Triggers) {
  53650. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53651. var t_int = parseInt(t);
  53652. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  53653. return true;
  53654. }
  53655. }
  53656. }
  53657. return false;
  53658. },
  53659. enumerable: true,
  53660. configurable: true
  53661. });
  53662. /**
  53663. * Does exist one action manager that handles actions of a given trigger
  53664. * @param trigger defines the trigger to be tested
  53665. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53666. **/
  53667. ActionManager.HasSpecificTrigger = function (trigger) {
  53668. for (var t in ActionManager.Triggers) {
  53669. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53670. var t_int = parseInt(t);
  53671. if (t_int === trigger) {
  53672. return true;
  53673. }
  53674. }
  53675. }
  53676. return false;
  53677. };
  53678. /**
  53679. * Registers an action to this action manager
  53680. * @param action defines the action to be registered
  53681. * @return the action amended (prepared) after registration
  53682. */
  53683. ActionManager.prototype.registerAction = function (action) {
  53684. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53685. if (this.getScene().actionManager !== this) {
  53686. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53687. return null;
  53688. }
  53689. }
  53690. this.actions.push(action);
  53691. if (ActionManager.Triggers[action.trigger]) {
  53692. ActionManager.Triggers[action.trigger]++;
  53693. }
  53694. else {
  53695. ActionManager.Triggers[action.trigger] = 1;
  53696. }
  53697. action._actionManager = this;
  53698. action._prepare();
  53699. return action;
  53700. };
  53701. /**
  53702. * Unregisters an action to this action manager
  53703. * @param action defines the action to be unregistered
  53704. * @return a boolean indicating whether the action has been unregistered
  53705. */
  53706. ActionManager.prototype.unregisterAction = function (action) {
  53707. var index = this.actions.indexOf(action);
  53708. if (index !== -1) {
  53709. this.actions.splice(index, 1);
  53710. ActionManager.Triggers[action.trigger] -= 1;
  53711. if (ActionManager.Triggers[action.trigger] === 0) {
  53712. delete ActionManager.Triggers[action.trigger];
  53713. }
  53714. delete action._actionManager;
  53715. return true;
  53716. }
  53717. return false;
  53718. };
  53719. /**
  53720. * Process a specific trigger
  53721. * @param trigger defines the trigger to process
  53722. * @param evt defines the event details to be processed
  53723. */
  53724. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53725. for (var index = 0; index < this.actions.length; index++) {
  53726. var action = this.actions[index];
  53727. if (action.trigger === trigger) {
  53728. if (evt) {
  53729. if (trigger === ActionManager.OnKeyUpTrigger
  53730. || trigger === ActionManager.OnKeyDownTrigger) {
  53731. var parameter = action.getTriggerParameter();
  53732. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53733. if (!parameter.toLowerCase) {
  53734. continue;
  53735. }
  53736. var lowerCase = parameter.toLowerCase();
  53737. if (lowerCase !== evt.sourceEvent.key) {
  53738. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53739. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53740. if (actualkey !== lowerCase) {
  53741. continue;
  53742. }
  53743. }
  53744. }
  53745. }
  53746. }
  53747. action._executeCurrent(evt);
  53748. }
  53749. }
  53750. };
  53751. /** @hidden */
  53752. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53753. var properties = propertyPath.split(".");
  53754. for (var index = 0; index < properties.length - 1; index++) {
  53755. target = target[properties[index]];
  53756. }
  53757. return target;
  53758. };
  53759. /** @hidden */
  53760. ActionManager.prototype._getProperty = function (propertyPath) {
  53761. var properties = propertyPath.split(".");
  53762. return properties[properties.length - 1];
  53763. };
  53764. /**
  53765. * Serialize this manager to a JSON object
  53766. * @param name defines the property name to store this manager
  53767. * @returns a JSON representation of this manager
  53768. */
  53769. ActionManager.prototype.serialize = function (name) {
  53770. var root = {
  53771. children: new Array(),
  53772. name: name,
  53773. type: 3,
  53774. properties: new Array() // Empty for root but required
  53775. };
  53776. for (var i = 0; i < this.actions.length; i++) {
  53777. var triggerObject = {
  53778. type: 0,
  53779. children: new Array(),
  53780. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53781. properties: new Array()
  53782. };
  53783. var triggerOptions = this.actions[i].triggerOptions;
  53784. if (triggerOptions && typeof triggerOptions !== "number") {
  53785. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53786. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53787. }
  53788. else {
  53789. var parameter = {};
  53790. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53791. if (triggerOptions.parameter.mesh) {
  53792. parameter._meshId = triggerOptions.parameter.mesh.id;
  53793. }
  53794. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53795. }
  53796. }
  53797. // Serialize child action, recursively
  53798. this.actions[i].serialize(triggerObject);
  53799. // Add serialized trigger
  53800. root.children.push(triggerObject);
  53801. }
  53802. return root;
  53803. };
  53804. /**
  53805. * Creates a new ActionManager from a JSON data
  53806. * @param parsedActions defines the JSON data to read from
  53807. * @param object defines the hosting mesh
  53808. * @param scene defines the hosting scene
  53809. */
  53810. ActionManager.Parse = function (parsedActions, object, scene) {
  53811. var actionManager = new ActionManager(scene);
  53812. if (object === null)
  53813. scene.actionManager = actionManager;
  53814. else
  53815. object.actionManager = actionManager;
  53816. // instanciate a new object
  53817. var instanciate = function (name, params) {
  53818. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53819. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53820. newInstance.constructor.apply(newInstance, params);
  53821. return newInstance;
  53822. };
  53823. var parseParameter = function (name, value, target, propertyPath) {
  53824. if (propertyPath === null) {
  53825. // String, boolean or float
  53826. var floatValue = parseFloat(value);
  53827. if (value === "true" || value === "false")
  53828. return value === "true";
  53829. else
  53830. return isNaN(floatValue) ? value : floatValue;
  53831. }
  53832. var effectiveTarget = propertyPath.split(".");
  53833. var values = value.split(",");
  53834. // Get effective Target
  53835. for (var i = 0; i < effectiveTarget.length; i++) {
  53836. target = target[effectiveTarget[i]];
  53837. }
  53838. // Return appropriate value with its type
  53839. if (typeof (target) === "boolean")
  53840. return values[0] === "true";
  53841. if (typeof (target) === "string")
  53842. return values[0];
  53843. // Parameters with multiple values such as Vector3 etc.
  53844. var split = new Array();
  53845. for (var i = 0; i < values.length; i++)
  53846. split.push(parseFloat(values[i]));
  53847. if (target instanceof BABYLON.Vector3)
  53848. return BABYLON.Vector3.FromArray(split);
  53849. if (target instanceof BABYLON.Vector4)
  53850. return BABYLON.Vector4.FromArray(split);
  53851. if (target instanceof BABYLON.Color3)
  53852. return BABYLON.Color3.FromArray(split);
  53853. if (target instanceof BABYLON.Color4)
  53854. return BABYLON.Color4.FromArray(split);
  53855. return parseFloat(values[0]);
  53856. };
  53857. // traverse graph per trigger
  53858. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53859. if (combineArray === void 0) { combineArray = null; }
  53860. if (parsedAction.detached)
  53861. return;
  53862. var parameters = new Array();
  53863. var target = null;
  53864. var propertyPath = null;
  53865. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53866. // Parameters
  53867. if (parsedAction.type === 2)
  53868. parameters.push(actionManager);
  53869. else
  53870. parameters.push(trigger);
  53871. if (combine) {
  53872. var actions = new Array();
  53873. for (var j = 0; j < parsedAction.combine.length; j++) {
  53874. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53875. }
  53876. parameters.push(actions);
  53877. }
  53878. else {
  53879. for (var i = 0; i < parsedAction.properties.length; i++) {
  53880. var value = parsedAction.properties[i].value;
  53881. var name = parsedAction.properties[i].name;
  53882. var targetType = parsedAction.properties[i].targetType;
  53883. if (name === "target")
  53884. if (targetType !== null && targetType === "SceneProperties")
  53885. value = target = scene;
  53886. else
  53887. value = target = scene.getNodeByName(value);
  53888. else if (name === "parent")
  53889. value = scene.getNodeByName(value);
  53890. else if (name === "sound") {
  53891. // Can not externalize to component, so only checks for the presence off the API.
  53892. if (scene.getSoundByName) {
  53893. value = scene.getSoundByName(value);
  53894. }
  53895. }
  53896. else if (name !== "propertyPath") {
  53897. if (parsedAction.type === 2 && name === "operator")
  53898. value = BABYLON.ValueCondition[value];
  53899. else
  53900. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53901. }
  53902. else {
  53903. propertyPath = value;
  53904. }
  53905. parameters.push(value);
  53906. }
  53907. }
  53908. if (combineArray === null) {
  53909. parameters.push(condition);
  53910. }
  53911. else {
  53912. parameters.push(null);
  53913. }
  53914. // If interpolate value action
  53915. if (parsedAction.name === "InterpolateValueAction") {
  53916. var param = parameters[parameters.length - 2];
  53917. parameters[parameters.length - 1] = param;
  53918. parameters[parameters.length - 2] = condition;
  53919. }
  53920. // Action or condition(s) and not CombineAction
  53921. var newAction = instanciate(parsedAction.name, parameters);
  53922. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53923. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53924. if (action)
  53925. action.then(nothing);
  53926. else
  53927. actionManager.registerAction(nothing);
  53928. action = nothing;
  53929. }
  53930. if (combineArray === null) {
  53931. if (newAction instanceof BABYLON.Condition) {
  53932. condition = newAction;
  53933. newAction = action;
  53934. }
  53935. else {
  53936. condition = null;
  53937. if (action)
  53938. action.then(newAction);
  53939. else
  53940. actionManager.registerAction(newAction);
  53941. }
  53942. }
  53943. else {
  53944. combineArray.push(newAction);
  53945. }
  53946. for (var i = 0; i < parsedAction.children.length; i++)
  53947. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53948. };
  53949. // triggers
  53950. for (var i = 0; i < parsedActions.children.length; i++) {
  53951. var triggerParams;
  53952. var trigger = parsedActions.children[i];
  53953. if (trigger.properties.length > 0) {
  53954. var param = trigger.properties[0].value;
  53955. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53956. if (value._meshId) {
  53957. value.mesh = scene.getMeshByID(value._meshId);
  53958. }
  53959. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53960. }
  53961. else
  53962. triggerParams = ActionManager[trigger.name];
  53963. for (var j = 0; j < trigger.children.length; j++) {
  53964. if (!trigger.detached)
  53965. traverse(trigger.children[j], triggerParams, null, null);
  53966. }
  53967. }
  53968. };
  53969. /**
  53970. * Get a trigger name by index
  53971. * @param trigger defines the trigger index
  53972. * @returns a trigger name
  53973. */
  53974. ActionManager.GetTriggerName = function (trigger) {
  53975. switch (trigger) {
  53976. case 0: return "NothingTrigger";
  53977. case 1: return "OnPickTrigger";
  53978. case 2: return "OnLeftPickTrigger";
  53979. case 3: return "OnRightPickTrigger";
  53980. case 4: return "OnCenterPickTrigger";
  53981. case 5: return "OnPickDownTrigger";
  53982. case 6: return "OnPickUpTrigger";
  53983. case 7: return "OnLongPressTrigger";
  53984. case 8: return "OnPointerOverTrigger";
  53985. case 9: return "OnPointerOutTrigger";
  53986. case 10: return "OnEveryFrameTrigger";
  53987. case 11: return "OnIntersectionEnterTrigger";
  53988. case 12: return "OnIntersectionExitTrigger";
  53989. case 13: return "OnKeyDownTrigger";
  53990. case 14: return "OnKeyUpTrigger";
  53991. case 15: return "OnPickOutTrigger";
  53992. default: return "";
  53993. }
  53994. };
  53995. /**
  53996. * Nothing
  53997. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53998. */
  53999. ActionManager.NothingTrigger = 0;
  54000. /**
  54001. * On pick
  54002. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54003. */
  54004. ActionManager.OnPickTrigger = 1;
  54005. /**
  54006. * On left pick
  54007. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54008. */
  54009. ActionManager.OnLeftPickTrigger = 2;
  54010. /**
  54011. * On right pick
  54012. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54013. */
  54014. ActionManager.OnRightPickTrigger = 3;
  54015. /**
  54016. * On center pick
  54017. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54018. */
  54019. ActionManager.OnCenterPickTrigger = 4;
  54020. /**
  54021. * On pick down
  54022. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54023. */
  54024. ActionManager.OnPickDownTrigger = 5;
  54025. /**
  54026. * On double pick
  54027. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54028. */
  54029. ActionManager.OnDoublePickTrigger = 6;
  54030. /**
  54031. * On pick up
  54032. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54033. */
  54034. ActionManager.OnPickUpTrigger = 7;
  54035. /**
  54036. * On pick out.
  54037. * This trigger will only be raised if you also declared a OnPickDown
  54038. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54039. */
  54040. ActionManager.OnPickOutTrigger = 16;
  54041. /**
  54042. * On long press
  54043. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54044. */
  54045. ActionManager.OnLongPressTrigger = 8;
  54046. /**
  54047. * On pointer over
  54048. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54049. */
  54050. ActionManager.OnPointerOverTrigger = 9;
  54051. /**
  54052. * On pointer out
  54053. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54054. */
  54055. ActionManager.OnPointerOutTrigger = 10;
  54056. /**
  54057. * On every frame
  54058. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54059. */
  54060. ActionManager.OnEveryFrameTrigger = 11;
  54061. /**
  54062. * On intersection enter
  54063. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54064. */
  54065. ActionManager.OnIntersectionEnterTrigger = 12;
  54066. /**
  54067. * On intersection exit
  54068. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54069. */
  54070. ActionManager.OnIntersectionExitTrigger = 13;
  54071. /**
  54072. * On key down
  54073. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54074. */
  54075. ActionManager.OnKeyDownTrigger = 14;
  54076. /**
  54077. * On key up
  54078. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54079. */
  54080. ActionManager.OnKeyUpTrigger = 15;
  54081. /** Gets the list of active triggers */
  54082. ActionManager.Triggers = {};
  54083. return ActionManager;
  54084. }());
  54085. BABYLON.ActionManager = ActionManager;
  54086. })(BABYLON || (BABYLON = {}));
  54087. //# sourceMappingURL=babylon.actionManager.js.map
  54088. var BABYLON;
  54089. (function (BABYLON) {
  54090. /**
  54091. * This defines an action responsible to change the value of a property
  54092. * by interpolating between its current value and the newly set one once triggered.
  54093. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54094. */
  54095. var InterpolateValueAction = /** @class */ (function (_super) {
  54096. __extends(InterpolateValueAction, _super);
  54097. /**
  54098. * Instantiate the action
  54099. * @param triggerOptions defines the trigger options
  54100. * @param target defines the object containing the value to interpolate
  54101. * @param propertyPath defines the path to the property in the target object
  54102. * @param value defines the target value at the end of the interpolation
  54103. * @param duration deines the time it will take for the property to interpolate to the value.
  54104. * @param condition defines the trigger related conditions
  54105. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54106. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54107. */
  54108. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54109. if (duration === void 0) { duration = 1000; }
  54110. var _this = _super.call(this, triggerOptions, condition) || this;
  54111. /**
  54112. * Defines the time it will take for the property to interpolate to the value.
  54113. */
  54114. _this.duration = 1000;
  54115. /**
  54116. * Observable triggered once the interpolation animation has been done.
  54117. */
  54118. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54119. _this.propertyPath = propertyPath;
  54120. _this.value = value;
  54121. _this.duration = duration;
  54122. _this.stopOtherAnimations = stopOtherAnimations;
  54123. _this.onInterpolationDone = onInterpolationDone;
  54124. _this._target = _this._effectiveTarget = target;
  54125. return _this;
  54126. }
  54127. /** @hidden */
  54128. InterpolateValueAction.prototype._prepare = function () {
  54129. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54130. this._property = this._getProperty(this.propertyPath);
  54131. };
  54132. /**
  54133. * Execute the action starts the value interpolation.
  54134. */
  54135. InterpolateValueAction.prototype.execute = function () {
  54136. var _this = this;
  54137. var scene = this._actionManager.getScene();
  54138. var keys = [
  54139. {
  54140. frame: 0,
  54141. value: this._effectiveTarget[this._property]
  54142. }, {
  54143. frame: 100,
  54144. value: this.value
  54145. }
  54146. ];
  54147. var dataType;
  54148. if (typeof this.value === "number") {
  54149. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54150. }
  54151. else if (this.value instanceof BABYLON.Color3) {
  54152. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54153. }
  54154. else if (this.value instanceof BABYLON.Vector3) {
  54155. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54156. }
  54157. else if (this.value instanceof BABYLON.Matrix) {
  54158. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54159. }
  54160. else if (this.value instanceof BABYLON.Quaternion) {
  54161. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54162. }
  54163. else {
  54164. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54165. return;
  54166. }
  54167. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54168. animation.setKeys(keys);
  54169. if (this.stopOtherAnimations) {
  54170. scene.stopAnimation(this._effectiveTarget);
  54171. }
  54172. var wrapper = function () {
  54173. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54174. if (_this.onInterpolationDone) {
  54175. _this.onInterpolationDone();
  54176. }
  54177. };
  54178. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54179. };
  54180. /**
  54181. * Serializes the actions and its related information.
  54182. * @param parent defines the object to serialize in
  54183. * @returns the serialized object
  54184. */
  54185. InterpolateValueAction.prototype.serialize = function (parent) {
  54186. return _super.prototype._serialize.call(this, {
  54187. name: "InterpolateValueAction",
  54188. properties: [
  54189. BABYLON.Action._GetTargetProperty(this._target),
  54190. { name: "propertyPath", value: this.propertyPath },
  54191. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54192. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54193. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54194. ]
  54195. }, parent);
  54196. };
  54197. return InterpolateValueAction;
  54198. }(BABYLON.Action));
  54199. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54200. })(BABYLON || (BABYLON = {}));
  54201. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54202. var BABYLON;
  54203. (function (BABYLON) {
  54204. /**
  54205. * This defines an action responsible to toggle a boolean once triggered.
  54206. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54207. */
  54208. var SwitchBooleanAction = /** @class */ (function (_super) {
  54209. __extends(SwitchBooleanAction, _super);
  54210. /**
  54211. * Instantiate the action
  54212. * @param triggerOptions defines the trigger options
  54213. * @param target defines the object containing the boolean
  54214. * @param propertyPath defines the path to the boolean property in the target object
  54215. * @param condition defines the trigger related conditions
  54216. */
  54217. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54218. var _this = _super.call(this, triggerOptions, condition) || this;
  54219. _this.propertyPath = propertyPath;
  54220. _this._target = _this._effectiveTarget = target;
  54221. return _this;
  54222. }
  54223. /** @hidden */
  54224. SwitchBooleanAction.prototype._prepare = function () {
  54225. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54226. this._property = this._getProperty(this.propertyPath);
  54227. };
  54228. /**
  54229. * Execute the action toggle the boolean value.
  54230. */
  54231. SwitchBooleanAction.prototype.execute = function () {
  54232. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54233. };
  54234. /**
  54235. * Serializes the actions and its related information.
  54236. * @param parent defines the object to serialize in
  54237. * @returns the serialized object
  54238. */
  54239. SwitchBooleanAction.prototype.serialize = function (parent) {
  54240. return _super.prototype._serialize.call(this, {
  54241. name: "SwitchBooleanAction",
  54242. properties: [
  54243. BABYLON.Action._GetTargetProperty(this._target),
  54244. { name: "propertyPath", value: this.propertyPath }
  54245. ]
  54246. }, parent);
  54247. };
  54248. return SwitchBooleanAction;
  54249. }(BABYLON.Action));
  54250. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54251. /**
  54252. * This defines an action responsible to set a the state field of the target
  54253. * to a desired value once triggered.
  54254. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54255. */
  54256. var SetStateAction = /** @class */ (function (_super) {
  54257. __extends(SetStateAction, _super);
  54258. /**
  54259. * Instantiate the action
  54260. * @param triggerOptions defines the trigger options
  54261. * @param target defines the object containing the state property
  54262. * @param value defines the value to store in the state field
  54263. * @param condition defines the trigger related conditions
  54264. */
  54265. function SetStateAction(triggerOptions, target, value, condition) {
  54266. var _this = _super.call(this, triggerOptions, condition) || this;
  54267. _this.value = value;
  54268. _this._target = target;
  54269. return _this;
  54270. }
  54271. /**
  54272. * Execute the action and store the value on the target state property.
  54273. */
  54274. SetStateAction.prototype.execute = function () {
  54275. this._target.state = this.value;
  54276. };
  54277. /**
  54278. * Serializes the actions and its related information.
  54279. * @param parent defines the object to serialize in
  54280. * @returns the serialized object
  54281. */
  54282. SetStateAction.prototype.serialize = function (parent) {
  54283. return _super.prototype._serialize.call(this, {
  54284. name: "SetStateAction",
  54285. properties: [
  54286. BABYLON.Action._GetTargetProperty(this._target),
  54287. { name: "value", value: this.value }
  54288. ]
  54289. }, parent);
  54290. };
  54291. return SetStateAction;
  54292. }(BABYLON.Action));
  54293. BABYLON.SetStateAction = SetStateAction;
  54294. /**
  54295. * This defines an action responsible to set a property of the target
  54296. * to a desired value once triggered.
  54297. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54298. */
  54299. var SetValueAction = /** @class */ (function (_super) {
  54300. __extends(SetValueAction, _super);
  54301. /**
  54302. * Instantiate the action
  54303. * @param triggerOptions defines the trigger options
  54304. * @param target defines the object containing the property
  54305. * @param propertyPath defines the path of the property to set in the target
  54306. * @param value defines the value to set in the property
  54307. * @param condition defines the trigger related conditions
  54308. */
  54309. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54310. var _this = _super.call(this, triggerOptions, condition) || this;
  54311. _this.propertyPath = propertyPath;
  54312. _this.value = value;
  54313. _this._target = _this._effectiveTarget = target;
  54314. return _this;
  54315. }
  54316. /** @hidden */
  54317. SetValueAction.prototype._prepare = function () {
  54318. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54319. this._property = this._getProperty(this.propertyPath);
  54320. };
  54321. /**
  54322. * Execute the action and set the targetted property to the desired value.
  54323. */
  54324. SetValueAction.prototype.execute = function () {
  54325. this._effectiveTarget[this._property] = this.value;
  54326. if (this._target.markAsDirty) {
  54327. this._target.markAsDirty(this._property);
  54328. }
  54329. };
  54330. /**
  54331. * Serializes the actions and its related information.
  54332. * @param parent defines the object to serialize in
  54333. * @returns the serialized object
  54334. */
  54335. SetValueAction.prototype.serialize = function (parent) {
  54336. return _super.prototype._serialize.call(this, {
  54337. name: "SetValueAction",
  54338. properties: [
  54339. BABYLON.Action._GetTargetProperty(this._target),
  54340. { name: "propertyPath", value: this.propertyPath },
  54341. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54342. ]
  54343. }, parent);
  54344. };
  54345. return SetValueAction;
  54346. }(BABYLON.Action));
  54347. BABYLON.SetValueAction = SetValueAction;
  54348. /**
  54349. * This defines an action responsible to increment the target value
  54350. * to a desired value once triggered.
  54351. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54352. */
  54353. var IncrementValueAction = /** @class */ (function (_super) {
  54354. __extends(IncrementValueAction, _super);
  54355. /**
  54356. * Instantiate the action
  54357. * @param triggerOptions defines the trigger options
  54358. * @param target defines the object containing the property
  54359. * @param propertyPath defines the path of the property to increment in the target
  54360. * @param value defines the value value we should increment the property by
  54361. * @param condition defines the trigger related conditions
  54362. */
  54363. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54364. var _this = _super.call(this, triggerOptions, condition) || this;
  54365. _this.propertyPath = propertyPath;
  54366. _this.value = value;
  54367. _this._target = _this._effectiveTarget = target;
  54368. return _this;
  54369. }
  54370. /** @hidden */
  54371. IncrementValueAction.prototype._prepare = function () {
  54372. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54373. this._property = this._getProperty(this.propertyPath);
  54374. if (typeof this._effectiveTarget[this._property] !== "number") {
  54375. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54376. }
  54377. };
  54378. /**
  54379. * Execute the action and increment the target of the value amount.
  54380. */
  54381. IncrementValueAction.prototype.execute = function () {
  54382. this._effectiveTarget[this._property] += this.value;
  54383. if (this._target.markAsDirty) {
  54384. this._target.markAsDirty(this._property);
  54385. }
  54386. };
  54387. /**
  54388. * Serializes the actions and its related information.
  54389. * @param parent defines the object to serialize in
  54390. * @returns the serialized object
  54391. */
  54392. IncrementValueAction.prototype.serialize = function (parent) {
  54393. return _super.prototype._serialize.call(this, {
  54394. name: "IncrementValueAction",
  54395. properties: [
  54396. BABYLON.Action._GetTargetProperty(this._target),
  54397. { name: "propertyPath", value: this.propertyPath },
  54398. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54399. ]
  54400. }, parent);
  54401. };
  54402. return IncrementValueAction;
  54403. }(BABYLON.Action));
  54404. BABYLON.IncrementValueAction = IncrementValueAction;
  54405. /**
  54406. * This defines an action responsible to start an animation once triggered.
  54407. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54408. */
  54409. var PlayAnimationAction = /** @class */ (function (_super) {
  54410. __extends(PlayAnimationAction, _super);
  54411. /**
  54412. * Instantiate the action
  54413. * @param triggerOptions defines the trigger options
  54414. * @param target defines the target animation or animation name
  54415. * @param from defines from where the animation should start (animation frame)
  54416. * @param end defines where the animation should stop (animation frame)
  54417. * @param loop defines if the animation should loop or stop after the first play
  54418. * @param condition defines the trigger related conditions
  54419. */
  54420. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54421. var _this = _super.call(this, triggerOptions, condition) || this;
  54422. _this.from = from;
  54423. _this.to = to;
  54424. _this.loop = loop;
  54425. _this._target = target;
  54426. return _this;
  54427. }
  54428. /** @hidden */
  54429. PlayAnimationAction.prototype._prepare = function () {
  54430. };
  54431. /**
  54432. * Execute the action and play the animation.
  54433. */
  54434. PlayAnimationAction.prototype.execute = function () {
  54435. var scene = this._actionManager.getScene();
  54436. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54437. };
  54438. /**
  54439. * Serializes the actions and its related information.
  54440. * @param parent defines the object to serialize in
  54441. * @returns the serialized object
  54442. */
  54443. PlayAnimationAction.prototype.serialize = function (parent) {
  54444. return _super.prototype._serialize.call(this, {
  54445. name: "PlayAnimationAction",
  54446. properties: [
  54447. BABYLON.Action._GetTargetProperty(this._target),
  54448. { name: "from", value: String(this.from) },
  54449. { name: "to", value: String(this.to) },
  54450. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54451. ]
  54452. }, parent);
  54453. };
  54454. return PlayAnimationAction;
  54455. }(BABYLON.Action));
  54456. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54457. /**
  54458. * This defines an action responsible to stop an animation once triggered.
  54459. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54460. */
  54461. var StopAnimationAction = /** @class */ (function (_super) {
  54462. __extends(StopAnimationAction, _super);
  54463. /**
  54464. * Instantiate the action
  54465. * @param triggerOptions defines the trigger options
  54466. * @param target defines the target animation or animation name
  54467. * @param condition defines the trigger related conditions
  54468. */
  54469. function StopAnimationAction(triggerOptions, target, condition) {
  54470. var _this = _super.call(this, triggerOptions, condition) || this;
  54471. _this._target = target;
  54472. return _this;
  54473. }
  54474. /** @hidden */
  54475. StopAnimationAction.prototype._prepare = function () {
  54476. };
  54477. /**
  54478. * Execute the action and stop the animation.
  54479. */
  54480. StopAnimationAction.prototype.execute = function () {
  54481. var scene = this._actionManager.getScene();
  54482. scene.stopAnimation(this._target);
  54483. };
  54484. /**
  54485. * Serializes the actions and its related information.
  54486. * @param parent defines the object to serialize in
  54487. * @returns the serialized object
  54488. */
  54489. StopAnimationAction.prototype.serialize = function (parent) {
  54490. return _super.prototype._serialize.call(this, {
  54491. name: "StopAnimationAction",
  54492. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54493. }, parent);
  54494. };
  54495. return StopAnimationAction;
  54496. }(BABYLON.Action));
  54497. BABYLON.StopAnimationAction = StopAnimationAction;
  54498. /**
  54499. * This defines an action responsible that does nothing once triggered.
  54500. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54501. */
  54502. var DoNothingAction = /** @class */ (function (_super) {
  54503. __extends(DoNothingAction, _super);
  54504. /**
  54505. * Instantiate the action
  54506. * @param triggerOptions defines the trigger options
  54507. * @param condition defines the trigger related conditions
  54508. */
  54509. function DoNothingAction(triggerOptions, condition) {
  54510. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54511. return _super.call(this, triggerOptions, condition) || this;
  54512. }
  54513. /**
  54514. * Execute the action and do nothing.
  54515. */
  54516. DoNothingAction.prototype.execute = function () {
  54517. };
  54518. /**
  54519. * Serializes the actions and its related information.
  54520. * @param parent defines the object to serialize in
  54521. * @returns the serialized object
  54522. */
  54523. DoNothingAction.prototype.serialize = function (parent) {
  54524. return _super.prototype._serialize.call(this, {
  54525. name: "DoNothingAction",
  54526. properties: []
  54527. }, parent);
  54528. };
  54529. return DoNothingAction;
  54530. }(BABYLON.Action));
  54531. BABYLON.DoNothingAction = DoNothingAction;
  54532. /**
  54533. * This defines an action responsible to trigger several actions once triggered.
  54534. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54535. */
  54536. var CombineAction = /** @class */ (function (_super) {
  54537. __extends(CombineAction, _super);
  54538. /**
  54539. * Instantiate the action
  54540. * @param triggerOptions defines the trigger options
  54541. * @param children defines the list of aggregated animations to run
  54542. * @param condition defines the trigger related conditions
  54543. */
  54544. function CombineAction(triggerOptions, children, condition) {
  54545. var _this = _super.call(this, triggerOptions, condition) || this;
  54546. _this.children = children;
  54547. return _this;
  54548. }
  54549. /** @hidden */
  54550. CombineAction.prototype._prepare = function () {
  54551. for (var index = 0; index < this.children.length; index++) {
  54552. this.children[index]._actionManager = this._actionManager;
  54553. this.children[index]._prepare();
  54554. }
  54555. };
  54556. /**
  54557. * Execute the action and executes all the aggregated actions.
  54558. */
  54559. CombineAction.prototype.execute = function (evt) {
  54560. for (var index = 0; index < this.children.length; index++) {
  54561. this.children[index].execute(evt);
  54562. }
  54563. };
  54564. /**
  54565. * Serializes the actions and its related information.
  54566. * @param parent defines the object to serialize in
  54567. * @returns the serialized object
  54568. */
  54569. CombineAction.prototype.serialize = function (parent) {
  54570. var serializationObject = _super.prototype._serialize.call(this, {
  54571. name: "CombineAction",
  54572. properties: [],
  54573. combine: []
  54574. }, parent);
  54575. for (var i = 0; i < this.children.length; i++) {
  54576. serializationObject.combine.push(this.children[i].serialize(null));
  54577. }
  54578. return serializationObject;
  54579. };
  54580. return CombineAction;
  54581. }(BABYLON.Action));
  54582. BABYLON.CombineAction = CombineAction;
  54583. /**
  54584. * This defines an action responsible to run code (external event) once triggered.
  54585. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54586. */
  54587. var ExecuteCodeAction = /** @class */ (function (_super) {
  54588. __extends(ExecuteCodeAction, _super);
  54589. /**
  54590. * Instantiate the action
  54591. * @param triggerOptions defines the trigger options
  54592. * @param func defines the callback function to run
  54593. * @param condition defines the trigger related conditions
  54594. */
  54595. function ExecuteCodeAction(triggerOptions, func, condition) {
  54596. var _this = _super.call(this, triggerOptions, condition) || this;
  54597. _this.func = func;
  54598. return _this;
  54599. }
  54600. /**
  54601. * Execute the action and run the attached code.
  54602. */
  54603. ExecuteCodeAction.prototype.execute = function (evt) {
  54604. this.func(evt);
  54605. };
  54606. return ExecuteCodeAction;
  54607. }(BABYLON.Action));
  54608. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54609. /**
  54610. * This defines an action responsible to set the parent property of the target once triggered.
  54611. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54612. */
  54613. var SetParentAction = /** @class */ (function (_super) {
  54614. __extends(SetParentAction, _super);
  54615. /**
  54616. * Instantiate the action
  54617. * @param triggerOptions defines the trigger options
  54618. * @param target defines the target containing the parent property
  54619. * @param parent defines from where the animation should start (animation frame)
  54620. * @param condition defines the trigger related conditions
  54621. */
  54622. function SetParentAction(triggerOptions, target, parent, condition) {
  54623. var _this = _super.call(this, triggerOptions, condition) || this;
  54624. _this._target = target;
  54625. _this._parent = parent;
  54626. return _this;
  54627. }
  54628. /** @hidden */
  54629. SetParentAction.prototype._prepare = function () {
  54630. };
  54631. /**
  54632. * Execute the action and set the parent property.
  54633. */
  54634. SetParentAction.prototype.execute = function () {
  54635. if (this._target.parent === this._parent) {
  54636. return;
  54637. }
  54638. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54639. invertParentWorldMatrix.invert();
  54640. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54641. this._target.parent = this._parent;
  54642. };
  54643. /**
  54644. * Serializes the actions and its related information.
  54645. * @param parent defines the object to serialize in
  54646. * @returns the serialized object
  54647. */
  54648. SetParentAction.prototype.serialize = function (parent) {
  54649. return _super.prototype._serialize.call(this, {
  54650. name: "SetParentAction",
  54651. properties: [
  54652. BABYLON.Action._GetTargetProperty(this._target),
  54653. BABYLON.Action._GetTargetProperty(this._parent),
  54654. ]
  54655. }, parent);
  54656. };
  54657. return SetParentAction;
  54658. }(BABYLON.Action));
  54659. BABYLON.SetParentAction = SetParentAction;
  54660. })(BABYLON || (BABYLON = {}));
  54661. //# sourceMappingURL=babylon.directActions.js.map
  54662. var BABYLON;
  54663. (function (BABYLON) {
  54664. var SpriteManager = /** @class */ (function () {
  54665. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54666. if (epsilon === void 0) { epsilon = 0.01; }
  54667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54668. this.name = name;
  54669. this.sprites = new Array();
  54670. this.renderingGroupId = 0;
  54671. this.layerMask = 0x0FFFFFFF;
  54672. this.fogEnabled = true;
  54673. this.isPickable = false;
  54674. /**
  54675. * An event triggered when the manager is disposed.
  54676. */
  54677. this.onDisposeObservable = new BABYLON.Observable();
  54678. this._vertexBuffers = {};
  54679. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  54680. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  54681. }
  54682. this._capacity = capacity;
  54683. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54684. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54685. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54686. if (cellSize.width && cellSize.height) {
  54687. this.cellWidth = cellSize.width;
  54688. this.cellHeight = cellSize.height;
  54689. }
  54690. else if (cellSize !== undefined) {
  54691. this.cellWidth = cellSize;
  54692. this.cellHeight = cellSize;
  54693. }
  54694. else {
  54695. return;
  54696. }
  54697. this._epsilon = epsilon;
  54698. this._scene = scene;
  54699. this._scene.spriteManagers.push(this);
  54700. var indices = [];
  54701. var index = 0;
  54702. for (var count = 0; count < capacity; count++) {
  54703. indices.push(index);
  54704. indices.push(index + 1);
  54705. indices.push(index + 2);
  54706. indices.push(index);
  54707. indices.push(index + 2);
  54708. indices.push(index + 3);
  54709. index += 4;
  54710. }
  54711. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54712. // VBO
  54713. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54714. this._vertexData = new Float32Array(capacity * 16 * 4);
  54715. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54716. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54717. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54718. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54719. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54720. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54721. this._vertexBuffers["options"] = options;
  54722. this._vertexBuffers["cellInfo"] = cellInfo;
  54723. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54724. // Effects
  54725. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54726. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54727. }
  54728. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54729. set: function (callback) {
  54730. if (this._onDisposeObserver) {
  54731. this.onDisposeObservable.remove(this._onDisposeObserver);
  54732. }
  54733. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54734. },
  54735. enumerable: true,
  54736. configurable: true
  54737. });
  54738. Object.defineProperty(SpriteManager.prototype, "texture", {
  54739. get: function () {
  54740. return this._spriteTexture;
  54741. },
  54742. set: function (value) {
  54743. this._spriteTexture = value;
  54744. },
  54745. enumerable: true,
  54746. configurable: true
  54747. });
  54748. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54749. var arrayOffset = index * 16;
  54750. if (offsetX === 0)
  54751. offsetX = this._epsilon;
  54752. else if (offsetX === 1)
  54753. offsetX = 1 - this._epsilon;
  54754. if (offsetY === 0)
  54755. offsetY = this._epsilon;
  54756. else if (offsetY === 1)
  54757. offsetY = 1 - this._epsilon;
  54758. this._vertexData[arrayOffset] = sprite.position.x;
  54759. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54760. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54761. this._vertexData[arrayOffset + 3] = sprite.angle;
  54762. this._vertexData[arrayOffset + 4] = sprite.width;
  54763. this._vertexData[arrayOffset + 5] = sprite.height;
  54764. this._vertexData[arrayOffset + 6] = offsetX;
  54765. this._vertexData[arrayOffset + 7] = offsetY;
  54766. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54767. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54768. var offset = (sprite.cellIndex / rowSize) >> 0;
  54769. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54770. this._vertexData[arrayOffset + 11] = offset;
  54771. // Color
  54772. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54773. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54774. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54775. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54776. };
  54777. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54778. var count = Math.min(this._capacity, this.sprites.length);
  54779. var min = BABYLON.Vector3.Zero();
  54780. var max = BABYLON.Vector3.Zero();
  54781. var distance = Number.MAX_VALUE;
  54782. var currentSprite = null;
  54783. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54784. var cameraView = camera.getViewMatrix();
  54785. for (var index = 0; index < count; index++) {
  54786. var sprite = this.sprites[index];
  54787. if (!sprite) {
  54788. continue;
  54789. }
  54790. if (predicate) {
  54791. if (!predicate(sprite)) {
  54792. continue;
  54793. }
  54794. }
  54795. else if (!sprite.isPickable) {
  54796. continue;
  54797. }
  54798. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54799. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54800. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54801. if (ray.intersectsBoxMinMax(min, max)) {
  54802. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54803. if (distance > currentDistance) {
  54804. distance = currentDistance;
  54805. currentSprite = sprite;
  54806. if (fastCheck) {
  54807. break;
  54808. }
  54809. }
  54810. }
  54811. }
  54812. if (currentSprite) {
  54813. var result = new BABYLON.PickingInfo();
  54814. result.hit = true;
  54815. result.pickedSprite = currentSprite;
  54816. result.distance = distance;
  54817. return result;
  54818. }
  54819. return null;
  54820. };
  54821. SpriteManager.prototype.render = function () {
  54822. // Check
  54823. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54824. return;
  54825. var engine = this._scene.getEngine();
  54826. var baseSize = this._spriteTexture.getBaseSize();
  54827. // Sprites
  54828. var deltaTime = engine.getDeltaTime();
  54829. var max = Math.min(this._capacity, this.sprites.length);
  54830. var rowSize = baseSize.width / this.cellWidth;
  54831. var offset = 0;
  54832. for (var index = 0; index < max; index++) {
  54833. var sprite = this.sprites[index];
  54834. if (!sprite || !sprite.isVisible) {
  54835. continue;
  54836. }
  54837. sprite._animate(deltaTime);
  54838. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54839. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54840. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54841. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54842. }
  54843. this._buffer.update(this._vertexData);
  54844. // Render
  54845. var effect = this._effectBase;
  54846. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54847. effect = this._effectFog;
  54848. }
  54849. engine.enableEffect(effect);
  54850. var viewMatrix = this._scene.getViewMatrix();
  54851. effect.setTexture("diffuseSampler", this._spriteTexture);
  54852. effect.setMatrix("view", viewMatrix);
  54853. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54854. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54855. // Fog
  54856. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54857. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54858. effect.setColor3("vFogColor", this._scene.fogColor);
  54859. }
  54860. // VBOs
  54861. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54862. // Draw order
  54863. engine.setDepthFunctionToLessOrEqual();
  54864. effect.setBool("alphaTest", true);
  54865. engine.setColorWrite(false);
  54866. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54867. engine.setColorWrite(true);
  54868. effect.setBool("alphaTest", false);
  54869. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54870. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54871. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54872. };
  54873. SpriteManager.prototype.dispose = function () {
  54874. if (this._buffer) {
  54875. this._buffer.dispose();
  54876. this._buffer = null;
  54877. }
  54878. if (this._indexBuffer) {
  54879. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54880. this._indexBuffer = null;
  54881. }
  54882. if (this._spriteTexture) {
  54883. this._spriteTexture.dispose();
  54884. this._spriteTexture = null;
  54885. }
  54886. // Remove from scene
  54887. var index = this._scene.spriteManagers.indexOf(this);
  54888. this._scene.spriteManagers.splice(index, 1);
  54889. // Callback
  54890. this.onDisposeObservable.notifyObservers(this);
  54891. this.onDisposeObservable.clear();
  54892. };
  54893. return SpriteManager;
  54894. }());
  54895. BABYLON.SpriteManager = SpriteManager;
  54896. })(BABYLON || (BABYLON = {}));
  54897. //# sourceMappingURL=babylon.spriteManager.js.map
  54898. var BABYLON;
  54899. (function (BABYLON) {
  54900. var Sprite = /** @class */ (function () {
  54901. function Sprite(name, manager) {
  54902. this.name = name;
  54903. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54904. this.width = 1.0;
  54905. this.height = 1.0;
  54906. this.angle = 0;
  54907. this.cellIndex = 0;
  54908. this.invertU = 0;
  54909. this.invertV = 0;
  54910. this.animations = new Array();
  54911. this.isPickable = false;
  54912. this._animationStarted = false;
  54913. this._loopAnimation = false;
  54914. this._fromIndex = 0;
  54915. this._toIndex = 0;
  54916. this._delay = 0;
  54917. this._direction = 1;
  54918. this._time = 0;
  54919. /**
  54920. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54921. */
  54922. this.isVisible = true;
  54923. this._manager = manager;
  54924. this._manager.sprites.push(this);
  54925. this.position = BABYLON.Vector3.Zero();
  54926. }
  54927. Object.defineProperty(Sprite.prototype, "size", {
  54928. get: function () {
  54929. return this.width;
  54930. },
  54931. set: function (value) {
  54932. this.width = value;
  54933. this.height = value;
  54934. },
  54935. enumerable: true,
  54936. configurable: true
  54937. });
  54938. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54939. this._fromIndex = from;
  54940. this._toIndex = to;
  54941. this._loopAnimation = loop;
  54942. this._delay = delay;
  54943. this._animationStarted = true;
  54944. this._direction = from < to ? 1 : -1;
  54945. this.cellIndex = from;
  54946. this._time = 0;
  54947. this._onAnimationEnd = onAnimationEnd;
  54948. };
  54949. Sprite.prototype.stopAnimation = function () {
  54950. this._animationStarted = false;
  54951. };
  54952. /** @hidden */
  54953. Sprite.prototype._animate = function (deltaTime) {
  54954. if (!this._animationStarted)
  54955. return;
  54956. this._time += deltaTime;
  54957. if (this._time > this._delay) {
  54958. this._time = this._time % this._delay;
  54959. this.cellIndex += this._direction;
  54960. if (this.cellIndex > this._toIndex) {
  54961. if (this._loopAnimation) {
  54962. this.cellIndex = this._fromIndex;
  54963. }
  54964. else {
  54965. this.cellIndex = this._toIndex;
  54966. this._animationStarted = false;
  54967. if (this._onAnimationEnd) {
  54968. this._onAnimationEnd();
  54969. }
  54970. if (this.disposeWhenFinishedAnimating) {
  54971. this.dispose();
  54972. }
  54973. }
  54974. }
  54975. }
  54976. };
  54977. Sprite.prototype.dispose = function () {
  54978. for (var i = 0; i < this._manager.sprites.length; i++) {
  54979. if (this._manager.sprites[i] == this) {
  54980. this._manager.sprites.splice(i, 1);
  54981. }
  54982. }
  54983. };
  54984. return Sprite;
  54985. }());
  54986. BABYLON.Sprite = Sprite;
  54987. })(BABYLON || (BABYLON = {}));
  54988. //# sourceMappingURL=babylon.sprite.js.map
  54989. var BABYLON;
  54990. (function (BABYLON) {
  54991. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54992. if (!BABYLON.PickingInfo) {
  54993. return null;
  54994. }
  54995. var pickingInfo = null;
  54996. if (!camera) {
  54997. if (!this.activeCamera) {
  54998. return null;
  54999. }
  55000. camera = this.activeCamera;
  55001. }
  55002. if (this.spriteManagers.length > 0) {
  55003. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55004. var spriteManager = this.spriteManagers[spriteIndex];
  55005. if (!spriteManager.isPickable) {
  55006. continue;
  55007. }
  55008. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55009. if (!result || !result.hit)
  55010. continue;
  55011. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55012. continue;
  55013. pickingInfo = result;
  55014. if (fastCheck) {
  55015. break;
  55016. }
  55017. }
  55018. }
  55019. return pickingInfo || new BABYLON.PickingInfo();
  55020. };
  55021. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55022. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55023. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55024. };
  55025. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55026. if (!this._tempSpritePickingRay) {
  55027. return null;
  55028. }
  55029. if (!camera) {
  55030. if (!this.activeCamera) {
  55031. return null;
  55032. }
  55033. camera = this.activeCamera;
  55034. }
  55035. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55036. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55037. };
  55038. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55039. if (this._pointerOverSprite === sprite) {
  55040. return;
  55041. }
  55042. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55043. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55044. }
  55045. this._pointerOverSprite = sprite;
  55046. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55047. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55048. }
  55049. };
  55050. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55051. return this._pointerOverSprite;
  55052. };
  55053. /**
  55054. * Defines the sprite scene component responsible to manage sprites
  55055. * in a given scene.
  55056. */
  55057. var SpriteSceneComponent = /** @class */ (function () {
  55058. /**
  55059. * Creates a new instance of the component for the given scene
  55060. * @param scene Defines the scene to register the component in
  55061. */
  55062. function SpriteSceneComponent(scene) {
  55063. /**
  55064. * The component name helpfull to identify the component in the list of scene components.
  55065. */
  55066. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55067. this.scene = scene;
  55068. this.scene.spriteManagers = new Array();
  55069. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55070. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55071. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55072. this._spritePredicate = function (sprite) {
  55073. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55074. };
  55075. }
  55076. /**
  55077. * Registers the component in a given scene
  55078. */
  55079. SpriteSceneComponent.prototype.register = function () {
  55080. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55081. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55082. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55083. };
  55084. /**
  55085. * Rebuilds the elements related to this component in case of
  55086. * context lost for instance.
  55087. */
  55088. SpriteSceneComponent.prototype.rebuild = function () {
  55089. /** Nothing to do for sprites */
  55090. };
  55091. /**
  55092. * Disposes the component and the associated ressources.
  55093. */
  55094. SpriteSceneComponent.prototype.dispose = function () {
  55095. this.scene.onBeforeSpritesRenderingObservable.clear();
  55096. this.scene.onAfterSpritesRenderingObservable.clear();
  55097. var spriteManagers = this.scene.spriteManagers;
  55098. while (spriteManagers.length) {
  55099. spriteManagers[0].dispose();
  55100. }
  55101. };
  55102. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55103. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55104. if (result) {
  55105. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55106. }
  55107. return result;
  55108. };
  55109. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55110. var scene = this.scene;
  55111. if (isMeshPicked) {
  55112. scene.setPointerOverSprite(null);
  55113. }
  55114. else {
  55115. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55116. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55117. scene.setPointerOverSprite(pickResult.pickedSprite);
  55118. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55119. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55120. }
  55121. else {
  55122. canvas.style.cursor = scene.hoverCursor;
  55123. }
  55124. }
  55125. else {
  55126. scene.setPointerOverSprite(null);
  55127. }
  55128. }
  55129. return pickResult;
  55130. };
  55131. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55132. var scene = this.scene;
  55133. scene._pickedDownSprite = null;
  55134. if (scene.spriteManagers.length > 0) {
  55135. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55136. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55137. if (pickResult.pickedSprite.actionManager) {
  55138. scene._pickedDownSprite = pickResult.pickedSprite;
  55139. switch (evt.button) {
  55140. case 0:
  55141. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55142. break;
  55143. case 1:
  55144. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55145. break;
  55146. case 2:
  55147. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55148. break;
  55149. }
  55150. if (pickResult.pickedSprite.actionManager) {
  55151. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55152. }
  55153. }
  55154. }
  55155. }
  55156. return pickResult;
  55157. };
  55158. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55159. var scene = this.scene;
  55160. if (scene.spriteManagers.length > 0) {
  55161. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55162. if (spritePickResult) {
  55163. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55164. if (spritePickResult.pickedSprite.actionManager) {
  55165. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55166. if (spritePickResult.pickedSprite.actionManager) {
  55167. if (!this.scene._isPointerSwiping()) {
  55168. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55169. }
  55170. }
  55171. }
  55172. }
  55173. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55174. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55175. }
  55176. }
  55177. }
  55178. return pickResult;
  55179. };
  55180. return SpriteSceneComponent;
  55181. }());
  55182. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55183. })(BABYLON || (BABYLON = {}));
  55184. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55185. var BABYLON;
  55186. (function (BABYLON) {
  55187. var IntersectionInfo = /** @class */ (function () {
  55188. function IntersectionInfo(bu, bv, distance) {
  55189. this.bu = bu;
  55190. this.bv = bv;
  55191. this.distance = distance;
  55192. this.faceId = 0;
  55193. this.subMeshId = 0;
  55194. }
  55195. return IntersectionInfo;
  55196. }());
  55197. BABYLON.IntersectionInfo = IntersectionInfo;
  55198. /**
  55199. * Information about the result of picking within a scene
  55200. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55201. */
  55202. var PickingInfo = /** @class */ (function () {
  55203. function PickingInfo() {
  55204. /**
  55205. * If the pick collided with an object
  55206. */
  55207. this.hit = false;
  55208. /**
  55209. * Distance away where the pick collided
  55210. */
  55211. this.distance = 0;
  55212. /**
  55213. * The location of pick collision
  55214. */
  55215. this.pickedPoint = null;
  55216. /**
  55217. * The mesh corresponding the the pick collision
  55218. */
  55219. this.pickedMesh = null;
  55220. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55221. this.bu = 0;
  55222. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55223. this.bv = 0;
  55224. /** The id of the face on the mesh that was picked */
  55225. this.faceId = -1;
  55226. /** Id of the the submesh that was picked */
  55227. this.subMeshId = 0;
  55228. /** If a sprite was picked, this will be the sprite the pick collided with */
  55229. this.pickedSprite = null;
  55230. /**
  55231. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55232. */
  55233. this.originMesh = null;
  55234. /**
  55235. * The ray that was used to perform the picking.
  55236. */
  55237. this.ray = null;
  55238. }
  55239. /**
  55240. * Gets the normal correspodning to the face the pick collided with
  55241. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55242. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55243. * @returns The normal correspodning to the face the pick collided with
  55244. */
  55245. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55246. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55247. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55248. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55249. return null;
  55250. }
  55251. var indices = this.pickedMesh.getIndices();
  55252. if (!indices) {
  55253. return null;
  55254. }
  55255. var result;
  55256. if (useVerticesNormals) {
  55257. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55258. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55259. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55260. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55261. normal0 = normal0.scale(this.bu);
  55262. normal1 = normal1.scale(this.bv);
  55263. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55264. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55265. }
  55266. else {
  55267. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55268. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55269. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55270. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55271. var p1p2 = vertex1.subtract(vertex2);
  55272. var p3p2 = vertex3.subtract(vertex2);
  55273. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55274. }
  55275. if (useWorldCoordinates) {
  55276. var wm = this.pickedMesh.getWorldMatrix();
  55277. if (this.pickedMesh.nonUniformScaling) {
  55278. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55279. wm = BABYLON.Tmp.Matrix[0];
  55280. wm.setTranslationFromFloats(0, 0, 0);
  55281. wm.invert();
  55282. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55283. wm = BABYLON.Tmp.Matrix[1];
  55284. }
  55285. result = BABYLON.Vector3.TransformNormal(result, wm);
  55286. }
  55287. result.normalize();
  55288. return result;
  55289. };
  55290. /**
  55291. * Gets the texture coordinates of where the pick occured
  55292. * @returns the vector containing the coordnates of the texture
  55293. */
  55294. PickingInfo.prototype.getTextureCoordinates = function () {
  55295. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55296. return null;
  55297. }
  55298. var indices = this.pickedMesh.getIndices();
  55299. if (!indices) {
  55300. return null;
  55301. }
  55302. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55303. if (!uvs) {
  55304. return null;
  55305. }
  55306. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55307. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55308. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55309. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55310. uv1 = uv1.scale(this.bu);
  55311. uv2 = uv2.scale(this.bv);
  55312. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55313. };
  55314. return PickingInfo;
  55315. }());
  55316. BABYLON.PickingInfo = PickingInfo;
  55317. })(BABYLON || (BABYLON = {}));
  55318. //# sourceMappingURL=babylon.pickingInfo.js.map
  55319. var BABYLON;
  55320. (function (BABYLON) {
  55321. var Ray = /** @class */ (function () {
  55322. function Ray(origin, direction, length) {
  55323. if (length === void 0) { length = Number.MAX_VALUE; }
  55324. this.origin = origin;
  55325. this.direction = direction;
  55326. this.length = length;
  55327. }
  55328. // Methods
  55329. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55330. var d = 0.0;
  55331. var maxValue = Number.MAX_VALUE;
  55332. var inv;
  55333. var min;
  55334. var max;
  55335. var temp;
  55336. if (Math.abs(this.direction.x) < 0.0000001) {
  55337. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55338. return false;
  55339. }
  55340. }
  55341. else {
  55342. inv = 1.0 / this.direction.x;
  55343. min = (minimum.x - this.origin.x) * inv;
  55344. max = (maximum.x - this.origin.x) * inv;
  55345. if (max === -Infinity) {
  55346. max = Infinity;
  55347. }
  55348. if (min > max) {
  55349. temp = min;
  55350. min = max;
  55351. max = temp;
  55352. }
  55353. d = Math.max(min, d);
  55354. maxValue = Math.min(max, maxValue);
  55355. if (d > maxValue) {
  55356. return false;
  55357. }
  55358. }
  55359. if (Math.abs(this.direction.y) < 0.0000001) {
  55360. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55361. return false;
  55362. }
  55363. }
  55364. else {
  55365. inv = 1.0 / this.direction.y;
  55366. min = (minimum.y - this.origin.y) * inv;
  55367. max = (maximum.y - this.origin.y) * inv;
  55368. if (max === -Infinity) {
  55369. max = Infinity;
  55370. }
  55371. if (min > max) {
  55372. temp = min;
  55373. min = max;
  55374. max = temp;
  55375. }
  55376. d = Math.max(min, d);
  55377. maxValue = Math.min(max, maxValue);
  55378. if (d > maxValue) {
  55379. return false;
  55380. }
  55381. }
  55382. if (Math.abs(this.direction.z) < 0.0000001) {
  55383. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55384. return false;
  55385. }
  55386. }
  55387. else {
  55388. inv = 1.0 / this.direction.z;
  55389. min = (minimum.z - this.origin.z) * inv;
  55390. max = (maximum.z - this.origin.z) * inv;
  55391. if (max === -Infinity) {
  55392. max = Infinity;
  55393. }
  55394. if (min > max) {
  55395. temp = min;
  55396. min = max;
  55397. max = temp;
  55398. }
  55399. d = Math.max(min, d);
  55400. maxValue = Math.min(max, maxValue);
  55401. if (d > maxValue) {
  55402. return false;
  55403. }
  55404. }
  55405. return true;
  55406. };
  55407. Ray.prototype.intersectsBox = function (box) {
  55408. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55409. };
  55410. Ray.prototype.intersectsSphere = function (sphere) {
  55411. var x = sphere.center.x - this.origin.x;
  55412. var y = sphere.center.y - this.origin.y;
  55413. var z = sphere.center.z - this.origin.z;
  55414. var pyth = (x * x) + (y * y) + (z * z);
  55415. var rr = sphere.radius * sphere.radius;
  55416. if (pyth <= rr) {
  55417. return true;
  55418. }
  55419. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55420. if (dot < 0.0) {
  55421. return false;
  55422. }
  55423. var temp = pyth - (dot * dot);
  55424. return temp <= rr;
  55425. };
  55426. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55427. if (!this._edge1) {
  55428. this._edge1 = BABYLON.Vector3.Zero();
  55429. this._edge2 = BABYLON.Vector3.Zero();
  55430. this._pvec = BABYLON.Vector3.Zero();
  55431. this._tvec = BABYLON.Vector3.Zero();
  55432. this._qvec = BABYLON.Vector3.Zero();
  55433. }
  55434. vertex1.subtractToRef(vertex0, this._edge1);
  55435. vertex2.subtractToRef(vertex0, this._edge2);
  55436. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55437. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55438. if (det === 0) {
  55439. return null;
  55440. }
  55441. var invdet = 1 / det;
  55442. this.origin.subtractToRef(vertex0, this._tvec);
  55443. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55444. if (bu < 0 || bu > 1.0) {
  55445. return null;
  55446. }
  55447. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55448. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55449. if (bv < 0 || bu + bv > 1.0) {
  55450. return null;
  55451. }
  55452. //check if the distance is longer than the predefined length.
  55453. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55454. if (distance > this.length) {
  55455. return null;
  55456. }
  55457. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55458. };
  55459. Ray.prototype.intersectsPlane = function (plane) {
  55460. var distance;
  55461. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55462. if (Math.abs(result1) < 9.99999997475243E-07) {
  55463. return null;
  55464. }
  55465. else {
  55466. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55467. distance = (-plane.d - result2) / result1;
  55468. if (distance < 0.0) {
  55469. if (distance < -9.99999997475243E-07) {
  55470. return null;
  55471. }
  55472. else {
  55473. return 0;
  55474. }
  55475. }
  55476. return distance;
  55477. }
  55478. };
  55479. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55480. var tm = BABYLON.Tmp.Matrix[0];
  55481. mesh.getWorldMatrix().invertToRef(tm);
  55482. if (this._tmpRay) {
  55483. Ray.TransformToRef(this, tm, this._tmpRay);
  55484. }
  55485. else {
  55486. this._tmpRay = Ray.Transform(this, tm);
  55487. }
  55488. return mesh.intersects(this._tmpRay, fastCheck);
  55489. };
  55490. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55491. if (results) {
  55492. results.length = 0;
  55493. }
  55494. else {
  55495. results = [];
  55496. }
  55497. for (var i = 0; i < meshes.length; i++) {
  55498. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55499. if (pickInfo.hit) {
  55500. results.push(pickInfo);
  55501. }
  55502. }
  55503. results.sort(this._comparePickingInfo);
  55504. return results;
  55505. };
  55506. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55507. if (pickingInfoA.distance < pickingInfoB.distance) {
  55508. return -1;
  55509. }
  55510. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55511. return 1;
  55512. }
  55513. else {
  55514. return 0;
  55515. }
  55516. };
  55517. /**
  55518. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55519. * @param sega the first point of the segment to test the intersection against
  55520. * @param segb the second point of the segment to test the intersection against
  55521. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55522. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55523. */
  55524. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55525. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55526. var u = segb.subtract(sega);
  55527. var v = rsegb.subtract(this.origin);
  55528. var w = sega.subtract(this.origin);
  55529. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55530. var b = BABYLON.Vector3.Dot(u, v);
  55531. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55532. var d = BABYLON.Vector3.Dot(u, w);
  55533. var e = BABYLON.Vector3.Dot(v, w);
  55534. var D = a * c - b * b; // always >= 0
  55535. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55536. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55537. // compute the line parameters of the two closest points
  55538. if (D < Ray.smallnum) { // the lines are almost parallel
  55539. sN = 0.0; // force using point P0 on segment S1
  55540. sD = 1.0; // to prevent possible division by 0.0 later
  55541. tN = e;
  55542. tD = c;
  55543. }
  55544. else { // get the closest points on the infinite lines
  55545. sN = (b * e - c * d);
  55546. tN = (a * e - b * d);
  55547. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55548. sN = 0.0;
  55549. tN = e;
  55550. tD = c;
  55551. }
  55552. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55553. sN = sD;
  55554. tN = e + b;
  55555. tD = c;
  55556. }
  55557. }
  55558. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55559. tN = 0.0;
  55560. // recompute sc for this edge
  55561. if (-d < 0.0) {
  55562. sN = 0.0;
  55563. }
  55564. else if (-d > a)
  55565. sN = sD;
  55566. else {
  55567. sN = -d;
  55568. sD = a;
  55569. }
  55570. }
  55571. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55572. tN = tD;
  55573. // recompute sc for this edge
  55574. if ((-d + b) < 0.0) {
  55575. sN = 0;
  55576. }
  55577. else if ((-d + b) > a) {
  55578. sN = sD;
  55579. }
  55580. else {
  55581. sN = (-d + b);
  55582. sD = a;
  55583. }
  55584. }
  55585. // finally do the division to get sc and tc
  55586. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55587. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55588. // get the difference of the two closest points
  55589. var qtc = v.multiplyByFloats(tc, tc, tc);
  55590. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55591. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55592. if (isIntersected) {
  55593. return qtc.length();
  55594. }
  55595. return -1;
  55596. };
  55597. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55598. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55599. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55600. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55601. this.direction.normalize();
  55602. return this;
  55603. };
  55604. // Statics
  55605. Ray.Zero = function () {
  55606. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55607. };
  55608. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55609. var result = Ray.Zero();
  55610. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55611. };
  55612. /**
  55613. * 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
  55614. * transformed to the given world matrix.
  55615. * @param origin The origin point
  55616. * @param end The end point
  55617. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55618. */
  55619. Ray.CreateNewFromTo = function (origin, end, world) {
  55620. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55621. var direction = end.subtract(origin);
  55622. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55623. direction.normalize();
  55624. return Ray.Transform(new Ray(origin, direction, length), world);
  55625. };
  55626. Ray.Transform = function (ray, matrix) {
  55627. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55628. Ray.TransformToRef(ray, matrix, result);
  55629. return result;
  55630. };
  55631. Ray.TransformToRef = function (ray, matrix, result) {
  55632. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55633. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55634. result.length = ray.length;
  55635. var dir = result.direction;
  55636. var len = dir.length();
  55637. if (!(len === 0 || len === 1)) {
  55638. var num = 1.0 / len;
  55639. dir.x *= num;
  55640. dir.y *= num;
  55641. dir.z *= num;
  55642. result.length *= len;
  55643. }
  55644. };
  55645. Ray.smallnum = 0.00000001;
  55646. Ray.rayl = 10e8;
  55647. return Ray;
  55648. }());
  55649. BABYLON.Ray = Ray;
  55650. })(BABYLON || (BABYLON = {}));
  55651. //# sourceMappingURL=babylon.ray.js.map
  55652. var BABYLON;
  55653. (function (BABYLON) {
  55654. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55655. if (boxMin.x > sphereCenter.x + sphereRadius)
  55656. return false;
  55657. if (sphereCenter.x - sphereRadius > boxMax.x)
  55658. return false;
  55659. if (boxMin.y > sphereCenter.y + sphereRadius)
  55660. return false;
  55661. if (sphereCenter.y - sphereRadius > boxMax.y)
  55662. return false;
  55663. if (boxMin.z > sphereCenter.z + sphereRadius)
  55664. return false;
  55665. if (sphereCenter.z - sphereRadius > boxMax.z)
  55666. return false;
  55667. return true;
  55668. };
  55669. var getLowestRoot = (function () {
  55670. var result = { root: 0, found: false };
  55671. return function (a, b, c, maxR) {
  55672. result.root = 0;
  55673. result.found = false;
  55674. var determinant = b * b - 4.0 * a * c;
  55675. if (determinant < 0)
  55676. return result;
  55677. var sqrtD = Math.sqrt(determinant);
  55678. var r1 = (-b - sqrtD) / (2.0 * a);
  55679. var r2 = (-b + sqrtD) / (2.0 * a);
  55680. if (r1 > r2) {
  55681. var temp = r2;
  55682. r2 = r1;
  55683. r1 = temp;
  55684. }
  55685. if (r1 > 0 && r1 < maxR) {
  55686. result.root = r1;
  55687. result.found = true;
  55688. return result;
  55689. }
  55690. if (r2 > 0 && r2 < maxR) {
  55691. result.root = r2;
  55692. result.found = true;
  55693. return result;
  55694. }
  55695. return result;
  55696. };
  55697. })();
  55698. /** @hidden */
  55699. var Collider = /** @class */ (function () {
  55700. function Collider() {
  55701. this._collisionPoint = BABYLON.Vector3.Zero();
  55702. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55703. this._tempVector = BABYLON.Vector3.Zero();
  55704. this._tempVector2 = BABYLON.Vector3.Zero();
  55705. this._tempVector3 = BABYLON.Vector3.Zero();
  55706. this._tempVector4 = BABYLON.Vector3.Zero();
  55707. this._edge = BABYLON.Vector3.Zero();
  55708. this._baseToVertex = BABYLON.Vector3.Zero();
  55709. this._destinationPoint = BABYLON.Vector3.Zero();
  55710. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55711. this._displacementVector = BABYLON.Vector3.Zero();
  55712. /** @hidden */
  55713. this._radius = BABYLON.Vector3.One();
  55714. /** @hidden */
  55715. this._retry = 0;
  55716. /** @hidden */
  55717. this._basePointWorld = BABYLON.Vector3.Zero();
  55718. this._velocityWorld = BABYLON.Vector3.Zero();
  55719. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55720. this._collisionMask = -1;
  55721. }
  55722. Object.defineProperty(Collider.prototype, "collisionMask", {
  55723. get: function () {
  55724. return this._collisionMask;
  55725. },
  55726. set: function (mask) {
  55727. this._collisionMask = !isNaN(mask) ? mask : -1;
  55728. },
  55729. enumerable: true,
  55730. configurable: true
  55731. });
  55732. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55733. /**
  55734. * Gets the plane normal used to compute the sliding response (in local space)
  55735. */
  55736. get: function () {
  55737. return this._slidePlaneNormal;
  55738. },
  55739. enumerable: true,
  55740. configurable: true
  55741. });
  55742. // Methods
  55743. /** @hidden */
  55744. Collider.prototype._initialize = function (source, dir, e) {
  55745. this._velocity = dir;
  55746. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55747. this._basePoint = source;
  55748. source.multiplyToRef(this._radius, this._basePointWorld);
  55749. dir.multiplyToRef(this._radius, this._velocityWorld);
  55750. this._velocityWorldLength = this._velocityWorld.length();
  55751. this._epsilon = e;
  55752. this.collisionFound = false;
  55753. };
  55754. /** @hidden */
  55755. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55756. pa.subtractToRef(point, this._tempVector);
  55757. pb.subtractToRef(point, this._tempVector2);
  55758. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55759. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55760. if (d < 0)
  55761. return false;
  55762. pc.subtractToRef(point, this._tempVector3);
  55763. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55764. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55765. if (d < 0)
  55766. return false;
  55767. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55768. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55769. return d >= 0;
  55770. };
  55771. /** @hidden */
  55772. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55773. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55774. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55775. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55776. return false;
  55777. }
  55778. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55779. return false;
  55780. return true;
  55781. };
  55782. /** @hidden */
  55783. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55784. var t0;
  55785. var embeddedInPlane = false;
  55786. //defensive programming, actually not needed.
  55787. if (!trianglePlaneArray) {
  55788. trianglePlaneArray = [];
  55789. }
  55790. if (!trianglePlaneArray[faceIndex]) {
  55791. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55792. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55793. }
  55794. var trianglePlane = trianglePlaneArray[faceIndex];
  55795. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55796. return;
  55797. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55798. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55799. if (normalDotVelocity == 0) {
  55800. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55801. return;
  55802. embeddedInPlane = true;
  55803. t0 = 0;
  55804. }
  55805. else {
  55806. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55807. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55808. if (t0 > t1) {
  55809. var temp = t1;
  55810. t1 = t0;
  55811. t0 = temp;
  55812. }
  55813. if (t0 > 1.0 || t1 < 0.0)
  55814. return;
  55815. if (t0 < 0)
  55816. t0 = 0;
  55817. if (t0 > 1.0)
  55818. t0 = 1.0;
  55819. }
  55820. this._collisionPoint.copyFromFloats(0, 0, 0);
  55821. var found = false;
  55822. var t = 1.0;
  55823. if (!embeddedInPlane) {
  55824. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55825. this._velocity.scaleToRef(t0, this._tempVector);
  55826. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55827. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55828. found = true;
  55829. t = t0;
  55830. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55831. }
  55832. }
  55833. if (!found) {
  55834. var velocitySquaredLength = this._velocity.lengthSquared();
  55835. var a = velocitySquaredLength;
  55836. this._basePoint.subtractToRef(p1, this._tempVector);
  55837. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55838. var c = this._tempVector.lengthSquared() - 1.0;
  55839. var lowestRoot = getLowestRoot(a, b, c, t);
  55840. if (lowestRoot.found) {
  55841. t = lowestRoot.root;
  55842. found = true;
  55843. this._collisionPoint.copyFrom(p1);
  55844. }
  55845. this._basePoint.subtractToRef(p2, this._tempVector);
  55846. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55847. c = this._tempVector.lengthSquared() - 1.0;
  55848. lowestRoot = getLowestRoot(a, b, c, t);
  55849. if (lowestRoot.found) {
  55850. t = lowestRoot.root;
  55851. found = true;
  55852. this._collisionPoint.copyFrom(p2);
  55853. }
  55854. this._basePoint.subtractToRef(p3, this._tempVector);
  55855. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55856. c = this._tempVector.lengthSquared() - 1.0;
  55857. lowestRoot = getLowestRoot(a, b, c, t);
  55858. if (lowestRoot.found) {
  55859. t = lowestRoot.root;
  55860. found = true;
  55861. this._collisionPoint.copyFrom(p3);
  55862. }
  55863. p2.subtractToRef(p1, this._edge);
  55864. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55865. var edgeSquaredLength = this._edge.lengthSquared();
  55866. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55867. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55868. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55869. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55870. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55871. lowestRoot = getLowestRoot(a, b, c, t);
  55872. if (lowestRoot.found) {
  55873. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55874. if (f >= 0.0 && f <= 1.0) {
  55875. t = lowestRoot.root;
  55876. found = true;
  55877. this._edge.scaleInPlace(f);
  55878. p1.addToRef(this._edge, this._collisionPoint);
  55879. }
  55880. }
  55881. p3.subtractToRef(p2, this._edge);
  55882. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55883. edgeSquaredLength = this._edge.lengthSquared();
  55884. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55885. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55886. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55887. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55888. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55889. lowestRoot = getLowestRoot(a, b, c, t);
  55890. if (lowestRoot.found) {
  55891. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55892. if (f >= 0.0 && f <= 1.0) {
  55893. t = lowestRoot.root;
  55894. found = true;
  55895. this._edge.scaleInPlace(f);
  55896. p2.addToRef(this._edge, this._collisionPoint);
  55897. }
  55898. }
  55899. p1.subtractToRef(p3, this._edge);
  55900. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55901. edgeSquaredLength = this._edge.lengthSquared();
  55902. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55903. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55904. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55905. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55906. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55907. lowestRoot = getLowestRoot(a, b, c, t);
  55908. if (lowestRoot.found) {
  55909. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55910. if (f >= 0.0 && f <= 1.0) {
  55911. t = lowestRoot.root;
  55912. found = true;
  55913. this._edge.scaleInPlace(f);
  55914. p3.addToRef(this._edge, this._collisionPoint);
  55915. }
  55916. }
  55917. }
  55918. if (found) {
  55919. var distToCollision = t * this._velocity.length();
  55920. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55921. if (!this.intersectionPoint) {
  55922. this.intersectionPoint = this._collisionPoint.clone();
  55923. }
  55924. else {
  55925. this.intersectionPoint.copyFrom(this._collisionPoint);
  55926. }
  55927. this._nearestDistance = distToCollision;
  55928. this.collisionFound = true;
  55929. }
  55930. }
  55931. };
  55932. /** @hidden */
  55933. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55934. for (var i = indexStart; i < indexEnd; i += 3) {
  55935. var p1 = pts[indices[i] - decal];
  55936. var p2 = pts[indices[i + 1] - decal];
  55937. var p3 = pts[indices[i + 2] - decal];
  55938. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55939. }
  55940. };
  55941. /** @hidden */
  55942. Collider.prototype._getResponse = function (pos, vel) {
  55943. pos.addToRef(vel, this._destinationPoint);
  55944. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55945. this._basePoint.addToRef(vel, pos);
  55946. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55947. this._slidePlaneNormal.normalize();
  55948. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55949. pos.addInPlace(this._displacementVector);
  55950. this.intersectionPoint.addInPlace(this._displacementVector);
  55951. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55952. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55953. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55954. };
  55955. return Collider;
  55956. }());
  55957. BABYLON.Collider = Collider;
  55958. })(BABYLON || (BABYLON = {}));
  55959. //# sourceMappingURL=babylon.collider.js.map
  55960. var BABYLON;
  55961. (function (BABYLON) {
  55962. //WebWorker code will be inserted to this variable.
  55963. /** @hidden */
  55964. BABYLON.CollisionWorker = "";
  55965. /** Defines supported task for worker process */
  55966. var WorkerTaskType;
  55967. (function (WorkerTaskType) {
  55968. /** Initialization */
  55969. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55970. /** Update of geometry */
  55971. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55972. /** Evaluate collision */
  55973. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55974. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55975. /** Defines kind of replies returned by worker */
  55976. var WorkerReplyType;
  55977. (function (WorkerReplyType) {
  55978. /** Success */
  55979. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55980. /** Unkown error */
  55981. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55982. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55983. /** @hidden */
  55984. var CollisionCoordinatorWorker = /** @class */ (function () {
  55985. function CollisionCoordinatorWorker() {
  55986. var _this = this;
  55987. this._scaledPosition = BABYLON.Vector3.Zero();
  55988. this._scaledVelocity = BABYLON.Vector3.Zero();
  55989. this.onMeshUpdated = function (transformNode) {
  55990. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55991. };
  55992. this.onGeometryUpdated = function (geometry) {
  55993. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55994. };
  55995. this._afterRender = function () {
  55996. if (!_this._init)
  55997. return;
  55998. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55999. return;
  56000. }
  56001. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56002. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56003. if (_this._runningUpdated > 4) {
  56004. return;
  56005. }
  56006. ++_this._runningUpdated;
  56007. var payload = {
  56008. updatedMeshes: _this._addUpdateMeshesList,
  56009. updatedGeometries: _this._addUpdateGeometriesList,
  56010. removedGeometries: _this._toRemoveGeometryArray,
  56011. removedMeshes: _this._toRemoveMeshesArray
  56012. };
  56013. var message = {
  56014. payload: payload,
  56015. taskType: WorkerTaskType.UPDATE
  56016. };
  56017. var serializable = [];
  56018. for (var id in payload.updatedGeometries) {
  56019. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56020. //prepare transferables
  56021. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56022. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56023. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56024. }
  56025. }
  56026. _this._worker.postMessage(message, serializable);
  56027. _this._addUpdateMeshesList = {};
  56028. _this._addUpdateGeometriesList = {};
  56029. _this._toRemoveGeometryArray = [];
  56030. _this._toRemoveMeshesArray = [];
  56031. };
  56032. this._onMessageFromWorker = function (e) {
  56033. var returnData = e.data;
  56034. if (returnData.error != WorkerReplyType.SUCCESS) {
  56035. //TODO what errors can be returned from the worker?
  56036. BABYLON.Tools.Warn("error returned from worker!");
  56037. return;
  56038. }
  56039. switch (returnData.taskType) {
  56040. case WorkerTaskType.INIT:
  56041. _this._init = true;
  56042. //Update the worked with ALL of the scene's current state
  56043. _this._scene.meshes.forEach(function (mesh) {
  56044. _this.onMeshAdded(mesh);
  56045. });
  56046. _this._scene.getGeometries().forEach(function (geometry) {
  56047. _this.onGeometryAdded(geometry);
  56048. });
  56049. break;
  56050. case WorkerTaskType.UPDATE:
  56051. _this._runningUpdated--;
  56052. break;
  56053. case WorkerTaskType.COLLIDE:
  56054. var returnPayload = returnData.payload;
  56055. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56056. return;
  56057. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56058. if (callback) {
  56059. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56060. if (mesh) {
  56061. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56062. }
  56063. }
  56064. //cleanup
  56065. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56066. break;
  56067. }
  56068. };
  56069. this._collisionsCallbackArray = [];
  56070. this._init = false;
  56071. this._runningUpdated = 0;
  56072. this._addUpdateMeshesList = {};
  56073. this._addUpdateGeometriesList = {};
  56074. this._toRemoveGeometryArray = [];
  56075. this._toRemoveMeshesArray = [];
  56076. }
  56077. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56078. if (!this._init)
  56079. return;
  56080. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56081. return;
  56082. position.divideToRef(collider._radius, this._scaledPosition);
  56083. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56084. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56085. var payload = {
  56086. collider: {
  56087. position: this._scaledPosition.asArray(),
  56088. velocity: this._scaledVelocity.asArray(),
  56089. radius: collider._radius.asArray()
  56090. },
  56091. collisionId: collisionIndex,
  56092. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56093. maximumRetry: maximumRetry
  56094. };
  56095. var message = {
  56096. payload: payload,
  56097. taskType: WorkerTaskType.COLLIDE
  56098. };
  56099. this._worker.postMessage(message);
  56100. };
  56101. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56102. this._scene = scene;
  56103. this._scene.registerAfterRender(this._afterRender);
  56104. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56105. this._worker = new Worker(workerUrl);
  56106. this._worker.onmessage = this._onMessageFromWorker;
  56107. var message = {
  56108. payload: {},
  56109. taskType: WorkerTaskType.INIT
  56110. };
  56111. this._worker.postMessage(message);
  56112. };
  56113. CollisionCoordinatorWorker.prototype.destroy = function () {
  56114. this._scene.unregisterAfterRender(this._afterRender);
  56115. this._worker.terminate();
  56116. };
  56117. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56118. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56119. this.onMeshUpdated(mesh);
  56120. };
  56121. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56122. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56123. };
  56124. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56125. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56126. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56127. this.onGeometryUpdated(geometry);
  56128. };
  56129. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56130. this._toRemoveGeometryArray.push(geometry.id);
  56131. };
  56132. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56133. var submeshes = [];
  56134. if (mesh.subMeshes) {
  56135. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56136. var boundingInfo = sm.getBoundingInfo();
  56137. return {
  56138. position: idx,
  56139. verticesStart: sm.verticesStart,
  56140. verticesCount: sm.verticesCount,
  56141. indexStart: sm.indexStart,
  56142. indexCount: sm.indexCount,
  56143. hasMaterial: !!sm.getMaterial(),
  56144. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56145. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56146. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56147. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56148. };
  56149. });
  56150. }
  56151. var geometryId = null;
  56152. if (mesh instanceof BABYLON.Mesh) {
  56153. var geometry = mesh.geometry;
  56154. geometryId = geometry ? geometry.id : null;
  56155. }
  56156. else if (mesh instanceof BABYLON.InstancedMesh) {
  56157. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56158. geometryId = geometry ? geometry.id : null;
  56159. }
  56160. var boundingInfo = mesh.getBoundingInfo();
  56161. return {
  56162. uniqueId: mesh.uniqueId,
  56163. id: mesh.id,
  56164. name: mesh.name,
  56165. geometryId: geometryId,
  56166. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56167. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56168. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56169. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56170. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56171. subMeshes: submeshes,
  56172. checkCollisions: mesh.checkCollisions
  56173. };
  56174. };
  56175. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56176. return {
  56177. id: geometry.id,
  56178. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56179. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56180. indices: new Uint32Array(geometry.getIndices() || []),
  56181. };
  56182. };
  56183. return CollisionCoordinatorWorker;
  56184. }());
  56185. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56186. /** @hidden */
  56187. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56188. function CollisionCoordinatorLegacy() {
  56189. this._scaledPosition = BABYLON.Vector3.Zero();
  56190. this._scaledVelocity = BABYLON.Vector3.Zero();
  56191. this._finalPosition = BABYLON.Vector3.Zero();
  56192. }
  56193. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56194. position.divideToRef(collider._radius, this._scaledPosition);
  56195. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56196. collider.collidedMesh = null;
  56197. collider._retry = 0;
  56198. collider._initialVelocity = this._scaledVelocity;
  56199. collider._initialPosition = this._scaledPosition;
  56200. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56201. this._finalPosition.multiplyInPlace(collider._radius);
  56202. //run the callback
  56203. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56204. };
  56205. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56206. this._scene = scene;
  56207. };
  56208. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56209. //Legacy need no destruction method.
  56210. };
  56211. //No update in legacy mode
  56212. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56213. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56214. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56215. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56216. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56217. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56218. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56219. if (excludedMesh === void 0) { excludedMesh = null; }
  56220. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56221. if (collider._retry >= maximumRetry) {
  56222. finalPosition.copyFrom(position);
  56223. return;
  56224. }
  56225. // Check if this is a mesh else camera or -1
  56226. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56227. collider._initialize(position, velocity, closeDistance);
  56228. // Check all meshes
  56229. for (var index = 0; index < this._scene.meshes.length; index++) {
  56230. var mesh = this._scene.meshes[index];
  56231. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56232. mesh._checkCollision(collider);
  56233. }
  56234. }
  56235. if (!collider.collisionFound) {
  56236. position.addToRef(velocity, finalPosition);
  56237. return;
  56238. }
  56239. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56240. collider._getResponse(position, velocity);
  56241. }
  56242. if (velocity.length() <= closeDistance) {
  56243. finalPosition.copyFrom(position);
  56244. return;
  56245. }
  56246. collider._retry++;
  56247. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56248. };
  56249. return CollisionCoordinatorLegacy;
  56250. }());
  56251. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56252. })(BABYLON || (BABYLON = {}));
  56253. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56254. var BABYLON;
  56255. (function (BABYLON) {
  56256. /**
  56257. * A particle represents one of the element emitted by a particle system.
  56258. * This is mainly define by its coordinates, direction, velocity and age.
  56259. */
  56260. var Particle = /** @class */ (function () {
  56261. /**
  56262. * Creates a new instance Particle
  56263. * @param particleSystem the particle system the particle belongs to
  56264. */
  56265. function Particle(
  56266. /**
  56267. * The particle system the particle belongs to.
  56268. */
  56269. particleSystem) {
  56270. this.particleSystem = particleSystem;
  56271. /**
  56272. * The world position of the particle in the scene.
  56273. */
  56274. this.position = BABYLON.Vector3.Zero();
  56275. /**
  56276. * The world direction of the particle in the scene.
  56277. */
  56278. this.direction = BABYLON.Vector3.Zero();
  56279. /**
  56280. * The color of the particle.
  56281. */
  56282. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56283. /**
  56284. * The color change of the particle per step.
  56285. */
  56286. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56287. /**
  56288. * Defines how long will the life of the particle be.
  56289. */
  56290. this.lifeTime = 1.0;
  56291. /**
  56292. * The current age of the particle.
  56293. */
  56294. this.age = 0;
  56295. /**
  56296. * The current size of the particle.
  56297. */
  56298. this.size = 0;
  56299. /**
  56300. * The current scale of the particle.
  56301. */
  56302. this.scale = new BABYLON.Vector2(1, 1);
  56303. /**
  56304. * The current angle of the particle.
  56305. */
  56306. this.angle = 0;
  56307. /**
  56308. * Defines how fast is the angle changing.
  56309. */
  56310. this.angularSpeed = 0;
  56311. /**
  56312. * Defines the cell index used by the particle to be rendered from a sprite.
  56313. */
  56314. this.cellIndex = 0;
  56315. /** @hidden */
  56316. this._attachedSubEmitters = null;
  56317. /** @hidden */
  56318. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56319. /** @hidden */
  56320. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56321. /** @hidden */
  56322. this._currentSize1 = 0;
  56323. /** @hidden */
  56324. this._currentSize2 = 0;
  56325. /** @hidden */
  56326. this._currentAngularSpeed1 = 0;
  56327. /** @hidden */
  56328. this._currentAngularSpeed2 = 0;
  56329. /** @hidden */
  56330. this._currentVelocity1 = 0;
  56331. /** @hidden */
  56332. this._currentVelocity2 = 0;
  56333. /** @hidden */
  56334. this._currentLimitVelocity1 = 0;
  56335. /** @hidden */
  56336. this._currentLimitVelocity2 = 0;
  56337. /** @hidden */
  56338. this._currentDrag1 = 0;
  56339. /** @hidden */
  56340. this._currentDrag2 = 0;
  56341. this.id = Particle._Count++;
  56342. if (!this.particleSystem.isAnimationSheetEnabled) {
  56343. return;
  56344. }
  56345. this.updateCellInfoFromSystem();
  56346. }
  56347. Particle.prototype.updateCellInfoFromSystem = function () {
  56348. this.cellIndex = this.particleSystem.startSpriteCellID;
  56349. };
  56350. /**
  56351. * Defines how the sprite cell index is updated for the particle
  56352. */
  56353. Particle.prototype.updateCellIndex = function () {
  56354. var offsetAge = this.age;
  56355. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56356. if (this.particleSystem.spriteRandomStartCell) {
  56357. if (this._randomCellOffset === undefined) {
  56358. this._randomCellOffset = Math.random() * this.lifeTime;
  56359. }
  56360. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56361. changeSpeed = 1;
  56362. offsetAge = this._randomCellOffset;
  56363. }
  56364. else {
  56365. offsetAge += this._randomCellOffset;
  56366. }
  56367. }
  56368. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56369. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56370. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56371. };
  56372. /** @hidden */
  56373. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56374. if (subEmitter.particleSystem.emitter.position) {
  56375. var emitterMesh = subEmitter.particleSystem.emitter;
  56376. emitterMesh.position.copyFrom(this.position);
  56377. if (subEmitter.inheritDirection) {
  56378. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56379. // Look at using Y as forward
  56380. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56381. }
  56382. }
  56383. else {
  56384. var emitterPosition = subEmitter.particleSystem.emitter;
  56385. emitterPosition.copyFrom(this.position);
  56386. }
  56387. // Set inheritedVelocityOffset to be used when new particles are created
  56388. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56389. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56390. };
  56391. /** @hidden */
  56392. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56393. var _this = this;
  56394. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56395. this._attachedSubEmitters.forEach(function (subEmitter) {
  56396. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56397. });
  56398. }
  56399. };
  56400. /** @hidden */
  56401. Particle.prototype._reset = function () {
  56402. this.age = 0;
  56403. this._currentColorGradient = null;
  56404. this._currentSizeGradient = null;
  56405. this._currentAngularSpeedGradient = null;
  56406. this._currentVelocityGradient = null;
  56407. this._currentLimitVelocityGradient = null;
  56408. this._currentDragGradient = null;
  56409. this.cellIndex = this.particleSystem.startSpriteCellID;
  56410. this._randomCellOffset = undefined;
  56411. };
  56412. /**
  56413. * Copy the properties of particle to another one.
  56414. * @param other the particle to copy the information to.
  56415. */
  56416. Particle.prototype.copyTo = function (other) {
  56417. other.position.copyFrom(this.position);
  56418. if (this._initialDirection) {
  56419. if (other._initialDirection) {
  56420. other._initialDirection.copyFrom(this._initialDirection);
  56421. }
  56422. else {
  56423. other._initialDirection = this._initialDirection.clone();
  56424. }
  56425. }
  56426. else {
  56427. other._initialDirection = null;
  56428. }
  56429. other.direction.copyFrom(this.direction);
  56430. other.color.copyFrom(this.color);
  56431. other.colorStep.copyFrom(this.colorStep);
  56432. other.lifeTime = this.lifeTime;
  56433. other.age = this.age;
  56434. other._randomCellOffset = this._randomCellOffset;
  56435. other.size = this.size;
  56436. other.scale.copyFrom(this.scale);
  56437. other.angle = this.angle;
  56438. other.angularSpeed = this.angularSpeed;
  56439. other.particleSystem = this.particleSystem;
  56440. other.cellIndex = this.cellIndex;
  56441. other.id = this.id;
  56442. other._attachedSubEmitters = this._attachedSubEmitters;
  56443. if (this._currentColorGradient) {
  56444. other._currentColorGradient = this._currentColorGradient;
  56445. other._currentColor1.copyFrom(this._currentColor1);
  56446. other._currentColor2.copyFrom(this._currentColor2);
  56447. }
  56448. if (this._currentSizeGradient) {
  56449. other._currentSizeGradient = this._currentSizeGradient;
  56450. other._currentSize1 = this._currentSize1;
  56451. other._currentSize2 = this._currentSize2;
  56452. }
  56453. if (this._currentAngularSpeedGradient) {
  56454. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56455. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56456. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56457. }
  56458. if (this._currentVelocityGradient) {
  56459. other._currentVelocityGradient = this._currentVelocityGradient;
  56460. other._currentVelocity1 = this._currentVelocity1;
  56461. other._currentVelocity2 = this._currentVelocity2;
  56462. }
  56463. if (this._currentLimitVelocityGradient) {
  56464. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56465. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56466. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56467. }
  56468. if (this._currentDragGradient) {
  56469. other._currentDragGradient = this._currentDragGradient;
  56470. other._currentDrag1 = this._currentDrag1;
  56471. other._currentDrag2 = this._currentDrag2;
  56472. }
  56473. if (this.particleSystem.isAnimationSheetEnabled) {
  56474. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56475. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56476. }
  56477. if (this.particleSystem.useRampGradients) {
  56478. other.remapData.copyFrom(this.remapData);
  56479. }
  56480. if (this._randomNoiseCoordinates1) {
  56481. if (other._randomNoiseCoordinates1) {
  56482. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56483. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56484. }
  56485. else {
  56486. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56487. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56488. }
  56489. }
  56490. };
  56491. Particle._Count = 0;
  56492. return Particle;
  56493. }());
  56494. BABYLON.Particle = Particle;
  56495. })(BABYLON || (BABYLON = {}));
  56496. //# sourceMappingURL=babylon.particle.js.map
  56497. var BABYLON;
  56498. (function (BABYLON) {
  56499. /**
  56500. * This represents the base class for particle system in Babylon.
  56501. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  56502. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56503. * @example https://doc.babylonjs.com/babylon101/particles
  56504. */
  56505. var BaseParticleSystem = /** @class */ (function () {
  56506. /**
  56507. * Instantiates a particle system.
  56508. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  56509. * @param name The name of the particle system
  56510. */
  56511. function BaseParticleSystem(name) {
  56512. /**
  56513. * List of animations used by the particle system.
  56514. */
  56515. this.animations = [];
  56516. /**
  56517. * The rendering group used by the Particle system to chose when to render.
  56518. */
  56519. this.renderingGroupId = 0;
  56520. /**
  56521. * The emitter represents the Mesh or position we are attaching the particle system to.
  56522. */
  56523. this.emitter = null;
  56524. /**
  56525. * The maximum number of particles to emit per frame
  56526. */
  56527. this.emitRate = 10;
  56528. /**
  56529. * If you want to launch only a few particles at once, that can be done, as well.
  56530. */
  56531. this.manualEmitCount = -1;
  56532. /**
  56533. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56534. */
  56535. this.updateSpeed = 0.01;
  56536. /**
  56537. * The amount of time the particle system is running (depends of the overall update speed).
  56538. */
  56539. this.targetStopDuration = 0;
  56540. /**
  56541. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56542. */
  56543. this.disposeOnStop = false;
  56544. /**
  56545. * Minimum power of emitting particles.
  56546. */
  56547. this.minEmitPower = 1;
  56548. /**
  56549. * Maximum power of emitting particles.
  56550. */
  56551. this.maxEmitPower = 1;
  56552. /**
  56553. * Minimum life time of emitting particles.
  56554. */
  56555. this.minLifeTime = 1;
  56556. /**
  56557. * Maximum life time of emitting particles.
  56558. */
  56559. this.maxLifeTime = 1;
  56560. /**
  56561. * Minimum Size of emitting particles.
  56562. */
  56563. this.minSize = 1;
  56564. /**
  56565. * Maximum Size of emitting particles.
  56566. */
  56567. this.maxSize = 1;
  56568. /**
  56569. * Minimum scale of emitting particles on X axis.
  56570. */
  56571. this.minScaleX = 1;
  56572. /**
  56573. * Maximum scale of emitting particles on X axis.
  56574. */
  56575. this.maxScaleX = 1;
  56576. /**
  56577. * Minimum scale of emitting particles on Y axis.
  56578. */
  56579. this.minScaleY = 1;
  56580. /**
  56581. * Maximum scale of emitting particles on Y axis.
  56582. */
  56583. this.maxScaleY = 1;
  56584. /**
  56585. * Gets or sets the minimal initial rotation in radians.
  56586. */
  56587. this.minInitialRotation = 0;
  56588. /**
  56589. * Gets or sets the maximal initial rotation in radians.
  56590. */
  56591. this.maxInitialRotation = 0;
  56592. /**
  56593. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56594. */
  56595. this.minAngularSpeed = 0;
  56596. /**
  56597. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56598. */
  56599. this.maxAngularSpeed = 0;
  56600. /**
  56601. * The layer mask we are rendering the particles through.
  56602. */
  56603. this.layerMask = 0x0FFFFFFF;
  56604. /**
  56605. * This can help using your own shader to render the particle system.
  56606. * The according effect will be created
  56607. */
  56608. this.customShader = null;
  56609. /**
  56610. * By default particle system starts as soon as they are created. This prevents the
  56611. * automatic start to happen and let you decide when to start emitting particles.
  56612. */
  56613. this.preventAutoStart = false;
  56614. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  56615. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  56616. /**
  56617. * Callback triggered when the particle animation is ending.
  56618. */
  56619. this.onAnimationEnd = null;
  56620. /**
  56621. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56622. */
  56623. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56624. /**
  56625. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56626. * to override the particles.
  56627. */
  56628. this.forceDepthWrite = false;
  56629. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  56630. this.preWarmCycles = 0;
  56631. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56632. this.preWarmStepOffset = 1;
  56633. /**
  56634. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  56635. */
  56636. this.spriteCellChangeSpeed = 1;
  56637. /**
  56638. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56639. */
  56640. this.startSpriteCellID = 0;
  56641. /**
  56642. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56643. */
  56644. this.endSpriteCellID = 0;
  56645. /**
  56646. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56647. */
  56648. this.spriteCellWidth = 0;
  56649. /**
  56650. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56651. */
  56652. this.spriteCellHeight = 0;
  56653. /**
  56654. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  56655. */
  56656. this.spriteRandomStartCell = false;
  56657. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56658. this.translationPivot = new BABYLON.Vector2(0, 0);
  56659. /**
  56660. * You can use gravity if you want to give an orientation to your particles.
  56661. */
  56662. this.gravity = BABYLON.Vector3.Zero();
  56663. this._colorGradients = null;
  56664. this._sizeGradients = null;
  56665. this._lifeTimeGradients = null;
  56666. this._angularSpeedGradients = null;
  56667. this._velocityGradients = null;
  56668. this._limitVelocityGradients = null;
  56669. this._dragGradients = null;
  56670. this._emitRateGradients = null;
  56671. this._startSizeGradients = null;
  56672. this._rampGradients = null;
  56673. this._colorRemapGradients = null;
  56674. this._alphaRemapGradients = null;
  56675. /**
  56676. * Defines the delay in milliseconds before starting the system (0 by default)
  56677. */
  56678. this.startDelay = 0;
  56679. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  56680. this.limitVelocityDamping = 0.4;
  56681. /**
  56682. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56683. */
  56684. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56685. /**
  56686. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56687. */
  56688. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56689. /**
  56690. * Color the particle will have at the end of its lifetime
  56691. */
  56692. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56693. /**
  56694. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  56695. */
  56696. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56697. /**
  56698. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56699. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  56700. */
  56701. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56702. this._isBillboardBased = true;
  56703. /**
  56704. * Local cache of defines for image processing.
  56705. */
  56706. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  56707. this.id = name;
  56708. this.name = name;
  56709. }
  56710. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  56711. /**
  56712. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  56713. */
  56714. get: function () {
  56715. return this._isAnimationSheetEnabled;
  56716. },
  56717. set: function (value) {
  56718. if (this._isAnimationSheetEnabled == value) {
  56719. return;
  56720. }
  56721. this._isAnimationSheetEnabled = value;
  56722. this._reset();
  56723. },
  56724. enumerable: true,
  56725. configurable: true
  56726. });
  56727. /**
  56728. * Get hosting scene
  56729. * @returns the scene
  56730. */
  56731. BaseParticleSystem.prototype.getScene = function () {
  56732. return this._scene;
  56733. };
  56734. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  56735. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  56736. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  56737. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  56738. };
  56739. /**
  56740. * Gets the current list of drag gradients.
  56741. * You must use addDragGradient and removeDragGradient to udpate this list
  56742. * @returns the list of drag gradients
  56743. */
  56744. BaseParticleSystem.prototype.getDragGradients = function () {
  56745. return this._dragGradients;
  56746. };
  56747. /**
  56748. * Gets the current list of limit velocity gradients.
  56749. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  56750. * @returns the list of limit velocity gradients
  56751. */
  56752. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  56753. return this._limitVelocityGradients;
  56754. };
  56755. /**
  56756. * Gets the current list of color gradients.
  56757. * You must use addColorGradient and removeColorGradient to udpate this list
  56758. * @returns the list of color gradients
  56759. */
  56760. BaseParticleSystem.prototype.getColorGradients = function () {
  56761. return this._colorGradients;
  56762. };
  56763. /**
  56764. * Gets the current list of size gradients.
  56765. * You must use addSizeGradient and removeSizeGradient to udpate this list
  56766. * @returns the list of size gradients
  56767. */
  56768. BaseParticleSystem.prototype.getSizeGradients = function () {
  56769. return this._sizeGradients;
  56770. };
  56771. /**
  56772. * Gets the current list of color remap gradients.
  56773. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  56774. * @returns the list of color remap gradients
  56775. */
  56776. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  56777. return this._colorRemapGradients;
  56778. };
  56779. /**
  56780. * Gets the current list of alpha remap gradients.
  56781. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  56782. * @returns the list of alpha remap gradients
  56783. */
  56784. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  56785. return this._alphaRemapGradients;
  56786. };
  56787. /**
  56788. * Gets the current list of life time gradients.
  56789. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  56790. * @returns the list of life time gradients
  56791. */
  56792. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  56793. return this._lifeTimeGradients;
  56794. };
  56795. /**
  56796. * Gets the current list of angular speed gradients.
  56797. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  56798. * @returns the list of angular speed gradients
  56799. */
  56800. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  56801. return this._angularSpeedGradients;
  56802. };
  56803. /**
  56804. * Gets the current list of velocity gradients.
  56805. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  56806. * @returns the list of velocity gradients
  56807. */
  56808. BaseParticleSystem.prototype.getVelocityGradients = function () {
  56809. return this._velocityGradients;
  56810. };
  56811. /**
  56812. * Gets the current list of start size gradients.
  56813. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  56814. * @returns the list of start size gradients
  56815. */
  56816. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  56817. return this._startSizeGradients;
  56818. };
  56819. /**
  56820. * Gets the current list of emit rate gradients.
  56821. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  56822. * @returns the list of emit rate gradients
  56823. */
  56824. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  56825. return this._emitRateGradients;
  56826. };
  56827. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  56828. /**
  56829. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56830. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56831. */
  56832. get: function () {
  56833. if (this.particleEmitterType.direction1) {
  56834. return this.particleEmitterType.direction1;
  56835. }
  56836. return BABYLON.Vector3.Zero();
  56837. },
  56838. set: function (value) {
  56839. if (this.particleEmitterType.direction1) {
  56840. this.particleEmitterType.direction1 = value;
  56841. }
  56842. },
  56843. enumerable: true,
  56844. configurable: true
  56845. });
  56846. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  56847. /**
  56848. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56849. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56850. */
  56851. get: function () {
  56852. if (this.particleEmitterType.direction2) {
  56853. return this.particleEmitterType.direction2;
  56854. }
  56855. return BABYLON.Vector3.Zero();
  56856. },
  56857. set: function (value) {
  56858. if (this.particleEmitterType.direction2) {
  56859. this.particleEmitterType.direction2 = value;
  56860. }
  56861. },
  56862. enumerable: true,
  56863. configurable: true
  56864. });
  56865. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  56866. /**
  56867. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56868. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56869. */
  56870. get: function () {
  56871. if (this.particleEmitterType.minEmitBox) {
  56872. return this.particleEmitterType.minEmitBox;
  56873. }
  56874. return BABYLON.Vector3.Zero();
  56875. },
  56876. set: function (value) {
  56877. if (this.particleEmitterType.minEmitBox) {
  56878. this.particleEmitterType.minEmitBox = value;
  56879. }
  56880. },
  56881. enumerable: true,
  56882. configurable: true
  56883. });
  56884. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  56885. /**
  56886. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56887. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56888. */
  56889. get: function () {
  56890. if (this.particleEmitterType.maxEmitBox) {
  56891. return this.particleEmitterType.maxEmitBox;
  56892. }
  56893. return BABYLON.Vector3.Zero();
  56894. },
  56895. set: function (value) {
  56896. if (this.particleEmitterType.maxEmitBox) {
  56897. this.particleEmitterType.maxEmitBox = value;
  56898. }
  56899. },
  56900. enumerable: true,
  56901. configurable: true
  56902. });
  56903. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  56904. /**
  56905. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  56906. */
  56907. get: function () {
  56908. return this._isBillboardBased;
  56909. },
  56910. set: function (value) {
  56911. if (this._isBillboardBased === value) {
  56912. return;
  56913. }
  56914. this._isBillboardBased = value;
  56915. this._reset();
  56916. },
  56917. enumerable: true,
  56918. configurable: true
  56919. });
  56920. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  56921. /**
  56922. * Gets the image processing configuration used either in this material.
  56923. */
  56924. get: function () {
  56925. return this._imageProcessingConfiguration;
  56926. },
  56927. /**
  56928. * Sets the Default image processing configuration used either in the this material.
  56929. *
  56930. * If sets to null, the scene one is in use.
  56931. */
  56932. set: function (value) {
  56933. this._attachImageProcessingConfiguration(value);
  56934. },
  56935. enumerable: true,
  56936. configurable: true
  56937. });
  56938. /**
  56939. * Attaches a new image processing configuration to the Standard Material.
  56940. * @param configuration
  56941. */
  56942. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  56943. if (configuration === this._imageProcessingConfiguration) {
  56944. return;
  56945. }
  56946. // Pick the scene configuration if needed.
  56947. if (!configuration) {
  56948. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  56949. }
  56950. else {
  56951. this._imageProcessingConfiguration = configuration;
  56952. }
  56953. };
  56954. /** @hidden */
  56955. BaseParticleSystem.prototype._reset = function () {
  56956. };
  56957. /** @hidden */
  56958. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  56959. if (!gradients) {
  56960. return this;
  56961. }
  56962. var index = 0;
  56963. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  56964. var valueGradient = gradients_1[_i];
  56965. if (valueGradient.gradient === gradient) {
  56966. gradients.splice(index, 1);
  56967. break;
  56968. }
  56969. index++;
  56970. }
  56971. if (texture) {
  56972. texture.dispose();
  56973. }
  56974. return this;
  56975. };
  56976. /**
  56977. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56978. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56979. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56980. * @returns the emitter
  56981. */
  56982. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56983. var particleEmitter = new BABYLON.PointParticleEmitter();
  56984. particleEmitter.direction1 = direction1;
  56985. particleEmitter.direction2 = direction2;
  56986. this.particleEmitterType = particleEmitter;
  56987. return particleEmitter;
  56988. };
  56989. /**
  56990. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56991. * @param radius The radius of the hemisphere to emit from
  56992. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56993. * @returns the emitter
  56994. */
  56995. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56996. if (radius === void 0) { radius = 1; }
  56997. if (radiusRange === void 0) { radiusRange = 1; }
  56998. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56999. this.particleEmitterType = particleEmitter;
  57000. return particleEmitter;
  57001. };
  57002. /**
  57003. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57004. * @param radius The radius of the sphere to emit from
  57005. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57006. * @returns the emitter
  57007. */
  57008. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57009. if (radius === void 0) { radius = 1; }
  57010. if (radiusRange === void 0) { radiusRange = 1; }
  57011. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57012. this.particleEmitterType = particleEmitter;
  57013. return particleEmitter;
  57014. };
  57015. /**
  57016. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57017. * @param radius The radius of the sphere to emit from
  57018. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57019. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57020. * @returns the emitter
  57021. */
  57022. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57023. if (radius === void 0) { radius = 1; }
  57024. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57025. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57026. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57027. this.particleEmitterType = particleEmitter;
  57028. return particleEmitter;
  57029. };
  57030. /**
  57031. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57032. * @param radius The radius of the emission cylinder
  57033. * @param height The height of the emission cylinder
  57034. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57035. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57036. * @returns the emitter
  57037. */
  57038. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57039. if (radius === void 0) { radius = 1; }
  57040. if (height === void 0) { height = 1; }
  57041. if (radiusRange === void 0) { radiusRange = 1; }
  57042. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57043. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57044. this.particleEmitterType = particleEmitter;
  57045. return particleEmitter;
  57046. };
  57047. /**
  57048. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57049. * @param radius The radius of the cylinder to emit from
  57050. * @param height The height of the emission cylinder
  57051. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57052. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57053. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57054. * @returns the emitter
  57055. */
  57056. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57057. if (radius === void 0) { radius = 1; }
  57058. if (height === void 0) { height = 1; }
  57059. if (radiusRange === void 0) { radiusRange = 1; }
  57060. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57061. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57062. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57063. this.particleEmitterType = particleEmitter;
  57064. return particleEmitter;
  57065. };
  57066. /**
  57067. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57068. * @param radius The radius of the cone to emit from
  57069. * @param angle The base angle of the cone
  57070. * @returns the emitter
  57071. */
  57072. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57073. if (radius === void 0) { radius = 1; }
  57074. if (angle === void 0) { angle = Math.PI / 4; }
  57075. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57076. this.particleEmitterType = particleEmitter;
  57077. return particleEmitter;
  57078. };
  57079. /**
  57080. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57081. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57082. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57083. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57084. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57085. * @returns the emitter
  57086. */
  57087. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57088. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57089. this.particleEmitterType = particleEmitter;
  57090. this.direction1 = direction1;
  57091. this.direction2 = direction2;
  57092. this.minEmitBox = minEmitBox;
  57093. this.maxEmitBox = maxEmitBox;
  57094. return particleEmitter;
  57095. };
  57096. /**
  57097. * Source color is added to the destination color without alpha affecting the result
  57098. */
  57099. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57100. /**
  57101. * Blend current color and particle color using particle’s alpha
  57102. */
  57103. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57104. /**
  57105. * Add current color and particle color multiplied by particle’s alpha
  57106. */
  57107. BaseParticleSystem.BLENDMODE_ADD = 2;
  57108. /**
  57109. * Multiply current color with particle color
  57110. */
  57111. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57112. /**
  57113. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57114. */
  57115. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57116. return BaseParticleSystem;
  57117. }());
  57118. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57119. })(BABYLON || (BABYLON = {}));
  57120. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57121. var BABYLON;
  57122. (function (BABYLON) {
  57123. /**
  57124. * This represents a particle system in Babylon.
  57125. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  57126. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57127. * @example https://doc.babylonjs.com/babylon101/particles
  57128. */
  57129. var ParticleSystem = /** @class */ (function (_super) {
  57130. __extends(ParticleSystem, _super);
  57131. /**
  57132. * Instantiates a particle system.
  57133. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  57134. * @param name The name of the particle system
  57135. * @param capacity The max number of particles alive at the same time
  57136. * @param scene The scene the particle system belongs to
  57137. * @param customEffect a custom effect used to change the way particles are rendered by default
  57138. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57139. * @param epsilon Offset used to render the particles
  57140. */
  57141. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57142. if (customEffect === void 0) { customEffect = null; }
  57143. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57144. if (epsilon === void 0) { epsilon = 0.01; }
  57145. var _this = _super.call(this, name) || this;
  57146. /**
  57147. * @hidden
  57148. */
  57149. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57150. /**
  57151. * An event triggered when the system is disposed
  57152. */
  57153. _this.onDisposeObservable = new BABYLON.Observable();
  57154. _this._particles = new Array();
  57155. _this._stockParticles = new Array();
  57156. _this._newPartsExcess = 0;
  57157. _this._vertexBuffers = {};
  57158. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57159. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57160. _this._scaledDirection = BABYLON.Vector3.Zero();
  57161. _this._scaledGravity = BABYLON.Vector3.Zero();
  57162. _this._currentRenderId = -1;
  57163. _this._useInstancing = false;
  57164. _this._started = false;
  57165. _this._stopped = false;
  57166. _this._actualFrame = 0;
  57167. /** @hidden */
  57168. _this._currentEmitRate1 = 0;
  57169. /** @hidden */
  57170. _this._currentEmitRate2 = 0;
  57171. /** @hidden */
  57172. _this._currentStartSize1 = 0;
  57173. /** @hidden */
  57174. _this._currentStartSize2 = 0;
  57175. _this._rawTextureWidth = 256;
  57176. _this._useRampGradients = false;
  57177. /**
  57178. * @hidden
  57179. * If the particle systems emitter should be disposed when the particle system is disposed
  57180. */
  57181. _this._disposeEmitterOnDispose = false;
  57182. // start of sub system methods
  57183. /**
  57184. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57185. * Its lifetime will start back at 0.
  57186. */
  57187. _this.recycleParticle = function (particle) {
  57188. // move particle from activeParticle list to stock particles
  57189. var lastParticle = _this._particles.pop();
  57190. if (lastParticle !== particle) {
  57191. lastParticle.copyTo(particle);
  57192. }
  57193. _this._stockParticles.push(lastParticle);
  57194. };
  57195. _this._createParticle = function () {
  57196. var particle;
  57197. if (_this._stockParticles.length !== 0) {
  57198. particle = _this._stockParticles.pop();
  57199. particle._reset();
  57200. }
  57201. else {
  57202. particle = new BABYLON.Particle(_this);
  57203. }
  57204. // Attach emitters
  57205. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57206. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57207. particle._attachedSubEmitters = [];
  57208. subEmitters.forEach(function (subEmitter) {
  57209. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57210. var newEmitter = subEmitter.clone();
  57211. particle._attachedSubEmitters.push(newEmitter);
  57212. newEmitter.particleSystem.start();
  57213. }
  57214. });
  57215. }
  57216. return particle;
  57217. };
  57218. _this._emitFromParticle = function (particle) {
  57219. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57220. return;
  57221. }
  57222. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57223. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57224. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57225. var subSystem = subEmitter.clone();
  57226. particle._inheritParticleInfoToSubEmitter(subSystem);
  57227. subSystem.particleSystem._rootParticleSystem = _this;
  57228. _this.activeSubSystems.push(subSystem.particleSystem);
  57229. subSystem.particleSystem.start();
  57230. }
  57231. });
  57232. };
  57233. _this._capacity = capacity;
  57234. _this._epsilon = epsilon;
  57235. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57236. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57237. // Setup the default processing configuration to the scene.
  57238. _this._attachImageProcessingConfiguration(null);
  57239. _this._customEffect = customEffect;
  57240. _this._scene.particleSystems.push(_this);
  57241. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57242. _this._createIndexBuffer();
  57243. _this._createVertexBuffers();
  57244. // Default emitter type
  57245. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57246. // Update
  57247. _this.updateFunction = function (particles) {
  57248. var noiseTextureSize = null;
  57249. var noiseTextureData = null;
  57250. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57251. noiseTextureSize = _this.noiseTexture.getSize();
  57252. noiseTextureData = (_this.noiseTexture.getContent());
  57253. }
  57254. var _loop_1 = function () {
  57255. particle = particles[index];
  57256. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57257. var previousAge = particle.age;
  57258. particle.age += scaledUpdateSpeed;
  57259. // Evaluate step to death
  57260. if (particle.age > particle.lifeTime) {
  57261. var diff = particle.age - previousAge;
  57262. var oldDiff = particle.lifeTime - previousAge;
  57263. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57264. particle.age = particle.lifeTime;
  57265. }
  57266. var ratio = particle.age / particle.lifeTime;
  57267. // Color
  57268. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57269. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57270. if (currentGradient !== particle._currentColorGradient) {
  57271. particle._currentColor1.copyFrom(particle._currentColor2);
  57272. nextGradient.getColorToRef(particle._currentColor2);
  57273. particle._currentColorGradient = currentGradient;
  57274. }
  57275. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57276. });
  57277. }
  57278. else {
  57279. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57280. particle.color.addInPlace(_this._scaledColorStep);
  57281. if (particle.color.a < 0) {
  57282. particle.color.a = 0;
  57283. }
  57284. }
  57285. // Angular speed
  57286. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57287. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57288. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57289. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57290. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57291. particle._currentAngularSpeedGradient = currentGradient;
  57292. }
  57293. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57294. });
  57295. }
  57296. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57297. // Direction
  57298. var directionScale = scaledUpdateSpeed;
  57299. /// Velocity
  57300. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57301. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57302. if (currentGradient !== particle._currentVelocityGradient) {
  57303. particle._currentVelocity1 = particle._currentVelocity2;
  57304. particle._currentVelocity2 = nextGradient.getFactor();
  57305. particle._currentVelocityGradient = currentGradient;
  57306. }
  57307. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57308. });
  57309. }
  57310. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57311. /// Limit velocity
  57312. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57313. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57314. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57315. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57316. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57317. particle._currentLimitVelocityGradient = currentGradient;
  57318. }
  57319. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57320. var currentVelocity = particle.direction.length();
  57321. if (currentVelocity > limitVelocity) {
  57322. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57323. }
  57324. });
  57325. }
  57326. /// Drag
  57327. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57328. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57329. if (currentGradient !== particle._currentDragGradient) {
  57330. particle._currentDrag1 = particle._currentDrag2;
  57331. particle._currentDrag2 = nextGradient.getFactor();
  57332. particle._currentDragGradient = currentGradient;
  57333. }
  57334. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57335. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57336. });
  57337. }
  57338. particle.position.addInPlace(_this._scaledDirection);
  57339. // Noise
  57340. if (noiseTextureData && noiseTextureSize) {
  57341. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57342. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57343. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57344. var force = BABYLON.Tmp.Vector3[0];
  57345. var scaledForce = BABYLON.Tmp.Vector3[1];
  57346. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57347. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57348. particle.direction.addInPlace(scaledForce);
  57349. }
  57350. // Gravity
  57351. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57352. particle.direction.addInPlace(_this._scaledGravity);
  57353. // Size
  57354. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57355. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57356. if (currentGradient !== particle._currentSizeGradient) {
  57357. particle._currentSize1 = particle._currentSize2;
  57358. particle._currentSize2 = nextGradient.getFactor();
  57359. particle._currentSizeGradient = currentGradient;
  57360. }
  57361. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57362. });
  57363. }
  57364. // Remap data
  57365. if (_this._useRampGradients) {
  57366. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57367. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57368. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57369. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57370. particle.remapData.x = min;
  57371. particle.remapData.y = max - min;
  57372. });
  57373. }
  57374. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57375. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57376. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57377. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57378. particle.remapData.z = min;
  57379. particle.remapData.w = max - min;
  57380. });
  57381. }
  57382. }
  57383. if (_this._isAnimationSheetEnabled) {
  57384. particle.updateCellIndex();
  57385. }
  57386. // Update the position of the attached sub-emitters to match their attached particle
  57387. particle._inheritParticleInfoToSubEmitters();
  57388. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57389. _this._emitFromParticle(particle);
  57390. if (particle._attachedSubEmitters) {
  57391. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57392. subEmitter.particleSystem.disposeOnStop = true;
  57393. subEmitter.particleSystem.stop();
  57394. });
  57395. particle._attachedSubEmitters = null;
  57396. }
  57397. _this.recycleParticle(particle);
  57398. index--;
  57399. return "continue";
  57400. }
  57401. };
  57402. var particle;
  57403. for (var index = 0; index < particles.length; index++) {
  57404. _loop_1();
  57405. }
  57406. };
  57407. return _this;
  57408. }
  57409. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57410. /**
  57411. * Sets a callback that will be triggered when the system is disposed
  57412. */
  57413. set: function (callback) {
  57414. if (this._onDisposeObserver) {
  57415. this.onDisposeObservable.remove(this._onDisposeObserver);
  57416. }
  57417. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57418. },
  57419. enumerable: true,
  57420. configurable: true
  57421. });
  57422. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57423. /** Gets or sets a boolean indicating that ramp gradients must be used
  57424. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57425. */
  57426. get: function () {
  57427. return this._useRampGradients;
  57428. },
  57429. set: function (value) {
  57430. if (this._useRampGradients === value) {
  57431. return;
  57432. }
  57433. this._useRampGradients = value;
  57434. this._resetEffect();
  57435. },
  57436. enumerable: true,
  57437. configurable: true
  57438. });
  57439. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57440. //end of Sub-emitter
  57441. /**
  57442. * Gets the current list of active particles
  57443. */
  57444. get: function () {
  57445. return this._particles;
  57446. },
  57447. enumerable: true,
  57448. configurable: true
  57449. });
  57450. /**
  57451. * Returns the string "ParticleSystem"
  57452. * @returns a string containing the class name
  57453. */
  57454. ParticleSystem.prototype.getClassName = function () {
  57455. return "ParticleSystem";
  57456. };
  57457. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57458. var newGradient = new BABYLON.FactorGradient();
  57459. newGradient.gradient = gradient;
  57460. newGradient.factor1 = factor;
  57461. newGradient.factor2 = factor2;
  57462. factorGradients.push(newGradient);
  57463. factorGradients.sort(function (a, b) {
  57464. if (a.gradient < b.gradient) {
  57465. return -1;
  57466. }
  57467. else if (a.gradient > b.gradient) {
  57468. return 1;
  57469. }
  57470. return 0;
  57471. });
  57472. };
  57473. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57474. if (!factorGradients) {
  57475. return;
  57476. }
  57477. var index = 0;
  57478. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57479. var factorGradient = factorGradients_1[_i];
  57480. if (factorGradient.gradient === gradient) {
  57481. factorGradients.splice(index, 1);
  57482. break;
  57483. }
  57484. index++;
  57485. }
  57486. };
  57487. /**
  57488. * Adds a new life time gradient
  57489. * @param gradient defines the gradient to use (between 0 and 1)
  57490. * @param factor defines the life time factor to affect to the specified gradient
  57491. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57492. * @returns the current particle system
  57493. */
  57494. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57495. if (!this._lifeTimeGradients) {
  57496. this._lifeTimeGradients = [];
  57497. }
  57498. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57499. return this;
  57500. };
  57501. /**
  57502. * Remove a specific life time gradient
  57503. * @param gradient defines the gradient to remove
  57504. * @returns the current particle system
  57505. */
  57506. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57507. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57508. return this;
  57509. };
  57510. /**
  57511. * Adds a new size gradient
  57512. * @param gradient defines the gradient to use (between 0 and 1)
  57513. * @param factor defines the size factor to affect to the specified gradient
  57514. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57515. * @returns the current particle system
  57516. */
  57517. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57518. if (!this._sizeGradients) {
  57519. this._sizeGradients = [];
  57520. }
  57521. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57522. return this;
  57523. };
  57524. /**
  57525. * Remove a specific size gradient
  57526. * @param gradient defines the gradient to remove
  57527. * @returns the current particle system
  57528. */
  57529. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57530. this._removeFactorGradient(this._sizeGradients, gradient);
  57531. return this;
  57532. };
  57533. /**
  57534. * Adds a new color remap gradient
  57535. * @param gradient defines the gradient to use (between 0 and 1)
  57536. * @param min defines the color remap minimal range
  57537. * @param max defines the color remap maximal range
  57538. * @returns the current particle system
  57539. */
  57540. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  57541. if (!this._colorRemapGradients) {
  57542. this._colorRemapGradients = [];
  57543. }
  57544. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  57545. return this;
  57546. };
  57547. /**
  57548. * Remove a specific color remap gradient
  57549. * @param gradient defines the gradient to remove
  57550. * @returns the current particle system
  57551. */
  57552. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  57553. this._removeFactorGradient(this._colorRemapGradients, gradient);
  57554. return this;
  57555. };
  57556. /**
  57557. * Adds a new alpha remap gradient
  57558. * @param gradient defines the gradient to use (between 0 and 1)
  57559. * @param min defines the alpha remap minimal range
  57560. * @param max defines the alpha remap maximal range
  57561. * @returns the current particle system
  57562. */
  57563. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  57564. if (!this._alphaRemapGradients) {
  57565. this._alphaRemapGradients = [];
  57566. }
  57567. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  57568. return this;
  57569. };
  57570. /**
  57571. * Remove a specific alpha remap gradient
  57572. * @param gradient defines the gradient to remove
  57573. * @returns the current particle system
  57574. */
  57575. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  57576. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  57577. return this;
  57578. };
  57579. /**
  57580. * Adds a new angular speed gradient
  57581. * @param gradient defines the gradient to use (between 0 and 1)
  57582. * @param factor defines the angular speed to affect to the specified gradient
  57583. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57584. * @returns the current particle system
  57585. */
  57586. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  57587. if (!this._angularSpeedGradients) {
  57588. this._angularSpeedGradients = [];
  57589. }
  57590. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  57591. return this;
  57592. };
  57593. /**
  57594. * Remove a specific angular speed gradient
  57595. * @param gradient defines the gradient to remove
  57596. * @returns the current particle system
  57597. */
  57598. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57599. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  57600. return this;
  57601. };
  57602. /**
  57603. * Adds a new velocity gradient
  57604. * @param gradient defines the gradient to use (between 0 and 1)
  57605. * @param factor defines the velocity to affect to the specified gradient
  57606. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57607. * @returns the current particle system
  57608. */
  57609. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  57610. if (!this._velocityGradients) {
  57611. this._velocityGradients = [];
  57612. }
  57613. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  57614. return this;
  57615. };
  57616. /**
  57617. * Remove a specific velocity gradient
  57618. * @param gradient defines the gradient to remove
  57619. * @returns the current particle system
  57620. */
  57621. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57622. this._removeFactorGradient(this._velocityGradients, gradient);
  57623. return this;
  57624. };
  57625. /**
  57626. * Adds a new limit velocity gradient
  57627. * @param gradient defines the gradient to use (between 0 and 1)
  57628. * @param factor defines the limit velocity value to affect to the specified gradient
  57629. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57630. * @returns the current particle system
  57631. */
  57632. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  57633. if (!this._limitVelocityGradients) {
  57634. this._limitVelocityGradients = [];
  57635. }
  57636. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  57637. return this;
  57638. };
  57639. /**
  57640. * Remove a specific limit velocity gradient
  57641. * @param gradient defines the gradient to remove
  57642. * @returns the current particle system
  57643. */
  57644. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  57645. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  57646. return this;
  57647. };
  57648. /**
  57649. * Adds a new drag gradient
  57650. * @param gradient defines the gradient to use (between 0 and 1)
  57651. * @param factor defines the drag value to affect to the specified gradient
  57652. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57653. * @returns the current particle system
  57654. */
  57655. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  57656. if (!this._dragGradients) {
  57657. this._dragGradients = [];
  57658. }
  57659. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  57660. return this;
  57661. };
  57662. /**
  57663. * Remove a specific drag gradient
  57664. * @param gradient defines the gradient to remove
  57665. * @returns the current particle system
  57666. */
  57667. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  57668. this._removeFactorGradient(this._dragGradients, gradient);
  57669. return this;
  57670. };
  57671. /**
  57672. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  57673. * @param gradient defines the gradient to use (between 0 and 1)
  57674. * @param factor defines the emit rate value to affect to the specified gradient
  57675. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57676. * @returns the current particle system
  57677. */
  57678. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  57679. if (!this._emitRateGradients) {
  57680. this._emitRateGradients = [];
  57681. }
  57682. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  57683. if (!this._currentEmitRateGradient) {
  57684. this._currentEmitRateGradient = this._emitRateGradients[0];
  57685. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  57686. this._currentEmitRate2 = this._currentEmitRate1;
  57687. }
  57688. if (this._emitRateGradients.length === 2) {
  57689. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  57690. }
  57691. return this;
  57692. };
  57693. /**
  57694. * Remove a specific emit rate gradient
  57695. * @param gradient defines the gradient to remove
  57696. * @returns the current particle system
  57697. */
  57698. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  57699. this._removeFactorGradient(this._emitRateGradients, gradient);
  57700. return this;
  57701. };
  57702. /**
  57703. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  57704. * @param gradient defines the gradient to use (between 0 and 1)
  57705. * @param factor defines the start size value to affect to the specified gradient
  57706. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57707. * @returns the current particle system
  57708. */
  57709. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  57710. if (!this._startSizeGradients) {
  57711. this._startSizeGradients = [];
  57712. }
  57713. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  57714. if (!this._currentStartSizeGradient) {
  57715. this._currentStartSizeGradient = this._startSizeGradients[0];
  57716. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  57717. this._currentStartSize2 = this._currentStartSize1;
  57718. }
  57719. if (this._startSizeGradients.length === 2) {
  57720. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  57721. }
  57722. return this;
  57723. };
  57724. /**
  57725. * Remove a specific start size gradient
  57726. * @param gradient defines the gradient to remove
  57727. * @returns the current particle system
  57728. */
  57729. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  57730. this._removeFactorGradient(this._emitRateGradients, gradient);
  57731. return this;
  57732. };
  57733. ParticleSystem.prototype._createRampGradientTexture = function () {
  57734. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  57735. return;
  57736. }
  57737. var data = new Uint8Array(this._rawTextureWidth * 4);
  57738. var tmpColor = BABYLON.Tmp.Color3[0];
  57739. for (var x = 0; x < this._rawTextureWidth; x++) {
  57740. var ratio = x / this._rawTextureWidth;
  57741. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  57742. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57743. data[x * 4] = tmpColor.r * 255;
  57744. data[x * 4 + 1] = tmpColor.g * 255;
  57745. data[x * 4 + 2] = tmpColor.b * 255;
  57746. data[x * 4 + 3] = 255;
  57747. });
  57748. }
  57749. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57750. };
  57751. /**
  57752. * Gets the current list of ramp gradients.
  57753. * You must use addRampGradient and removeRampGradient to udpate this list
  57754. * @returns the list of ramp gradients
  57755. */
  57756. ParticleSystem.prototype.getRampGradients = function () {
  57757. return this._rampGradients;
  57758. };
  57759. /**
  57760. * Adds a new ramp gradient used to remap particle colors
  57761. * @param gradient defines the gradient to use (between 0 and 1)
  57762. * @param color defines the color to affect to the specified gradient
  57763. * @returns the current particle system
  57764. */
  57765. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  57766. if (!this._rampGradients) {
  57767. this._rampGradients = [];
  57768. }
  57769. var rampGradient = new BABYLON.Color3Gradient();
  57770. rampGradient.gradient = gradient;
  57771. rampGradient.color = color;
  57772. this._rampGradients.push(rampGradient);
  57773. this._rampGradients.sort(function (a, b) {
  57774. if (a.gradient < b.gradient) {
  57775. return -1;
  57776. }
  57777. else if (a.gradient > b.gradient) {
  57778. return 1;
  57779. }
  57780. return 0;
  57781. });
  57782. if (this._rampGradientsTexture) {
  57783. this._rampGradientsTexture.dispose();
  57784. this._rampGradientsTexture = null;
  57785. }
  57786. this._createRampGradientTexture();
  57787. return this;
  57788. };
  57789. /**
  57790. * Remove a specific ramp gradient
  57791. * @param gradient defines the gradient to remove
  57792. * @returns the current particle system
  57793. */
  57794. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  57795. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  57796. this._rampGradientsTexture = null;
  57797. if (this._rampGradients && this._rampGradients.length > 0) {
  57798. this._createRampGradientTexture();
  57799. }
  57800. return this;
  57801. };
  57802. /**
  57803. * Adds a new color gradient
  57804. * @param gradient defines the gradient to use (between 0 and 1)
  57805. * @param color1 defines the color to affect to the specified gradient
  57806. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57807. */
  57808. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57809. if (!this._colorGradients) {
  57810. this._colorGradients = [];
  57811. }
  57812. var colorGradient = new BABYLON.ColorGradient();
  57813. colorGradient.gradient = gradient;
  57814. colorGradient.color1 = color1;
  57815. colorGradient.color2 = color2;
  57816. this._colorGradients.push(colorGradient);
  57817. this._colorGradients.sort(function (a, b) {
  57818. if (a.gradient < b.gradient) {
  57819. return -1;
  57820. }
  57821. else if (a.gradient > b.gradient) {
  57822. return 1;
  57823. }
  57824. return 0;
  57825. });
  57826. return this;
  57827. };
  57828. /**
  57829. * Remove a specific color gradient
  57830. * @param gradient defines the gradient to remove
  57831. */
  57832. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  57833. if (!this._colorGradients) {
  57834. return this;
  57835. }
  57836. var index = 0;
  57837. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57838. var colorGradient = _a[_i];
  57839. if (colorGradient.gradient === gradient) {
  57840. this._colorGradients.splice(index, 1);
  57841. break;
  57842. }
  57843. index++;
  57844. }
  57845. return this;
  57846. };
  57847. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  57848. u = Math.abs(u) * 0.5 + 0.5;
  57849. v = Math.abs(v) * 0.5 + 0.5;
  57850. var wrappedU = ((u * width) % width) | 0;
  57851. var wrappedV = ((v * height) % height) | 0;
  57852. var position = (wrappedU + wrappedV * width) * 4;
  57853. return pixels[position] / 255;
  57854. };
  57855. ParticleSystem.prototype._reset = function () {
  57856. this._resetEffect();
  57857. };
  57858. ParticleSystem.prototype._resetEffect = function () {
  57859. if (this._vertexBuffer) {
  57860. this._vertexBuffer.dispose();
  57861. this._vertexBuffer = null;
  57862. }
  57863. if (this._spriteBuffer) {
  57864. this._spriteBuffer.dispose();
  57865. this._spriteBuffer = null;
  57866. }
  57867. this._createVertexBuffers();
  57868. };
  57869. ParticleSystem.prototype._createVertexBuffers = function () {
  57870. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  57871. if (this._isAnimationSheetEnabled) {
  57872. this._vertexBufferSize += 1;
  57873. }
  57874. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  57875. this._vertexBufferSize += 3;
  57876. }
  57877. if (this._useRampGradients) {
  57878. this._vertexBufferSize += 4;
  57879. }
  57880. var engine = this._scene.getEngine();
  57881. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  57882. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  57883. var dataOffset = 0;
  57884. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57885. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57886. dataOffset += 3;
  57887. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57888. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57889. dataOffset += 4;
  57890. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57891. this._vertexBuffers["angle"] = options;
  57892. dataOffset += 1;
  57893. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57894. this._vertexBuffers["size"] = size;
  57895. dataOffset += 2;
  57896. if (this._isAnimationSheetEnabled) {
  57897. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57898. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  57899. dataOffset += 1;
  57900. }
  57901. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  57902. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57903. this._vertexBuffers["direction"] = directionBuffer;
  57904. dataOffset += 3;
  57905. }
  57906. if (this._useRampGradients) {
  57907. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57908. this._vertexBuffers["remapData"] = rampDataBuffer;
  57909. dataOffset += 4;
  57910. }
  57911. var offsets;
  57912. if (this._useInstancing) {
  57913. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  57914. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  57915. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  57916. }
  57917. else {
  57918. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57919. dataOffset += 2;
  57920. }
  57921. this._vertexBuffers["offset"] = offsets;
  57922. };
  57923. ParticleSystem.prototype._createIndexBuffer = function () {
  57924. if (this._useInstancing) {
  57925. return;
  57926. }
  57927. var indices = [];
  57928. var index = 0;
  57929. for (var count = 0; count < this._capacity; count++) {
  57930. indices.push(index);
  57931. indices.push(index + 1);
  57932. indices.push(index + 2);
  57933. indices.push(index);
  57934. indices.push(index + 2);
  57935. indices.push(index + 3);
  57936. index += 4;
  57937. }
  57938. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  57939. };
  57940. /**
  57941. * Gets the maximum number of particles active at the same time.
  57942. * @returns The max number of active particles.
  57943. */
  57944. ParticleSystem.prototype.getCapacity = function () {
  57945. return this._capacity;
  57946. };
  57947. /**
  57948. * Gets whether there are still active particles in the system.
  57949. * @returns True if it is alive, otherwise false.
  57950. */
  57951. ParticleSystem.prototype.isAlive = function () {
  57952. return this._alive;
  57953. };
  57954. /**
  57955. * Gets if the system has been started. (Note: this will still be true after stop is called)
  57956. * @returns True if it has been started, otherwise false.
  57957. */
  57958. ParticleSystem.prototype.isStarted = function () {
  57959. return this._started;
  57960. };
  57961. /**
  57962. * Starts the particle system and begins to emit
  57963. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  57964. */
  57965. ParticleSystem.prototype.start = function (delay) {
  57966. var _this = this;
  57967. if (delay === void 0) { delay = this.startDelay; }
  57968. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  57969. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  57970. }
  57971. if (delay) {
  57972. setTimeout(function () {
  57973. _this.start(0);
  57974. }, delay);
  57975. return;
  57976. }
  57977. // Convert the subEmitters field to the constant type field _subEmitters
  57978. this._subEmitters = new Array();
  57979. if (this.subEmitters) {
  57980. this.subEmitters.forEach(function (subEmitter) {
  57981. if (subEmitter instanceof ParticleSystem) {
  57982. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  57983. }
  57984. else if (subEmitter instanceof BABYLON.SubEmitter) {
  57985. _this._subEmitters.push([subEmitter]);
  57986. }
  57987. else if (subEmitter instanceof Array) {
  57988. _this._subEmitters.push(subEmitter);
  57989. }
  57990. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  57991. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  57992. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  57993. }
  57994. });
  57995. });
  57996. }
  57997. this._started = true;
  57998. this._stopped = false;
  57999. this._actualFrame = 0;
  58000. if (this._subEmitters && this._subEmitters.length != 0) {
  58001. this.activeSubSystems = new Array();
  58002. }
  58003. if (this.preWarmCycles) {
  58004. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58005. this.emitter.computeWorldMatrix(true);
  58006. }
  58007. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58008. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58009. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58010. setTimeout(function () {
  58011. for (var index = 0; index < _this.preWarmCycles; index++) {
  58012. _this.animate(true);
  58013. noiseTextureAsProcedural_1.render();
  58014. }
  58015. });
  58016. });
  58017. }
  58018. else {
  58019. for (var index = 0; index < this.preWarmCycles; index++) {
  58020. this.animate(true);
  58021. }
  58022. }
  58023. }
  58024. };
  58025. /**
  58026. * Stops the particle system.
  58027. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  58028. */
  58029. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58030. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58031. this._stopped = true;
  58032. if (stopSubEmitters) {
  58033. this._stopSubEmitters();
  58034. }
  58035. };
  58036. // animation sheet
  58037. /**
  58038. * Remove all active particles
  58039. */
  58040. ParticleSystem.prototype.reset = function () {
  58041. this._stockParticles = [];
  58042. this._particles = [];
  58043. };
  58044. /**
  58045. * @hidden (for internal use only)
  58046. */
  58047. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58048. var offset = index * this._vertexBufferSize;
  58049. this._vertexData[offset++] = particle.position.x;
  58050. this._vertexData[offset++] = particle.position.y;
  58051. this._vertexData[offset++] = particle.position.z;
  58052. this._vertexData[offset++] = particle.color.r;
  58053. this._vertexData[offset++] = particle.color.g;
  58054. this._vertexData[offset++] = particle.color.b;
  58055. this._vertexData[offset++] = particle.color.a;
  58056. this._vertexData[offset++] = particle.angle;
  58057. this._vertexData[offset++] = particle.scale.x * particle.size;
  58058. this._vertexData[offset++] = particle.scale.y * particle.size;
  58059. if (this._isAnimationSheetEnabled) {
  58060. this._vertexData[offset++] = particle.cellIndex;
  58061. }
  58062. if (!this._isBillboardBased) {
  58063. if (particle._initialDirection) {
  58064. this._vertexData[offset++] = particle._initialDirection.x;
  58065. this._vertexData[offset++] = particle._initialDirection.y;
  58066. this._vertexData[offset++] = particle._initialDirection.z;
  58067. }
  58068. else {
  58069. this._vertexData[offset++] = particle.direction.x;
  58070. this._vertexData[offset++] = particle.direction.y;
  58071. this._vertexData[offset++] = particle.direction.z;
  58072. }
  58073. }
  58074. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58075. this._vertexData[offset++] = particle.direction.x;
  58076. this._vertexData[offset++] = particle.direction.y;
  58077. this._vertexData[offset++] = particle.direction.z;
  58078. }
  58079. if (this._useRampGradients) {
  58080. this._vertexData[offset++] = particle.remapData.x;
  58081. this._vertexData[offset++] = particle.remapData.y;
  58082. this._vertexData[offset++] = particle.remapData.z;
  58083. this._vertexData[offset++] = particle.remapData.w;
  58084. }
  58085. if (!this._useInstancing) {
  58086. if (this._isAnimationSheetEnabled) {
  58087. if (offsetX === 0)
  58088. offsetX = this._epsilon;
  58089. else if (offsetX === 1)
  58090. offsetX = 1 - this._epsilon;
  58091. if (offsetY === 0)
  58092. offsetY = this._epsilon;
  58093. else if (offsetY === 1)
  58094. offsetY = 1 - this._epsilon;
  58095. }
  58096. this._vertexData[offset++] = offsetX;
  58097. this._vertexData[offset++] = offsetY;
  58098. }
  58099. };
  58100. ParticleSystem.prototype._stopSubEmitters = function () {
  58101. if (!this.activeSubSystems) {
  58102. return;
  58103. }
  58104. this.activeSubSystems.forEach(function (subSystem) {
  58105. subSystem.stop(true);
  58106. });
  58107. this.activeSubSystems = new Array();
  58108. };
  58109. ParticleSystem.prototype._removeFromRoot = function () {
  58110. if (!this._rootParticleSystem) {
  58111. return;
  58112. }
  58113. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58114. if (index !== -1) {
  58115. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58116. }
  58117. this._rootParticleSystem = null;
  58118. };
  58119. // End of sub system methods
  58120. ParticleSystem.prototype._update = function (newParticles) {
  58121. var _this = this;
  58122. // Update current
  58123. this._alive = this._particles.length > 0;
  58124. if (this.emitter.position) {
  58125. var emitterMesh = this.emitter;
  58126. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58127. }
  58128. else {
  58129. var emitterPosition = this.emitter;
  58130. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58131. }
  58132. this.updateFunction(this._particles);
  58133. // Add new ones
  58134. var particle;
  58135. var _loop_2 = function () {
  58136. if (this_1._particles.length === this_1._capacity) {
  58137. return "break";
  58138. }
  58139. particle = this_1._createParticle();
  58140. this_1._particles.push(particle);
  58141. // Emitter
  58142. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58143. if (this_1.startPositionFunction) {
  58144. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58145. }
  58146. else {
  58147. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58148. }
  58149. if (this_1.startDirectionFunction) {
  58150. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58151. }
  58152. else {
  58153. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58154. }
  58155. if (emitPower === 0) {
  58156. if (!particle._initialDirection) {
  58157. particle._initialDirection = particle.direction.clone();
  58158. }
  58159. else {
  58160. particle._initialDirection.copyFrom(particle.direction);
  58161. }
  58162. }
  58163. else {
  58164. particle._initialDirection = null;
  58165. }
  58166. particle.direction.scaleInPlace(emitPower);
  58167. // Life time
  58168. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58169. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58170. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58171. var factorGradient1 = currentGradient;
  58172. var factorGradient2 = nextGradient;
  58173. var lifeTime1 = factorGradient1.getFactor();
  58174. var lifeTime2 = factorGradient2.getFactor();
  58175. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58176. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58177. });
  58178. }
  58179. else {
  58180. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58181. }
  58182. // Size
  58183. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58184. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58185. }
  58186. else {
  58187. particle._currentSizeGradient = this_1._sizeGradients[0];
  58188. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58189. particle.size = particle._currentSize1;
  58190. if (this_1._sizeGradients.length > 1) {
  58191. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58192. }
  58193. else {
  58194. particle._currentSize2 = particle._currentSize1;
  58195. }
  58196. }
  58197. // Size and scale
  58198. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58199. // Adjust scale by start size
  58200. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58201. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58202. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58203. if (currentGradient !== _this._currentStartSizeGradient) {
  58204. _this._currentStartSize1 = _this._currentStartSize2;
  58205. _this._currentStartSize2 = nextGradient.getFactor();
  58206. _this._currentStartSizeGradient = currentGradient;
  58207. }
  58208. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58209. particle.scale.scaleInPlace(value);
  58210. });
  58211. }
  58212. // Angle
  58213. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58214. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58215. }
  58216. else {
  58217. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58218. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58219. particle._currentAngularSpeed1 = particle.angularSpeed;
  58220. if (this_1._angularSpeedGradients.length > 1) {
  58221. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58222. }
  58223. else {
  58224. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58225. }
  58226. }
  58227. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58228. // Velocity
  58229. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58230. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58231. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58232. if (this_1._velocityGradients.length > 1) {
  58233. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58234. }
  58235. else {
  58236. particle._currentVelocity2 = particle._currentVelocity1;
  58237. }
  58238. }
  58239. // Limit velocity
  58240. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58241. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58242. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58243. if (this_1._limitVelocityGradients.length > 1) {
  58244. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58245. }
  58246. else {
  58247. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58248. }
  58249. }
  58250. // Drag
  58251. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58252. particle._currentDragGradient = this_1._dragGradients[0];
  58253. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58254. if (this_1._dragGradients.length > 1) {
  58255. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58256. }
  58257. else {
  58258. particle._currentDrag2 = particle._currentDrag1;
  58259. }
  58260. }
  58261. // Color
  58262. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58263. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58264. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58265. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58266. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58267. }
  58268. else {
  58269. particle._currentColorGradient = this_1._colorGradients[0];
  58270. particle._currentColorGradient.getColorToRef(particle.color);
  58271. particle._currentColor1.copyFrom(particle.color);
  58272. if (this_1._colorGradients.length > 1) {
  58273. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58274. }
  58275. else {
  58276. particle._currentColor2.copyFrom(particle.color);
  58277. }
  58278. }
  58279. // Sheet
  58280. if (this_1._isAnimationSheetEnabled) {
  58281. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58282. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58283. }
  58284. // Inherited Velocity
  58285. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58286. // Ramp
  58287. if (this_1._useRampGradients) {
  58288. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58289. }
  58290. // Noise texture coordinates
  58291. if (this_1.noiseTexture) {
  58292. if (particle._randomNoiseCoordinates1) {
  58293. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58294. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58295. }
  58296. else {
  58297. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58298. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58299. }
  58300. }
  58301. // Update the position of the attached sub-emitters to match their attached particle
  58302. particle._inheritParticleInfoToSubEmitters();
  58303. };
  58304. var this_1 = this, step;
  58305. for (var index = 0; index < newParticles; index++) {
  58306. var state_1 = _loop_2();
  58307. if (state_1 === "break")
  58308. break;
  58309. }
  58310. };
  58311. /** @hidden */
  58312. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58313. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58314. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58315. if (useRampGradients === void 0) { useRampGradients = false; }
  58316. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58317. if (isAnimationSheetEnabled) {
  58318. attributeNamesOrOptions.push("cellIndex");
  58319. }
  58320. if (!isBillboardBased) {
  58321. attributeNamesOrOptions.push("direction");
  58322. }
  58323. if (useRampGradients) {
  58324. attributeNamesOrOptions.push("remapData");
  58325. }
  58326. return attributeNamesOrOptions;
  58327. };
  58328. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58329. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58330. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58331. if (isAnimationSheetEnabled) {
  58332. effectCreationOption.push("particlesInfos");
  58333. }
  58334. return effectCreationOption;
  58335. };
  58336. ParticleSystem.prototype._getEffect = function (blendMode) {
  58337. if (this._customEffect) {
  58338. return this._customEffect;
  58339. }
  58340. ;
  58341. var defines = [];
  58342. if (this._scene.clipPlane) {
  58343. defines.push("#define CLIPPLANE");
  58344. }
  58345. if (this._scene.clipPlane2) {
  58346. defines.push("#define CLIPPLANE2");
  58347. }
  58348. if (this._scene.clipPlane3) {
  58349. defines.push("#define CLIPPLANE3");
  58350. }
  58351. if (this._scene.clipPlane4) {
  58352. defines.push("#define CLIPPLANE4");
  58353. }
  58354. if (this._isAnimationSheetEnabled) {
  58355. defines.push("#define ANIMATESHEET");
  58356. }
  58357. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58358. defines.push("#define BLENDMULTIPLYMODE");
  58359. }
  58360. if (this._useRampGradients) {
  58361. defines.push("#define RAMPGRADIENT");
  58362. }
  58363. if (this._isBillboardBased) {
  58364. defines.push("#define BILLBOARD");
  58365. switch (this.billboardMode) {
  58366. case ParticleSystem.BILLBOARDMODE_Y:
  58367. defines.push("#define BILLBOARDY");
  58368. break;
  58369. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58370. defines.push("#define BILLBOARDSTRETCHED");
  58371. break;
  58372. case ParticleSystem.BILLBOARDMODE_ALL:
  58373. default:
  58374. break;
  58375. }
  58376. }
  58377. if (this._imageProcessingConfiguration) {
  58378. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58379. defines.push(this._imageProcessingConfigurationDefines.toString());
  58380. }
  58381. // Effect
  58382. var join = defines.join("\n");
  58383. if (this._cachedDefines !== join) {
  58384. this._cachedDefines = join;
  58385. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58386. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58387. var samplers = ["diffuseSampler", "rampSampler"];
  58388. if (BABYLON.ImageProcessingConfiguration) {
  58389. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58390. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58391. }
  58392. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58393. }
  58394. return this._effect;
  58395. };
  58396. /**
  58397. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58398. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58399. */
  58400. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58401. var _this = this;
  58402. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58403. if (!this._started)
  58404. return;
  58405. if (!preWarmOnly) {
  58406. // Check
  58407. if (!this.isReady())
  58408. return;
  58409. if (this._currentRenderId === this._scene.getRenderId()) {
  58410. return;
  58411. }
  58412. this._currentRenderId = this._scene.getRenderId();
  58413. }
  58414. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58415. // Determine the number of particles we need to create
  58416. var newParticles;
  58417. if (this.manualEmitCount > -1) {
  58418. newParticles = this.manualEmitCount;
  58419. this._newPartsExcess = 0;
  58420. this.manualEmitCount = 0;
  58421. }
  58422. else {
  58423. var rate_1 = this.emitRate;
  58424. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58425. var ratio = this._actualFrame / this.targetStopDuration;
  58426. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58427. if (currentGradient !== _this._currentEmitRateGradient) {
  58428. _this._currentEmitRate1 = _this._currentEmitRate2;
  58429. _this._currentEmitRate2 = nextGradient.getFactor();
  58430. _this._currentEmitRateGradient = currentGradient;
  58431. }
  58432. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58433. });
  58434. }
  58435. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58436. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58437. }
  58438. if (this._newPartsExcess > 1.0) {
  58439. newParticles += this._newPartsExcess >> 0;
  58440. this._newPartsExcess -= this._newPartsExcess >> 0;
  58441. }
  58442. this._alive = false;
  58443. if (!this._stopped) {
  58444. this._actualFrame += this._scaledUpdateSpeed;
  58445. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58446. this.stop();
  58447. }
  58448. else {
  58449. newParticles = 0;
  58450. }
  58451. this._update(newParticles);
  58452. // Stopped?
  58453. if (this._stopped) {
  58454. if (!this._alive) {
  58455. this._started = false;
  58456. if (this.onAnimationEnd) {
  58457. this.onAnimationEnd();
  58458. }
  58459. if (this.disposeOnStop) {
  58460. this._scene._toBeDisposed.push(this);
  58461. }
  58462. }
  58463. }
  58464. if (!preWarmOnly) {
  58465. // Update VBO
  58466. var offset = 0;
  58467. for (var index = 0; index < this._particles.length; index++) {
  58468. var particle = this._particles[index];
  58469. this._appendParticleVertices(offset, particle);
  58470. offset += this._useInstancing ? 1 : 4;
  58471. }
  58472. if (this._vertexBuffer) {
  58473. this._vertexBuffer.update(this._vertexData);
  58474. }
  58475. }
  58476. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58477. this.stop();
  58478. }
  58479. };
  58480. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58481. this._appendParticleVertex(offset++, particle, 0, 0);
  58482. if (!this._useInstancing) {
  58483. this._appendParticleVertex(offset++, particle, 1, 0);
  58484. this._appendParticleVertex(offset++, particle, 1, 1);
  58485. this._appendParticleVertex(offset++, particle, 0, 1);
  58486. }
  58487. };
  58488. /**
  58489. * Rebuilds the particle system.
  58490. */
  58491. ParticleSystem.prototype.rebuild = function () {
  58492. this._createIndexBuffer();
  58493. if (this._vertexBuffer) {
  58494. this._vertexBuffer._rebuild();
  58495. }
  58496. };
  58497. /**
  58498. * Is this system ready to be used/rendered
  58499. * @return true if the system is ready
  58500. */
  58501. ParticleSystem.prototype.isReady = function () {
  58502. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58503. return false;
  58504. }
  58505. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58506. if (!this._getEffect(this.blendMode).isReady()) {
  58507. return false;
  58508. }
  58509. }
  58510. else {
  58511. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58512. return false;
  58513. }
  58514. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58515. return false;
  58516. }
  58517. }
  58518. return true;
  58519. };
  58520. ParticleSystem.prototype._render = function (blendMode) {
  58521. var effect = this._getEffect(blendMode);
  58522. var engine = this._scene.getEngine();
  58523. // Render
  58524. engine.enableEffect(effect);
  58525. var viewMatrix = this._scene.getViewMatrix();
  58526. effect.setTexture("diffuseSampler", this.particleTexture);
  58527. effect.setMatrix("view", viewMatrix);
  58528. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58529. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58530. var baseSize = this.particleTexture.getBaseSize();
  58531. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58532. }
  58533. effect.setVector2("translationPivot", this.translationPivot);
  58534. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  58535. if (this._isBillboardBased) {
  58536. var camera = this._scene.activeCamera;
  58537. effect.setVector3("eyePosition", camera.globalPosition);
  58538. }
  58539. if (this._rampGradientsTexture) {
  58540. effect.setTexture("rampSampler", this._rampGradientsTexture);
  58541. }
  58542. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  58543. var invView = viewMatrix.clone();
  58544. invView.invert();
  58545. effect.setMatrix("invView", invView);
  58546. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  58547. }
  58548. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58549. // image processing
  58550. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  58551. this._imageProcessingConfiguration.bind(effect);
  58552. }
  58553. // Draw order
  58554. switch (blendMode) {
  58555. case ParticleSystem.BLENDMODE_ADD:
  58556. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58557. break;
  58558. case ParticleSystem.BLENDMODE_ONEONE:
  58559. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58560. break;
  58561. case ParticleSystem.BLENDMODE_STANDARD:
  58562. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58563. break;
  58564. case ParticleSystem.BLENDMODE_MULTIPLY:
  58565. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  58566. break;
  58567. }
  58568. if (this._useInstancing) {
  58569. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  58570. }
  58571. else {
  58572. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  58573. }
  58574. return this._particles.length;
  58575. };
  58576. /**
  58577. * Renders the particle system in its current state.
  58578. * @returns the current number of particles
  58579. */
  58580. ParticleSystem.prototype.render = function () {
  58581. // Check
  58582. if (!this.isReady() || !this._particles.length) {
  58583. return 0;
  58584. }
  58585. var engine = this._scene.getEngine();
  58586. engine.setState(false);
  58587. if (this.forceDepthWrite) {
  58588. engine.setDepthWrite(true);
  58589. }
  58590. var outparticles = 0;
  58591. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58592. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  58593. }
  58594. outparticles = this._render(this.blendMode);
  58595. engine.unbindInstanceAttributes();
  58596. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58597. return outparticles;
  58598. };
  58599. /**
  58600. * Disposes the particle system and free the associated resources
  58601. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58602. */
  58603. ParticleSystem.prototype.dispose = function (disposeTexture) {
  58604. if (disposeTexture === void 0) { disposeTexture = true; }
  58605. if (this._vertexBuffer) {
  58606. this._vertexBuffer.dispose();
  58607. this._vertexBuffer = null;
  58608. }
  58609. if (this._spriteBuffer) {
  58610. this._spriteBuffer.dispose();
  58611. this._spriteBuffer = null;
  58612. }
  58613. if (this._indexBuffer) {
  58614. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58615. this._indexBuffer = null;
  58616. }
  58617. if (disposeTexture && this.particleTexture) {
  58618. this.particleTexture.dispose();
  58619. this.particleTexture = null;
  58620. }
  58621. if (disposeTexture && this.noiseTexture) {
  58622. this.noiseTexture.dispose();
  58623. this.noiseTexture = null;
  58624. }
  58625. if (this._rampGradientsTexture) {
  58626. this._rampGradientsTexture.dispose();
  58627. this._rampGradientsTexture = null;
  58628. }
  58629. this._removeFromRoot();
  58630. if (this._subEmitters && this._subEmitters.length) {
  58631. for (var index = 0; index < this._subEmitters.length; index++) {
  58632. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  58633. var subEmitter = _a[_i];
  58634. subEmitter.dispose();
  58635. }
  58636. }
  58637. this._subEmitters = [];
  58638. this.subEmitters = [];
  58639. }
  58640. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  58641. this.emitter.dispose(true);
  58642. }
  58643. // Remove from scene
  58644. var index = this._scene.particleSystems.indexOf(this);
  58645. if (index > -1) {
  58646. this._scene.particleSystems.splice(index, 1);
  58647. }
  58648. this._scene._activeParticleSystems.dispose();
  58649. // Callback
  58650. this.onDisposeObservable.notifyObservers(this);
  58651. this.onDisposeObservable.clear();
  58652. this.reset();
  58653. };
  58654. // Clone
  58655. /**
  58656. * Clones the particle system.
  58657. * @param name The name of the cloned object
  58658. * @param newEmitter The new emitter to use
  58659. * @returns the cloned particle system
  58660. */
  58661. ParticleSystem.prototype.clone = function (name, newEmitter) {
  58662. var custom = null;
  58663. var program = null;
  58664. if (this.customShader != null) {
  58665. program = this.customShader;
  58666. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58667. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58668. }
  58669. else if (this._customEffect) {
  58670. custom = this._customEffect;
  58671. }
  58672. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  58673. result.customShader = program;
  58674. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  58675. if (newEmitter === undefined) {
  58676. newEmitter = this.emitter;
  58677. }
  58678. result.noiseTexture = this.noiseTexture;
  58679. result.emitter = newEmitter;
  58680. if (this.particleTexture) {
  58681. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58682. }
  58683. // Clone gradients
  58684. if (this._colorGradients) {
  58685. this._colorGradients.forEach(function (v) {
  58686. result.addColorGradient(v.gradient, v.color1, v.color2);
  58687. });
  58688. }
  58689. if (this._dragGradients) {
  58690. this._dragGradients.forEach(function (v) {
  58691. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  58692. });
  58693. }
  58694. if (this._angularSpeedGradients) {
  58695. this._angularSpeedGradients.forEach(function (v) {
  58696. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  58697. });
  58698. }
  58699. if (this._emitRateGradients) {
  58700. this._emitRateGradients.forEach(function (v) {
  58701. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  58702. });
  58703. }
  58704. if (this._lifeTimeGradients) {
  58705. this._lifeTimeGradients.forEach(function (v) {
  58706. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  58707. });
  58708. }
  58709. if (this._limitVelocityGradients) {
  58710. this._limitVelocityGradients.forEach(function (v) {
  58711. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  58712. });
  58713. }
  58714. if (this._sizeGradients) {
  58715. this._sizeGradients.forEach(function (v) {
  58716. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  58717. });
  58718. }
  58719. if (this._startSizeGradients) {
  58720. this._startSizeGradients.forEach(function (v) {
  58721. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  58722. });
  58723. }
  58724. if (this._velocityGradients) {
  58725. this._velocityGradients.forEach(function (v) {
  58726. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  58727. });
  58728. }
  58729. if (this._rampGradients) {
  58730. this._rampGradients.forEach(function (v) {
  58731. result.addRampGradient(v.gradient, v.color);
  58732. });
  58733. }
  58734. if (this._colorRemapGradients) {
  58735. this._colorRemapGradients.forEach(function (v) {
  58736. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  58737. });
  58738. }
  58739. if (this._alphaRemapGradients) {
  58740. this._alphaRemapGradients.forEach(function (v) {
  58741. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  58742. });
  58743. }
  58744. if (!this.preventAutoStart) {
  58745. result.start();
  58746. }
  58747. return result;
  58748. };
  58749. /**
  58750. * Serializes the particle system to a JSON object.
  58751. * @returns the JSON object
  58752. */
  58753. ParticleSystem.prototype.serialize = function () {
  58754. var serializationObject = {};
  58755. ParticleSystem._Serialize(serializationObject, this);
  58756. serializationObject.textureMask = this.textureMask.asArray();
  58757. serializationObject.customShader = this.customShader;
  58758. serializationObject.preventAutoStart = this.preventAutoStart;
  58759. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  58760. return serializationObject;
  58761. };
  58762. /** @hidden */
  58763. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  58764. serializationObject.name = particleSystem.name;
  58765. serializationObject.id = particleSystem.id;
  58766. serializationObject.capacity = particleSystem.getCapacity();
  58767. // Emitter
  58768. if (particleSystem.emitter.position) {
  58769. var emitterMesh = particleSystem.emitter;
  58770. serializationObject.emitterId = emitterMesh.id;
  58771. }
  58772. else {
  58773. var emitterPosition = particleSystem.emitter;
  58774. serializationObject.emitter = emitterPosition.asArray();
  58775. }
  58776. // Emitter
  58777. if (particleSystem.particleEmitterType) {
  58778. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  58779. }
  58780. if (particleSystem.particleTexture) {
  58781. serializationObject.textureName = particleSystem.particleTexture.name;
  58782. }
  58783. // Animations
  58784. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  58785. // Particle system
  58786. serializationObject.startDelay = particleSystem.startDelay;
  58787. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  58788. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  58789. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  58790. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  58791. serializationObject.minSize = particleSystem.minSize;
  58792. serializationObject.maxSize = particleSystem.maxSize;
  58793. serializationObject.minScaleX = particleSystem.minScaleX;
  58794. serializationObject.maxScaleX = particleSystem.maxScaleX;
  58795. serializationObject.minScaleY = particleSystem.minScaleY;
  58796. serializationObject.maxScaleY = particleSystem.maxScaleY;
  58797. serializationObject.minEmitPower = particleSystem.minEmitPower;
  58798. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  58799. serializationObject.minLifeTime = particleSystem.minLifeTime;
  58800. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  58801. serializationObject.emitRate = particleSystem.emitRate;
  58802. serializationObject.gravity = particleSystem.gravity.asArray();
  58803. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  58804. serializationObject.color1 = particleSystem.color1.asArray();
  58805. serializationObject.color2 = particleSystem.color2.asArray();
  58806. serializationObject.colorDead = particleSystem.colorDead.asArray();
  58807. serializationObject.updateSpeed = particleSystem.updateSpeed;
  58808. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  58809. serializationObject.blendMode = particleSystem.blendMode;
  58810. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  58811. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  58812. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  58813. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  58814. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  58815. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  58816. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  58817. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  58818. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  58819. var colorGradients = particleSystem.getColorGradients();
  58820. if (colorGradients) {
  58821. serializationObject.colorGradients = [];
  58822. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  58823. var colorGradient = colorGradients_1[_i];
  58824. var serializedGradient = {
  58825. gradient: colorGradient.gradient,
  58826. color1: colorGradient.color1.asArray()
  58827. };
  58828. if (colorGradient.color2) {
  58829. serializedGradient.color2 = colorGradient.color2.asArray();
  58830. }
  58831. serializationObject.colorGradients.push(serializedGradient);
  58832. }
  58833. }
  58834. var rampGradients = particleSystem.getRampGradients();
  58835. if (rampGradients) {
  58836. serializationObject.rampGradients = [];
  58837. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  58838. var rampGradient = rampGradients_1[_a];
  58839. var serializedGradient = {
  58840. gradient: rampGradient.gradient,
  58841. color: rampGradient.color.asArray()
  58842. };
  58843. serializationObject.rampGradients.push(serializedGradient);
  58844. }
  58845. }
  58846. var colorRemapGradients = particleSystem.getColorRemapGradients();
  58847. if (colorRemapGradients) {
  58848. serializationObject.colorRemapGradients = [];
  58849. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  58850. var colorRemapGradient = colorRemapGradients_1[_b];
  58851. var serializedGradient = {
  58852. gradient: colorRemapGradient.gradient,
  58853. factor1: colorRemapGradient.factor1
  58854. };
  58855. if (colorRemapGradient.factor2 !== undefined) {
  58856. serializedGradient.factor2 = colorRemapGradient.factor2;
  58857. }
  58858. serializationObject.colorRemapGradients.push(serializedGradient);
  58859. }
  58860. }
  58861. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  58862. if (alphaRemapGradients) {
  58863. serializationObject.alphaRemapGradients = [];
  58864. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  58865. var alphaRemapGradient = alphaRemapGradients_1[_c];
  58866. var serializedGradient = {
  58867. gradient: alphaRemapGradient.gradient,
  58868. factor1: alphaRemapGradient.factor1
  58869. };
  58870. if (alphaRemapGradient.factor2 !== undefined) {
  58871. serializedGradient.factor2 = alphaRemapGradient.factor2;
  58872. }
  58873. serializationObject.alphaRemapGradients.push(serializedGradient);
  58874. }
  58875. }
  58876. var sizeGradients = particleSystem.getSizeGradients();
  58877. if (sizeGradients) {
  58878. serializationObject.sizeGradients = [];
  58879. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  58880. var sizeGradient = sizeGradients_1[_d];
  58881. var serializedGradient = {
  58882. gradient: sizeGradient.gradient,
  58883. factor1: sizeGradient.factor1
  58884. };
  58885. if (sizeGradient.factor2 !== undefined) {
  58886. serializedGradient.factor2 = sizeGradient.factor2;
  58887. }
  58888. serializationObject.sizeGradients.push(serializedGradient);
  58889. }
  58890. }
  58891. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  58892. if (angularSpeedGradients) {
  58893. serializationObject.angularSpeedGradients = [];
  58894. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  58895. var angularSpeedGradient = angularSpeedGradients_1[_e];
  58896. var serializedGradient = {
  58897. gradient: angularSpeedGradient.gradient,
  58898. factor1: angularSpeedGradient.factor1
  58899. };
  58900. if (angularSpeedGradient.factor2 !== undefined) {
  58901. serializedGradient.factor2 = angularSpeedGradient.factor2;
  58902. }
  58903. serializationObject.angularSpeedGradients.push(serializedGradient);
  58904. }
  58905. }
  58906. var velocityGradients = particleSystem.getVelocityGradients();
  58907. if (velocityGradients) {
  58908. serializationObject.velocityGradients = [];
  58909. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  58910. var velocityGradient = velocityGradients_1[_f];
  58911. var serializedGradient = {
  58912. gradient: velocityGradient.gradient,
  58913. factor1: velocityGradient.factor1
  58914. };
  58915. if (velocityGradient.factor2 !== undefined) {
  58916. serializedGradient.factor2 = velocityGradient.factor2;
  58917. }
  58918. serializationObject.velocityGradients.push(serializedGradient);
  58919. }
  58920. }
  58921. var dragGradients = particleSystem.getDragGradients();
  58922. if (dragGradients) {
  58923. serializationObject.dragyGradients = [];
  58924. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  58925. var dragGradient = dragGradients_1[_g];
  58926. var serializedGradient = {
  58927. gradient: dragGradient.gradient,
  58928. factor1: dragGradient.factor1
  58929. };
  58930. if (dragGradient.factor2 !== undefined) {
  58931. serializedGradient.factor2 = dragGradient.factor2;
  58932. }
  58933. serializationObject.dragGradients.push(serializedGradient);
  58934. }
  58935. }
  58936. var emitRateGradients = particleSystem.getEmitRateGradients();
  58937. if (emitRateGradients) {
  58938. serializationObject.emitRateGradients = [];
  58939. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  58940. var emitRateGradient = emitRateGradients_1[_h];
  58941. var serializedGradient = {
  58942. gradient: emitRateGradient.gradient,
  58943. factor1: emitRateGradient.factor1
  58944. };
  58945. if (emitRateGradient.factor2 !== undefined) {
  58946. serializedGradient.factor2 = emitRateGradient.factor2;
  58947. }
  58948. serializationObject.emitRateGradients.push(serializedGradient);
  58949. }
  58950. }
  58951. var startSizeGradients = particleSystem.getStartSizeGradients();
  58952. if (startSizeGradients) {
  58953. serializationObject.startSizeGradients = [];
  58954. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  58955. var startSizeGradient = startSizeGradients_1[_j];
  58956. var serializedGradient = {
  58957. gradient: startSizeGradient.gradient,
  58958. factor1: startSizeGradient.factor1
  58959. };
  58960. if (startSizeGradient.factor2 !== undefined) {
  58961. serializedGradient.factor2 = startSizeGradient.factor2;
  58962. }
  58963. serializationObject.startSizeGradients.push(serializedGradient);
  58964. }
  58965. }
  58966. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  58967. if (limitVelocityGradients) {
  58968. serializationObject.limitVelocityGradients = [];
  58969. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  58970. var limitVelocityGradient = limitVelocityGradients_1[_k];
  58971. var serializedGradient = {
  58972. gradient: limitVelocityGradient.gradient,
  58973. factor1: limitVelocityGradient.factor1
  58974. };
  58975. if (limitVelocityGradient.factor2 !== undefined) {
  58976. serializedGradient.factor2 = limitVelocityGradient.factor2;
  58977. }
  58978. serializationObject.limitVelocityGradients.push(serializedGradient);
  58979. }
  58980. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  58981. }
  58982. if (particleSystem.noiseTexture) {
  58983. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  58984. }
  58985. };
  58986. /** @hidden */
  58987. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  58988. // Texture
  58989. if (parsedParticleSystem.textureName) {
  58990. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58991. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58992. }
  58993. // Emitter
  58994. if (parsedParticleSystem.emitterId === undefined) {
  58995. particleSystem.emitter = BABYLON.Vector3.Zero();
  58996. }
  58997. else if (parsedParticleSystem.emitterId) {
  58998. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58999. }
  59000. else {
  59001. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59002. }
  59003. // Misc.
  59004. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59005. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59006. }
  59007. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59008. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59009. }
  59010. // Animations
  59011. if (parsedParticleSystem.animations) {
  59012. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59013. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59014. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59015. }
  59016. }
  59017. if (parsedParticleSystem.autoAnimate) {
  59018. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59019. }
  59020. // Particle system
  59021. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59022. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59023. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59024. particleSystem.minSize = parsedParticleSystem.minSize;
  59025. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59026. if (parsedParticleSystem.minScaleX) {
  59027. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59028. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59029. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59030. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59031. }
  59032. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59033. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59034. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59035. }
  59036. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59037. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59038. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59039. }
  59040. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59041. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59042. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59043. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59044. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59045. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59046. if (parsedParticleSystem.noiseStrength) {
  59047. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59048. }
  59049. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59050. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59051. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59052. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59053. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59054. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59055. if (parsedParticleSystem.colorGradients) {
  59056. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59057. var colorGradient = _a[_i];
  59058. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59059. }
  59060. }
  59061. if (parsedParticleSystem.rampGradients) {
  59062. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59063. var rampGradient = _c[_b];
  59064. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  59065. }
  59066. }
  59067. if (parsedParticleSystem.colorRemapGradients) {
  59068. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59069. var colorRemapGradient = _e[_d];
  59070. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59071. }
  59072. }
  59073. if (parsedParticleSystem.alphaRemapGradients) {
  59074. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59075. var alphaRemapGradient = _g[_f];
  59076. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59077. }
  59078. }
  59079. if (parsedParticleSystem.sizeGradients) {
  59080. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59081. var sizeGradient = _j[_h];
  59082. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59083. }
  59084. }
  59085. if (parsedParticleSystem.sizeGradients) {
  59086. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59087. var sizeGradient = _l[_k];
  59088. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59089. }
  59090. }
  59091. if (parsedParticleSystem.angularSpeedGradients) {
  59092. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59093. var angularSpeedGradient = _o[_m];
  59094. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59095. }
  59096. }
  59097. if (parsedParticleSystem.velocityGradients) {
  59098. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59099. var velocityGradient = _q[_p];
  59100. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59101. }
  59102. }
  59103. if (parsedParticleSystem.dragGradients) {
  59104. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59105. var dragGradient = _s[_r];
  59106. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59107. }
  59108. }
  59109. if (parsedParticleSystem.emitRateGradients) {
  59110. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59111. var emitRateGradient = _u[_t];
  59112. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59113. }
  59114. }
  59115. if (parsedParticleSystem.startSizeGradients) {
  59116. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59117. var startSizeGradient = _w[_v];
  59118. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59119. }
  59120. }
  59121. if (parsedParticleSystem.limitVelocityGradients) {
  59122. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  59123. var limitVelocityGradient = _y[_x];
  59124. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59125. }
  59126. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59127. }
  59128. if (parsedParticleSystem.noiseTexture) {
  59129. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59130. }
  59131. // Emitter
  59132. var emitterType;
  59133. if (parsedParticleSystem.particleEmitterType) {
  59134. switch (parsedParticleSystem.particleEmitterType.type) {
  59135. case "SphereParticleEmitter":
  59136. emitterType = new BABYLON.SphereParticleEmitter();
  59137. break;
  59138. case "SphereDirectedParticleEmitter":
  59139. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59140. break;
  59141. case "ConeEmitter":
  59142. case "ConeParticleEmitter":
  59143. emitterType = new BABYLON.ConeParticleEmitter();
  59144. break;
  59145. case "BoxEmitter":
  59146. case "BoxParticleEmitter":
  59147. default:
  59148. emitterType = new BABYLON.BoxParticleEmitter();
  59149. break;
  59150. }
  59151. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59152. }
  59153. else {
  59154. emitterType = new BABYLON.BoxParticleEmitter();
  59155. emitterType.parse(parsedParticleSystem);
  59156. }
  59157. particleSystem.particleEmitterType = emitterType;
  59158. // Animation sheet
  59159. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59160. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59161. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59162. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59163. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59164. };
  59165. /**
  59166. * Parses a JSON object to create a particle system.
  59167. * @param parsedParticleSystem The JSON object to parse
  59168. * @param scene The scene to create the particle system in
  59169. * @param rootUrl The root url to use to load external dependencies like texture
  59170. * @returns the Parsed particle system
  59171. */
  59172. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  59173. var name = parsedParticleSystem.name;
  59174. var custom = null;
  59175. var program = null;
  59176. if (parsedParticleSystem.customShader) {
  59177. program = parsedParticleSystem.customShader;
  59178. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59179. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59180. }
  59181. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59182. particleSystem.customShader = program;
  59183. if (parsedParticleSystem.id) {
  59184. particleSystem.id = parsedParticleSystem.id;
  59185. }
  59186. // Auto start
  59187. if (parsedParticleSystem.preventAutoStart) {
  59188. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59189. }
  59190. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59191. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59192. if (!particleSystem.preventAutoStart) {
  59193. particleSystem.start();
  59194. }
  59195. return particleSystem;
  59196. };
  59197. /**
  59198. * Billboard mode will only apply to Y axis
  59199. */
  59200. ParticleSystem.BILLBOARDMODE_Y = 2;
  59201. /**
  59202. * Billboard mode will apply to all axes
  59203. */
  59204. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59205. /**
  59206. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59207. */
  59208. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59209. return ParticleSystem;
  59210. }(BABYLON.BaseParticleSystem));
  59211. BABYLON.ParticleSystem = ParticleSystem;
  59212. })(BABYLON || (BABYLON = {}));
  59213. //# sourceMappingURL=babylon.particleSystem.js.map
  59214. var BABYLON;
  59215. (function (BABYLON) {
  59216. /**
  59217. * Particle emitter emitting particles from the inside of a box.
  59218. * It emits the particles randomly between 2 given directions.
  59219. */
  59220. var BoxParticleEmitter = /** @class */ (function () {
  59221. /**
  59222. * Creates a new instance BoxParticleEmitter
  59223. */
  59224. function BoxParticleEmitter() {
  59225. /**
  59226. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59227. */
  59228. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59229. /**
  59230. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59231. */
  59232. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59233. /**
  59234. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  59235. */
  59236. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59237. /**
  59238. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  59239. */
  59240. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59241. }
  59242. /**
  59243. * Called by the particle System when the direction is computed for the created particle.
  59244. * @param worldMatrix is the world matrix of the particle system
  59245. * @param directionToUpdate is the direction vector to update with the result
  59246. * @param particle is the particle we are computed the direction for
  59247. */
  59248. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59249. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59250. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59251. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59252. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59253. };
  59254. /**
  59255. * Called by the particle System when the position is computed for the created particle.
  59256. * @param worldMatrix is the world matrix of the particle system
  59257. * @param positionToUpdate is the position vector to update with the result
  59258. * @param particle is the particle we are computed the position for
  59259. */
  59260. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59261. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59262. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59263. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59264. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59265. };
  59266. /**
  59267. * Clones the current emitter and returns a copy of it
  59268. * @returns the new emitter
  59269. */
  59270. BoxParticleEmitter.prototype.clone = function () {
  59271. var newOne = new BoxParticleEmitter();
  59272. BABYLON.Tools.DeepCopy(this, newOne);
  59273. return newOne;
  59274. };
  59275. /**
  59276. * Called by the GPUParticleSystem to setup the update shader
  59277. * @param effect defines the update shader
  59278. */
  59279. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59280. effect.setVector3("direction1", this.direction1);
  59281. effect.setVector3("direction2", this.direction2);
  59282. effect.setVector3("minEmitBox", this.minEmitBox);
  59283. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59284. };
  59285. /**
  59286. * Returns a string to use to update the GPU particles update shader
  59287. * @returns a string containng the defines string
  59288. */
  59289. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59290. return "#define BOXEMITTER";
  59291. };
  59292. /**
  59293. * Returns the string "BoxParticleEmitter"
  59294. * @returns a string containing the class name
  59295. */
  59296. BoxParticleEmitter.prototype.getClassName = function () {
  59297. return "BoxParticleEmitter";
  59298. };
  59299. /**
  59300. * Serializes the particle system to a JSON object.
  59301. * @returns the JSON object
  59302. */
  59303. BoxParticleEmitter.prototype.serialize = function () {
  59304. var serializationObject = {};
  59305. serializationObject.type = this.getClassName();
  59306. serializationObject.direction1 = this.direction1.asArray();
  59307. serializationObject.direction2 = this.direction2.asArray();
  59308. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59309. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59310. return serializationObject;
  59311. };
  59312. /**
  59313. * Parse properties from a JSON object
  59314. * @param serializationObject defines the JSON object
  59315. */
  59316. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59317. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59318. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59319. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59320. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59321. };
  59322. return BoxParticleEmitter;
  59323. }());
  59324. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59325. })(BABYLON || (BABYLON = {}));
  59326. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59327. var BABYLON;
  59328. (function (BABYLON) {
  59329. /**
  59330. * Particle emitter emitting particles from the inside of a cylinder.
  59331. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59332. */
  59333. var CylinderParticleEmitter = /** @class */ (function () {
  59334. /**
  59335. * Creates a new instance CylinderParticleEmitter
  59336. * @param radius the radius of the emission cylinder (1 by default)
  59337. * @param height the height of the emission cylinder (1 by default)
  59338. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59339. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59340. */
  59341. function CylinderParticleEmitter(
  59342. /**
  59343. * The radius of the emission cylinder.
  59344. */
  59345. radius,
  59346. /**
  59347. * The height of the emission cylinder.
  59348. */
  59349. height,
  59350. /**
  59351. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59352. */
  59353. radiusRange,
  59354. /**
  59355. * How much to randomize the particle direction [0-1].
  59356. */
  59357. directionRandomizer) {
  59358. if (radius === void 0) { radius = 1; }
  59359. if (height === void 0) { height = 1; }
  59360. if (radiusRange === void 0) { radiusRange = 1; }
  59361. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59362. this.radius = radius;
  59363. this.height = height;
  59364. this.radiusRange = radiusRange;
  59365. this.directionRandomizer = directionRandomizer;
  59366. }
  59367. /**
  59368. * Called by the particle System when the direction is computed for the created particle.
  59369. * @param worldMatrix is the world matrix of the particle system
  59370. * @param directionToUpdate is the direction vector to update with the result
  59371. * @param particle is the particle we are computed the direction for
  59372. */
  59373. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59374. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59375. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59376. var angle = Math.atan2(direction.x, direction.z);
  59377. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59378. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59379. direction.x = Math.sin(angle);
  59380. direction.z = Math.cos(angle);
  59381. direction.normalize();
  59382. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59383. };
  59384. /**
  59385. * Called by the particle System when the position is computed for the created particle.
  59386. * @param worldMatrix is the world matrix of the particle system
  59387. * @param positionToUpdate is the position vector to update with the result
  59388. * @param particle is the particle we are computed the position for
  59389. */
  59390. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59391. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59392. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59393. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59394. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59395. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59396. var xPos = positionRadius * Math.cos(angle);
  59397. var zPos = positionRadius * Math.sin(angle);
  59398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59399. };
  59400. /**
  59401. * Clones the current emitter and returns a copy of it
  59402. * @returns the new emitter
  59403. */
  59404. CylinderParticleEmitter.prototype.clone = function () {
  59405. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59406. BABYLON.Tools.DeepCopy(this, newOne);
  59407. return newOne;
  59408. };
  59409. /**
  59410. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59411. * @param effect defines the update shader
  59412. */
  59413. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59414. effect.setFloat("radius", this.radius);
  59415. effect.setFloat("height", this.height);
  59416. effect.setFloat("radiusRange", this.radiusRange);
  59417. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59418. };
  59419. /**
  59420. * Returns a string to use to update the GPU particles update shader
  59421. * @returns a string containng the defines string
  59422. */
  59423. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59424. return "#define CYLINDEREMITTER";
  59425. };
  59426. /**
  59427. * Returns the string "CylinderParticleEmitter"
  59428. * @returns a string containing the class name
  59429. */
  59430. CylinderParticleEmitter.prototype.getClassName = function () {
  59431. return "CylinderParticleEmitter";
  59432. };
  59433. /**
  59434. * Serializes the particle system to a JSON object.
  59435. * @returns the JSON object
  59436. */
  59437. CylinderParticleEmitter.prototype.serialize = function () {
  59438. var serializationObject = {};
  59439. serializationObject.type = this.getClassName();
  59440. serializationObject.radius = this.radius;
  59441. serializationObject.height = this.height;
  59442. serializationObject.radiusRange = this.radiusRange;
  59443. serializationObject.directionRandomizer = this.directionRandomizer;
  59444. return serializationObject;
  59445. };
  59446. /**
  59447. * Parse properties from a JSON object
  59448. * @param serializationObject defines the JSON object
  59449. */
  59450. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59451. this.radius = serializationObject.radius;
  59452. this.height = serializationObject.height;
  59453. this.radiusRange = serializationObject.radiusRange;
  59454. this.directionRandomizer = serializationObject.directionRandomizer;
  59455. };
  59456. return CylinderParticleEmitter;
  59457. }());
  59458. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  59459. /**
  59460. * Particle emitter emitting particles from the inside of a cylinder.
  59461. * It emits the particles randomly between two vectors.
  59462. */
  59463. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  59464. __extends(CylinderDirectedParticleEmitter, _super);
  59465. /**
  59466. * Creates a new instance CylinderDirectedParticleEmitter
  59467. * @param radius the radius of the emission cylinder (1 by default)
  59468. * @param height the height of the emission cylinder (1 by default)
  59469. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59470. * @param direction1 the min limit of the emission direction (up vector by default)
  59471. * @param direction2 the max limit of the emission direction (up vector by default)
  59472. */
  59473. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  59474. /**
  59475. * The min limit of the emission direction.
  59476. */
  59477. direction1,
  59478. /**
  59479. * The max limit of the emission direction.
  59480. */
  59481. direction2) {
  59482. if (radius === void 0) { radius = 1; }
  59483. if (height === void 0) { height = 1; }
  59484. if (radiusRange === void 0) { radiusRange = 1; }
  59485. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59486. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59487. var _this = _super.call(this, radius, height, radiusRange) || this;
  59488. _this.direction1 = direction1;
  59489. _this.direction2 = direction2;
  59490. return _this;
  59491. }
  59492. /**
  59493. * Called by the particle System when the direction is computed for the created particle.
  59494. * @param worldMatrix is the world matrix of the particle system
  59495. * @param directionToUpdate is the direction vector to update with the result
  59496. * @param particle is the particle we are computed the direction for
  59497. */
  59498. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59499. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59500. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59501. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59502. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59503. };
  59504. /**
  59505. * Clones the current emitter and returns a copy of it
  59506. * @returns the new emitter
  59507. */
  59508. CylinderDirectedParticleEmitter.prototype.clone = function () {
  59509. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  59510. BABYLON.Tools.DeepCopy(this, newOne);
  59511. return newOne;
  59512. };
  59513. /**
  59514. * Called by the GPUParticleSystem to setup the update shader
  59515. * @param effect defines the update shader
  59516. */
  59517. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59518. effect.setFloat("radius", this.radius);
  59519. effect.setFloat("height", this.height);
  59520. effect.setFloat("radiusRange", this.radiusRange);
  59521. effect.setVector3("direction1", this.direction1);
  59522. effect.setVector3("direction2", this.direction2);
  59523. };
  59524. /**
  59525. * Returns a string to use to update the GPU particles update shader
  59526. * @returns a string containng the defines string
  59527. */
  59528. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59529. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  59530. };
  59531. /**
  59532. * Returns the string "CylinderDirectedParticleEmitter"
  59533. * @returns a string containing the class name
  59534. */
  59535. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  59536. return "CylinderDirectedParticleEmitter";
  59537. };
  59538. /**
  59539. * Serializes the particle system to a JSON object.
  59540. * @returns the JSON object
  59541. */
  59542. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  59543. var serializationObject = _super.prototype.serialize.call(this);
  59544. serializationObject.direction1 = this.direction1.asArray();
  59545. serializationObject.direction2 = this.direction2.asArray();
  59546. return serializationObject;
  59547. };
  59548. /**
  59549. * Parse properties from a JSON object
  59550. * @param serializationObject defines the JSON object
  59551. */
  59552. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59553. _super.prototype.parse.call(this, serializationObject);
  59554. this.direction1.copyFrom(serializationObject.direction1);
  59555. this.direction2.copyFrom(serializationObject.direction2);
  59556. };
  59557. return CylinderDirectedParticleEmitter;
  59558. }(CylinderParticleEmitter));
  59559. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  59560. })(BABYLON || (BABYLON = {}));
  59561. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  59562. var BABYLON;
  59563. (function (BABYLON) {
  59564. /**
  59565. * Particle emitter emitting particles from the inside of a cone.
  59566. * It emits the particles alongside the cone volume from the base to the particle.
  59567. * The emission direction might be randomized.
  59568. */
  59569. var ConeParticleEmitter = /** @class */ (function () {
  59570. /**
  59571. * Creates a new instance ConeParticleEmitter
  59572. * @param radius the radius of the emission cone (1 by default)
  59573. * @param angles the cone base angle (PI by default)
  59574. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  59575. */
  59576. function ConeParticleEmitter(radius, angle,
  59577. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  59578. directionRandomizer) {
  59579. if (radius === void 0) { radius = 1; }
  59580. if (angle === void 0) { angle = Math.PI; }
  59581. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59582. this.directionRandomizer = directionRandomizer;
  59583. /**
  59584. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  59585. */
  59586. this.radiusRange = 1;
  59587. /**
  59588. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  59589. */
  59590. this.heightRange = 1;
  59591. /**
  59592. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  59593. */
  59594. this.emitFromSpawnPointOnly = false;
  59595. this.angle = angle;
  59596. this.radius = radius;
  59597. }
  59598. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  59599. /**
  59600. * Gets or sets the radius of the emission cone
  59601. */
  59602. get: function () {
  59603. return this._radius;
  59604. },
  59605. set: function (value) {
  59606. this._radius = value;
  59607. this._buildHeight();
  59608. },
  59609. enumerable: true,
  59610. configurable: true
  59611. });
  59612. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  59613. /**
  59614. * Gets or sets the angle of the emission cone
  59615. */
  59616. get: function () {
  59617. return this._angle;
  59618. },
  59619. set: function (value) {
  59620. this._angle = value;
  59621. this._buildHeight();
  59622. },
  59623. enumerable: true,
  59624. configurable: true
  59625. });
  59626. ConeParticleEmitter.prototype._buildHeight = function () {
  59627. if (this._angle !== 0) {
  59628. this._height = this._radius / Math.tan(this._angle / 2);
  59629. }
  59630. else {
  59631. this._height = 1;
  59632. }
  59633. };
  59634. /**
  59635. * Called by the particle System when the direction is computed for the created particle.
  59636. * @param worldMatrix is the world matrix of the particle system
  59637. * @param directionToUpdate is the direction vector to update with the result
  59638. * @param particle is the particle we are computed the direction for
  59639. */
  59640. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59641. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  59642. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  59643. }
  59644. else {
  59645. // measure the direction Vector from the emitter to the particle.
  59646. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59647. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59648. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59649. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59650. direction.x += randX;
  59651. direction.y += randY;
  59652. direction.z += randZ;
  59653. direction.normalize();
  59654. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59655. }
  59656. };
  59657. /**
  59658. * Called by the particle System when the position is computed for the created particle.
  59659. * @param worldMatrix is the world matrix of the particle system
  59660. * @param positionToUpdate is the position vector to update with the result
  59661. * @param particle is the particle we are computed the position for
  59662. */
  59663. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59664. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  59665. var h;
  59666. if (!this.emitFromSpawnPointOnly) {
  59667. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  59668. // Better distribution in a cone at normal angles.
  59669. h = 1 - h * h;
  59670. }
  59671. else {
  59672. h = 0.0001;
  59673. }
  59674. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  59675. radius = radius * h;
  59676. var randX = radius * Math.sin(s);
  59677. var randZ = radius * Math.cos(s);
  59678. var randY = h * this._height;
  59679. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59680. };
  59681. /**
  59682. * Clones the current emitter and returns a copy of it
  59683. * @returns the new emitter
  59684. */
  59685. ConeParticleEmitter.prototype.clone = function () {
  59686. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  59687. BABYLON.Tools.DeepCopy(this, newOne);
  59688. return newOne;
  59689. };
  59690. /**
  59691. * Called by the GPUParticleSystem to setup the update shader
  59692. * @param effect defines the update shader
  59693. */
  59694. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  59695. effect.setFloat2("radius", this._radius, this.radiusRange);
  59696. effect.setFloat("coneAngle", this._angle);
  59697. effect.setFloat2("height", this._height, this.heightRange);
  59698. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59699. };
  59700. /**
  59701. * Returns a string to use to update the GPU particles update shader
  59702. * @returns a string containng the defines string
  59703. */
  59704. ConeParticleEmitter.prototype.getEffectDefines = function () {
  59705. var defines = "#define CONEEMITTER";
  59706. if (this.emitFromSpawnPointOnly) {
  59707. defines += "\n#define CONEEMITTERSPAWNPOINT";
  59708. }
  59709. return defines;
  59710. };
  59711. /**
  59712. * Returns the string "ConeParticleEmitter"
  59713. * @returns a string containing the class name
  59714. */
  59715. ConeParticleEmitter.prototype.getClassName = function () {
  59716. return "ConeParticleEmitter";
  59717. };
  59718. /**
  59719. * Serializes the particle system to a JSON object.
  59720. * @returns the JSON object
  59721. */
  59722. ConeParticleEmitter.prototype.serialize = function () {
  59723. var serializationObject = {};
  59724. serializationObject.type = this.getClassName();
  59725. serializationObject.radius = this._radius;
  59726. serializationObject.angle = this._angle;
  59727. serializationObject.directionRandomizer = this.directionRandomizer;
  59728. return serializationObject;
  59729. };
  59730. /**
  59731. * Parse properties from a JSON object
  59732. * @param serializationObject defines the JSON object
  59733. */
  59734. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  59735. this.radius = serializationObject.radius;
  59736. this.angle = serializationObject.angle;
  59737. this.directionRandomizer = serializationObject.directionRandomizer;
  59738. };
  59739. return ConeParticleEmitter;
  59740. }());
  59741. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  59742. })(BABYLON || (BABYLON = {}));
  59743. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  59744. var BABYLON;
  59745. (function (BABYLON) {
  59746. /**
  59747. * Particle emitter emitting particles from the inside of a sphere.
  59748. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  59749. */
  59750. var SphereParticleEmitter = /** @class */ (function () {
  59751. /**
  59752. * Creates a new instance SphereParticleEmitter
  59753. * @param radius the radius of the emission sphere (1 by default)
  59754. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59755. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59756. */
  59757. function SphereParticleEmitter(
  59758. /**
  59759. * The radius of the emission sphere.
  59760. */
  59761. radius,
  59762. /**
  59763. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59764. */
  59765. radiusRange,
  59766. /**
  59767. * How much to randomize the particle direction [0-1].
  59768. */
  59769. directionRandomizer) {
  59770. if (radius === void 0) { radius = 1; }
  59771. if (radiusRange === void 0) { radiusRange = 1; }
  59772. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59773. this.radius = radius;
  59774. this.radiusRange = radiusRange;
  59775. this.directionRandomizer = directionRandomizer;
  59776. }
  59777. /**
  59778. * Called by the particle System when the direction is computed for the created particle.
  59779. * @param worldMatrix is the world matrix of the particle system
  59780. * @param directionToUpdate is the direction vector to update with the result
  59781. * @param particle is the particle we are computed the direction for
  59782. */
  59783. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59784. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59785. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59786. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59787. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59788. direction.x += randX;
  59789. direction.y += randY;
  59790. direction.z += randZ;
  59791. direction.normalize();
  59792. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59793. };
  59794. /**
  59795. * Called by the particle System when the position is computed for the created particle.
  59796. * @param worldMatrix is the world matrix of the particle system
  59797. * @param positionToUpdate is the position vector to update with the result
  59798. * @param particle is the particle we are computed the position for
  59799. */
  59800. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59801. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  59802. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  59803. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59804. var theta = Math.acos(2 * v - 1);
  59805. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  59806. var randY = randRadius * Math.cos(theta);
  59807. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  59808. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59809. };
  59810. /**
  59811. * Clones the current emitter and returns a copy of it
  59812. * @returns the new emitter
  59813. */
  59814. SphereParticleEmitter.prototype.clone = function () {
  59815. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  59816. BABYLON.Tools.DeepCopy(this, newOne);
  59817. return newOne;
  59818. };
  59819. /**
  59820. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59821. * @param effect defines the update shader
  59822. */
  59823. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  59824. effect.setFloat("radius", this.radius);
  59825. effect.setFloat("radiusRange", this.radiusRange);
  59826. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59827. };
  59828. /**
  59829. * Returns a string to use to update the GPU particles update shader
  59830. * @returns a string containng the defines string
  59831. */
  59832. SphereParticleEmitter.prototype.getEffectDefines = function () {
  59833. return "#define SPHEREEMITTER";
  59834. };
  59835. /**
  59836. * Returns the string "SphereParticleEmitter"
  59837. * @returns a string containing the class name
  59838. */
  59839. SphereParticleEmitter.prototype.getClassName = function () {
  59840. return "SphereParticleEmitter";
  59841. };
  59842. /**
  59843. * Serializes the particle system to a JSON object.
  59844. * @returns the JSON object
  59845. */
  59846. SphereParticleEmitter.prototype.serialize = function () {
  59847. var serializationObject = {};
  59848. serializationObject.type = this.getClassName();
  59849. serializationObject.radius = this.radius;
  59850. serializationObject.radiusRange = this.radiusRange;
  59851. serializationObject.directionRandomizer = this.directionRandomizer;
  59852. return serializationObject;
  59853. };
  59854. /**
  59855. * Parse properties from a JSON object
  59856. * @param serializationObject defines the JSON object
  59857. */
  59858. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  59859. this.radius = serializationObject.radius;
  59860. this.radiusRange = serializationObject.radiusRange;
  59861. this.directionRandomizer = serializationObject.directionRandomizer;
  59862. };
  59863. return SphereParticleEmitter;
  59864. }());
  59865. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  59866. /**
  59867. * Particle emitter emitting particles from the inside of a sphere.
  59868. * It emits the particles randomly between two vectors.
  59869. */
  59870. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  59871. __extends(SphereDirectedParticleEmitter, _super);
  59872. /**
  59873. * Creates a new instance SphereDirectedParticleEmitter
  59874. * @param radius the radius of the emission sphere (1 by default)
  59875. * @param direction1 the min limit of the emission direction (up vector by default)
  59876. * @param direction2 the max limit of the emission direction (up vector by default)
  59877. */
  59878. function SphereDirectedParticleEmitter(radius,
  59879. /**
  59880. * The min limit of the emission direction.
  59881. */
  59882. direction1,
  59883. /**
  59884. * The max limit of the emission direction.
  59885. */
  59886. direction2) {
  59887. if (radius === void 0) { radius = 1; }
  59888. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59889. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59890. var _this = _super.call(this, radius) || this;
  59891. _this.direction1 = direction1;
  59892. _this.direction2 = direction2;
  59893. return _this;
  59894. }
  59895. /**
  59896. * Called by the particle System when the direction is computed for the created particle.
  59897. * @param worldMatrix is the world matrix of the particle system
  59898. * @param directionToUpdate is the direction vector to update with the result
  59899. * @param particle is the particle we are computed the direction for
  59900. */
  59901. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59902. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59903. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59904. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59905. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59906. };
  59907. /**
  59908. * Clones the current emitter and returns a copy of it
  59909. * @returns the new emitter
  59910. */
  59911. SphereDirectedParticleEmitter.prototype.clone = function () {
  59912. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  59913. BABYLON.Tools.DeepCopy(this, newOne);
  59914. return newOne;
  59915. };
  59916. /**
  59917. * Called by the GPUParticleSystem to setup the update shader
  59918. * @param effect defines the update shader
  59919. */
  59920. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59921. effect.setFloat("radius", this.radius);
  59922. effect.setFloat("radiusRange", this.radiusRange);
  59923. effect.setVector3("direction1", this.direction1);
  59924. effect.setVector3("direction2", this.direction2);
  59925. };
  59926. /**
  59927. * Returns a string to use to update the GPU particles update shader
  59928. * @returns a string containng the defines string
  59929. */
  59930. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59931. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  59932. };
  59933. /**
  59934. * Returns the string "SphereDirectedParticleEmitter"
  59935. * @returns a string containing the class name
  59936. */
  59937. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  59938. return "SphereDirectedParticleEmitter";
  59939. };
  59940. /**
  59941. * Serializes the particle system to a JSON object.
  59942. * @returns the JSON object
  59943. */
  59944. SphereDirectedParticleEmitter.prototype.serialize = function () {
  59945. var serializationObject = _super.prototype.serialize.call(this);
  59946. serializationObject.direction1 = this.direction1.asArray();
  59947. serializationObject.direction2 = this.direction2.asArray();
  59948. return serializationObject;
  59949. };
  59950. /**
  59951. * Parse properties from a JSON object
  59952. * @param serializationObject defines the JSON object
  59953. */
  59954. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59955. _super.prototype.parse.call(this, serializationObject);
  59956. this.direction1.copyFrom(serializationObject.direction1);
  59957. this.direction2.copyFrom(serializationObject.direction2);
  59958. };
  59959. return SphereDirectedParticleEmitter;
  59960. }(SphereParticleEmitter));
  59961. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  59962. })(BABYLON || (BABYLON = {}));
  59963. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  59964. var BABYLON;
  59965. (function (BABYLON) {
  59966. /**
  59967. * Particle emitter emitting particles from the inside of a hemisphere.
  59968. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  59969. */
  59970. var HemisphericParticleEmitter = /** @class */ (function () {
  59971. /**
  59972. * Creates a new instance HemisphericParticleEmitter
  59973. * @param radius the radius of the emission hemisphere (1 by default)
  59974. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59975. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59976. */
  59977. function HemisphericParticleEmitter(
  59978. /**
  59979. * The radius of the emission hemisphere.
  59980. */
  59981. radius,
  59982. /**
  59983. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59984. */
  59985. radiusRange,
  59986. /**
  59987. * How much to randomize the particle direction [0-1].
  59988. */
  59989. directionRandomizer) {
  59990. if (radius === void 0) { radius = 1; }
  59991. if (radiusRange === void 0) { radiusRange = 1; }
  59992. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59993. this.radius = radius;
  59994. this.radiusRange = radiusRange;
  59995. this.directionRandomizer = directionRandomizer;
  59996. }
  59997. /**
  59998. * Called by the particle System when the direction is computed for the created particle.
  59999. * @param worldMatrix is the world matrix of the particle system
  60000. * @param directionToUpdate is the direction vector to update with the result
  60001. * @param particle is the particle we are computed the direction for
  60002. */
  60003. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60004. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60005. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60006. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60007. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60008. direction.x += randX;
  60009. direction.y += randY;
  60010. direction.z += randZ;
  60011. direction.normalize();
  60012. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60013. };
  60014. /**
  60015. * Called by the particle System when the position is computed for the created particle.
  60016. * @param worldMatrix is the world matrix of the particle system
  60017. * @param positionToUpdate is the position vector to update with the result
  60018. * @param particle is the particle we are computed the position for
  60019. */
  60020. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60021. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60022. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60023. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60024. var theta = Math.acos(2 * v - 1);
  60025. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60026. var randY = randRadius * Math.cos(theta);
  60027. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60028. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60029. };
  60030. /**
  60031. * Clones the current emitter and returns a copy of it
  60032. * @returns the new emitter
  60033. */
  60034. HemisphericParticleEmitter.prototype.clone = function () {
  60035. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60036. BABYLON.Tools.DeepCopy(this, newOne);
  60037. return newOne;
  60038. };
  60039. /**
  60040. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60041. * @param effect defines the update shader
  60042. */
  60043. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60044. effect.setFloat("radius", this.radius);
  60045. effect.setFloat("radiusRange", this.radiusRange);
  60046. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60047. };
  60048. /**
  60049. * Returns a string to use to update the GPU particles update shader
  60050. * @returns a string containng the defines string
  60051. */
  60052. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60053. return "#define HEMISPHERICEMITTER";
  60054. };
  60055. /**
  60056. * Returns the string "HemisphericParticleEmitter"
  60057. * @returns a string containing the class name
  60058. */
  60059. HemisphericParticleEmitter.prototype.getClassName = function () {
  60060. return "HemisphericParticleEmitter";
  60061. };
  60062. /**
  60063. * Serializes the particle system to a JSON object.
  60064. * @returns the JSON object
  60065. */
  60066. HemisphericParticleEmitter.prototype.serialize = function () {
  60067. var serializationObject = {};
  60068. serializationObject.type = this.getClassName();
  60069. serializationObject.radius = this.radius;
  60070. serializationObject.radiusRange = this.radiusRange;
  60071. serializationObject.directionRandomizer = this.directionRandomizer;
  60072. return serializationObject;
  60073. };
  60074. /**
  60075. * Parse properties from a JSON object
  60076. * @param serializationObject defines the JSON object
  60077. */
  60078. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60079. this.radius = serializationObject.radius;
  60080. this.radiusRange = serializationObject.radiusRange;
  60081. this.directionRandomizer = serializationObject.directionRandomizer;
  60082. };
  60083. return HemisphericParticleEmitter;
  60084. }());
  60085. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60086. })(BABYLON || (BABYLON = {}));
  60087. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60088. var BABYLON;
  60089. (function (BABYLON) {
  60090. /**
  60091. * Particle emitter emitting particles from a point.
  60092. * It emits the particles randomly between 2 given directions.
  60093. */
  60094. var PointParticleEmitter = /** @class */ (function () {
  60095. /**
  60096. * Creates a new instance PointParticleEmitter
  60097. */
  60098. function PointParticleEmitter() {
  60099. /**
  60100. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60101. */
  60102. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60103. /**
  60104. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60105. */
  60106. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60107. }
  60108. /**
  60109. * Called by the particle System when the direction is computed for the created particle.
  60110. * @param worldMatrix is the world matrix of the particle system
  60111. * @param directionToUpdate is the direction vector to update with the result
  60112. * @param particle is the particle we are computed the direction for
  60113. */
  60114. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60115. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60116. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60117. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60118. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60119. };
  60120. /**
  60121. * Called by the particle System when the position is computed for the created particle.
  60122. * @param worldMatrix is the world matrix of the particle system
  60123. * @param positionToUpdate is the position vector to update with the result
  60124. * @param particle is the particle we are computed the position for
  60125. */
  60126. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60127. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60128. };
  60129. /**
  60130. * Clones the current emitter and returns a copy of it
  60131. * @returns the new emitter
  60132. */
  60133. PointParticleEmitter.prototype.clone = function () {
  60134. var newOne = new PointParticleEmitter();
  60135. BABYLON.Tools.DeepCopy(this, newOne);
  60136. return newOne;
  60137. };
  60138. /**
  60139. * Called by the GPUParticleSystem to setup the update shader
  60140. * @param effect defines the update shader
  60141. */
  60142. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60143. effect.setVector3("direction1", this.direction1);
  60144. effect.setVector3("direction2", this.direction2);
  60145. };
  60146. /**
  60147. * Returns a string to use to update the GPU particles update shader
  60148. * @returns a string containng the defines string
  60149. */
  60150. PointParticleEmitter.prototype.getEffectDefines = function () {
  60151. return "#define POINTEMITTER";
  60152. };
  60153. /**
  60154. * Returns the string "PointParticleEmitter"
  60155. * @returns a string containing the class name
  60156. */
  60157. PointParticleEmitter.prototype.getClassName = function () {
  60158. return "PointParticleEmitter";
  60159. };
  60160. /**
  60161. * Serializes the particle system to a JSON object.
  60162. * @returns the JSON object
  60163. */
  60164. PointParticleEmitter.prototype.serialize = function () {
  60165. var serializationObject = {};
  60166. serializationObject.type = this.getClassName();
  60167. serializationObject.direction1 = this.direction1.asArray();
  60168. serializationObject.direction2 = this.direction2.asArray();
  60169. return serializationObject;
  60170. };
  60171. /**
  60172. * Parse properties from a JSON object
  60173. * @param serializationObject defines the JSON object
  60174. */
  60175. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60176. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60177. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60178. };
  60179. return PointParticleEmitter;
  60180. }());
  60181. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60182. })(BABYLON || (BABYLON = {}));
  60183. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60184. var BABYLON;
  60185. (function (BABYLON) {
  60186. // Adds the parsers to the scene parsers.
  60187. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60188. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60189. if (!individualParser) {
  60190. return;
  60191. }
  60192. // Particles Systems
  60193. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60194. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60195. var parsedParticleSystem = parsedData.particleSystems[index];
  60196. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60197. }
  60198. }
  60199. });
  60200. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60201. if (parsedParticleSystem.activeParticleCount) {
  60202. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60203. return ps;
  60204. }
  60205. else {
  60206. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60207. return ps;
  60208. }
  60209. });
  60210. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60211. if (uniformsNames === void 0) { uniformsNames = []; }
  60212. if (samplers === void 0) { samplers = []; }
  60213. if (defines === void 0) { defines = ""; }
  60214. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60215. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60216. if (defines.indexOf(" BILLBOARD") === -1) {
  60217. defines += "\n#define BILLBOARD\n";
  60218. }
  60219. if (samplers.indexOf("diffuseSampler") === -1) {
  60220. samplers.push("diffuseSampler");
  60221. }
  60222. return this.createEffect({
  60223. vertex: "particles",
  60224. fragmentElement: fragmentName
  60225. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60226. };
  60227. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60228. var results = new Array();
  60229. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60230. var particleSystem = this.getScene().particleSystems[index];
  60231. if (particleSystem.emitter === this) {
  60232. results.push(particleSystem);
  60233. }
  60234. }
  60235. return results;
  60236. };
  60237. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60238. var results = new Array();
  60239. var descendants = this.getDescendants();
  60240. descendants.push(this);
  60241. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60242. var particleSystem = this.getScene().particleSystems[index];
  60243. var emitter = particleSystem.emitter;
  60244. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60245. results.push(particleSystem);
  60246. }
  60247. }
  60248. return results;
  60249. };
  60250. })(BABYLON || (BABYLON = {}));
  60251. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60252. var BABYLON;
  60253. (function (BABYLON) {
  60254. /**
  60255. * Type of sub emitter
  60256. */
  60257. var SubEmitterType;
  60258. (function (SubEmitterType) {
  60259. /**
  60260. * Attached to the particle over it's lifetime
  60261. */
  60262. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60263. /**
  60264. * Created when the particle dies
  60265. */
  60266. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60267. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60268. /**
  60269. * Sub emitter class used to emit particles from an existing particle
  60270. */
  60271. var SubEmitter = /** @class */ (function () {
  60272. /**
  60273. * Creates a sub emitter
  60274. * @param particleSystem the particle system to be used by the sub emitter
  60275. */
  60276. function SubEmitter(
  60277. /**
  60278. * the particle system to be used by the sub emitter
  60279. */
  60280. particleSystem) {
  60281. this.particleSystem = particleSystem;
  60282. /**
  60283. * Type of the submitter (Default: END)
  60284. */
  60285. this.type = SubEmitterType.END;
  60286. /**
  60287. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  60288. * Note: This only is supported when using an emitter of type Mesh
  60289. */
  60290. this.inheritDirection = false;
  60291. /**
  60292. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60293. */
  60294. this.inheritedVelocityAmount = 0;
  60295. }
  60296. /**
  60297. * Clones the sub emitter
  60298. * @returns the cloned sub emitter
  60299. */
  60300. SubEmitter.prototype.clone = function () {
  60301. // Clone particle system
  60302. var emitter = this.particleSystem.emitter;
  60303. if (!emitter) {
  60304. emitter = new BABYLON.Vector3();
  60305. }
  60306. else if (emitter instanceof BABYLON.Vector3) {
  60307. emitter = emitter.clone();
  60308. }
  60309. else if (emitter instanceof BABYLON.AbstractMesh) {
  60310. emitter = new BABYLON.Mesh("", emitter.getScene());
  60311. emitter.isVisible = false;
  60312. }
  60313. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60314. // Clone properties
  60315. clone.type = this.type;
  60316. clone.inheritDirection = this.inheritDirection;
  60317. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60318. clone.particleSystem._disposeEmitterOnDispose = true;
  60319. clone.particleSystem.disposeOnStop = true;
  60320. return clone;
  60321. };
  60322. /** Release associated resources */
  60323. SubEmitter.prototype.dispose = function () {
  60324. this.particleSystem.dispose();
  60325. };
  60326. return SubEmitter;
  60327. }());
  60328. BABYLON.SubEmitter = SubEmitter;
  60329. })(BABYLON || (BABYLON = {}));
  60330. //# sourceMappingURL=babylon.subEmitter.js.map
  60331. var BABYLON;
  60332. (function (BABYLON) {
  60333. var ShaderMaterial = /** @class */ (function (_super) {
  60334. __extends(ShaderMaterial, _super);
  60335. function ShaderMaterial(name, scene, shaderPath, options) {
  60336. var _this = _super.call(this, name, scene) || this;
  60337. _this._textures = {};
  60338. _this._textureArrays = {};
  60339. _this._floats = {};
  60340. _this._ints = {};
  60341. _this._floatsArrays = {};
  60342. _this._colors3 = {};
  60343. _this._colors3Arrays = {};
  60344. _this._colors4 = {};
  60345. _this._vectors2 = {};
  60346. _this._vectors3 = {};
  60347. _this._vectors4 = {};
  60348. _this._matrices = {};
  60349. _this._matrices3x3 = {};
  60350. _this._matrices2x2 = {};
  60351. _this._vectors2Arrays = {};
  60352. _this._vectors3Arrays = {};
  60353. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60354. _this._shaderPath = shaderPath;
  60355. options.needAlphaBlending = options.needAlphaBlending || false;
  60356. options.needAlphaTesting = options.needAlphaTesting || false;
  60357. options.attributes = options.attributes || ["position", "normal", "uv"];
  60358. options.uniforms = options.uniforms || ["worldViewProjection"];
  60359. options.uniformBuffers = options.uniformBuffers || [];
  60360. options.samplers = options.samplers || [];
  60361. options.defines = options.defines || [];
  60362. _this._options = options;
  60363. return _this;
  60364. }
  60365. ShaderMaterial.prototype.getClassName = function () {
  60366. return "ShaderMaterial";
  60367. };
  60368. ShaderMaterial.prototype.needAlphaBlending = function () {
  60369. return this._options.needAlphaBlending;
  60370. };
  60371. ShaderMaterial.prototype.needAlphaTesting = function () {
  60372. return this._options.needAlphaTesting;
  60373. };
  60374. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60375. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60376. this._options.uniforms.push(uniformName);
  60377. }
  60378. };
  60379. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60380. if (this._options.samplers.indexOf(name) === -1) {
  60381. this._options.samplers.push(name);
  60382. }
  60383. this._textures[name] = texture;
  60384. return this;
  60385. };
  60386. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60387. if (this._options.samplers.indexOf(name) === -1) {
  60388. this._options.samplers.push(name);
  60389. }
  60390. this._checkUniform(name);
  60391. this._textureArrays[name] = textures;
  60392. return this;
  60393. };
  60394. ShaderMaterial.prototype.setFloat = function (name, value) {
  60395. this._checkUniform(name);
  60396. this._floats[name] = value;
  60397. return this;
  60398. };
  60399. ShaderMaterial.prototype.setInt = function (name, value) {
  60400. this._checkUniform(name);
  60401. this._ints[name] = value;
  60402. return this;
  60403. };
  60404. ShaderMaterial.prototype.setFloats = function (name, value) {
  60405. this._checkUniform(name);
  60406. this._floatsArrays[name] = value;
  60407. return this;
  60408. };
  60409. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60410. this._checkUniform(name);
  60411. this._colors3[name] = value;
  60412. return this;
  60413. };
  60414. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60415. this._checkUniform(name);
  60416. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60417. color.toArray(arr, arr.length);
  60418. return arr;
  60419. }, []);
  60420. return this;
  60421. };
  60422. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60423. this._checkUniform(name);
  60424. this._colors4[name] = value;
  60425. return this;
  60426. };
  60427. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60428. this._checkUniform(name);
  60429. this._vectors2[name] = value;
  60430. return this;
  60431. };
  60432. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60433. this._checkUniform(name);
  60434. this._vectors3[name] = value;
  60435. return this;
  60436. };
  60437. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60438. this._checkUniform(name);
  60439. this._vectors4[name] = value;
  60440. return this;
  60441. };
  60442. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60443. this._checkUniform(name);
  60444. this._matrices[name] = value;
  60445. return this;
  60446. };
  60447. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60448. this._checkUniform(name);
  60449. this._matrices3x3[name] = value;
  60450. return this;
  60451. };
  60452. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60453. this._checkUniform(name);
  60454. this._matrices2x2[name] = value;
  60455. return this;
  60456. };
  60457. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60458. this._checkUniform(name);
  60459. this._vectors2Arrays[name] = value;
  60460. return this;
  60461. };
  60462. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60463. this._checkUniform(name);
  60464. this._vectors3Arrays[name] = value;
  60465. return this;
  60466. };
  60467. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60468. if (!mesh) {
  60469. return true;
  60470. }
  60471. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60472. return false;
  60473. }
  60474. return false;
  60475. };
  60476. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60477. var scene = this.getScene();
  60478. var engine = scene.getEngine();
  60479. if (!this.checkReadyOnEveryCall) {
  60480. if (this._renderId === scene.getRenderId()) {
  60481. if (this._checkCache(scene, mesh, useInstances)) {
  60482. return true;
  60483. }
  60484. }
  60485. }
  60486. // Instances
  60487. var defines = [];
  60488. var attribs = [];
  60489. var fallbacks = new BABYLON.EffectFallbacks();
  60490. if (useInstances) {
  60491. defines.push("#define INSTANCES");
  60492. }
  60493. for (var index = 0; index < this._options.defines.length; index++) {
  60494. defines.push(this._options.defines[index]);
  60495. }
  60496. for (var index = 0; index < this._options.attributes.length; index++) {
  60497. attribs.push(this._options.attributes[index]);
  60498. }
  60499. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60500. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60501. defines.push("#define VERTEXCOLOR");
  60502. }
  60503. // Bones
  60504. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60505. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60506. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60507. if (mesh.numBoneInfluencers > 4) {
  60508. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60509. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60510. }
  60511. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60512. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60513. fallbacks.addCPUSkinningFallback(0, mesh);
  60514. if (this._options.uniforms.indexOf("mBones") === -1) {
  60515. this._options.uniforms.push("mBones");
  60516. }
  60517. }
  60518. else {
  60519. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60520. }
  60521. // Textures
  60522. for (var name in this._textures) {
  60523. if (!this._textures[name].isReady()) {
  60524. return false;
  60525. }
  60526. }
  60527. // Alpha test
  60528. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60529. defines.push("#define ALPHATEST");
  60530. }
  60531. var previousEffect = this._effect;
  60532. var join = defines.join("\n");
  60533. this._effect = engine.createEffect(this._shaderPath, {
  60534. attributes: attribs,
  60535. uniformsNames: this._options.uniforms,
  60536. uniformBuffersNames: this._options.uniformBuffers,
  60537. samplers: this._options.samplers,
  60538. defines: join,
  60539. fallbacks: fallbacks,
  60540. onCompiled: this.onCompiled,
  60541. onError: this.onError
  60542. }, engine);
  60543. if (!this._effect.isReady()) {
  60544. return false;
  60545. }
  60546. if (previousEffect !== this._effect) {
  60547. scene.resetCachedMaterial();
  60548. }
  60549. this._renderId = scene.getRenderId();
  60550. return true;
  60551. };
  60552. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60553. var scene = this.getScene();
  60554. if (!this._effect) {
  60555. return;
  60556. }
  60557. if (this._options.uniforms.indexOf("world") !== -1) {
  60558. this._effect.setMatrix("world", world);
  60559. }
  60560. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60561. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60562. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60563. }
  60564. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60565. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60566. }
  60567. };
  60568. ShaderMaterial.prototype.bind = function (world, mesh) {
  60569. // Std values
  60570. this.bindOnlyWorldMatrix(world);
  60571. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60572. if (this._options.uniforms.indexOf("view") !== -1) {
  60573. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60574. }
  60575. if (this._options.uniforms.indexOf("projection") !== -1) {
  60576. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60577. }
  60578. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60579. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60580. }
  60581. // Bones
  60582. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60583. var name;
  60584. // Texture
  60585. for (name in this._textures) {
  60586. this._effect.setTexture(name, this._textures[name]);
  60587. }
  60588. // Texture arrays
  60589. for (name in this._textureArrays) {
  60590. this._effect.setTextureArray(name, this._textureArrays[name]);
  60591. }
  60592. // Int
  60593. for (name in this._ints) {
  60594. this._effect.setInt(name, this._ints[name]);
  60595. }
  60596. // Float
  60597. for (name in this._floats) {
  60598. this._effect.setFloat(name, this._floats[name]);
  60599. }
  60600. // Floats
  60601. for (name in this._floatsArrays) {
  60602. this._effect.setArray(name, this._floatsArrays[name]);
  60603. }
  60604. // Color3
  60605. for (name in this._colors3) {
  60606. this._effect.setColor3(name, this._colors3[name]);
  60607. }
  60608. for (name in this._colors3Arrays) {
  60609. this._effect.setArray3(name, this._colors3Arrays[name]);
  60610. }
  60611. // Color4
  60612. for (name in this._colors4) {
  60613. var color = this._colors4[name];
  60614. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60615. }
  60616. // Vector2
  60617. for (name in this._vectors2) {
  60618. this._effect.setVector2(name, this._vectors2[name]);
  60619. }
  60620. // Vector3
  60621. for (name in this._vectors3) {
  60622. this._effect.setVector3(name, this._vectors3[name]);
  60623. }
  60624. // Vector4
  60625. for (name in this._vectors4) {
  60626. this._effect.setVector4(name, this._vectors4[name]);
  60627. }
  60628. // Matrix
  60629. for (name in this._matrices) {
  60630. this._effect.setMatrix(name, this._matrices[name]);
  60631. }
  60632. // Matrix 3x3
  60633. for (name in this._matrices3x3) {
  60634. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60635. }
  60636. // Matrix 2x2
  60637. for (name in this._matrices2x2) {
  60638. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60639. }
  60640. // Vector2Array
  60641. for (name in this._vectors2Arrays) {
  60642. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60643. }
  60644. // Vector3Array
  60645. for (name in this._vectors3Arrays) {
  60646. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60647. }
  60648. }
  60649. this._afterBind(mesh);
  60650. };
  60651. ShaderMaterial.prototype.getActiveTextures = function () {
  60652. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60653. for (var name in this._textures) {
  60654. activeTextures.push(this._textures[name]);
  60655. }
  60656. for (var name in this._textureArrays) {
  60657. var array = this._textureArrays[name];
  60658. for (var index = 0; index < array.length; index++) {
  60659. activeTextures.push(array[index]);
  60660. }
  60661. }
  60662. return activeTextures;
  60663. };
  60664. ShaderMaterial.prototype.hasTexture = function (texture) {
  60665. if (_super.prototype.hasTexture.call(this, texture)) {
  60666. return true;
  60667. }
  60668. for (var name in this._textures) {
  60669. if (this._textures[name] === texture) {
  60670. return true;
  60671. }
  60672. }
  60673. for (var name in this._textureArrays) {
  60674. var array = this._textureArrays[name];
  60675. for (var index = 0; index < array.length; index++) {
  60676. if (array[index] === texture) {
  60677. return true;
  60678. }
  60679. }
  60680. }
  60681. return false;
  60682. };
  60683. ShaderMaterial.prototype.clone = function (name) {
  60684. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60685. return newShaderMaterial;
  60686. };
  60687. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60688. if (forceDisposeTextures) {
  60689. var name;
  60690. for (name in this._textures) {
  60691. this._textures[name].dispose();
  60692. }
  60693. for (name in this._textureArrays) {
  60694. var array = this._textureArrays[name];
  60695. for (var index = 0; index < array.length; index++) {
  60696. array[index].dispose();
  60697. }
  60698. }
  60699. }
  60700. this._textures = {};
  60701. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60702. };
  60703. ShaderMaterial.prototype.serialize = function () {
  60704. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60705. serializationObject.customType = "BABYLON.ShaderMaterial";
  60706. serializationObject.options = this._options;
  60707. serializationObject.shaderPath = this._shaderPath;
  60708. var name;
  60709. // Texture
  60710. serializationObject.textures = {};
  60711. for (name in this._textures) {
  60712. serializationObject.textures[name] = this._textures[name].serialize();
  60713. }
  60714. // Texture arrays
  60715. serializationObject.textureArrays = {};
  60716. for (name in this._textureArrays) {
  60717. serializationObject.textureArrays[name] = [];
  60718. var array = this._textureArrays[name];
  60719. for (var index = 0; index < array.length; index++) {
  60720. serializationObject.textureArrays[name].push(array[index].serialize());
  60721. }
  60722. }
  60723. // Float
  60724. serializationObject.floats = {};
  60725. for (name in this._floats) {
  60726. serializationObject.floats[name] = this._floats[name];
  60727. }
  60728. // Float s
  60729. serializationObject.FloatArrays = {};
  60730. for (name in this._floatsArrays) {
  60731. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60732. }
  60733. // Color3
  60734. serializationObject.colors3 = {};
  60735. for (name in this._colors3) {
  60736. serializationObject.colors3[name] = this._colors3[name].asArray();
  60737. }
  60738. // Color3 array
  60739. serializationObject.colors3Arrays = {};
  60740. for (name in this._colors3Arrays) {
  60741. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60742. }
  60743. // Color4
  60744. serializationObject.colors4 = {};
  60745. for (name in this._colors4) {
  60746. serializationObject.colors4[name] = this._colors4[name].asArray();
  60747. }
  60748. // Vector2
  60749. serializationObject.vectors2 = {};
  60750. for (name in this._vectors2) {
  60751. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60752. }
  60753. // Vector3
  60754. serializationObject.vectors3 = {};
  60755. for (name in this._vectors3) {
  60756. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60757. }
  60758. // Vector4
  60759. serializationObject.vectors4 = {};
  60760. for (name in this._vectors4) {
  60761. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60762. }
  60763. // Matrix
  60764. serializationObject.matrices = {};
  60765. for (name in this._matrices) {
  60766. serializationObject.matrices[name] = this._matrices[name].asArray();
  60767. }
  60768. // Matrix 3x3
  60769. serializationObject.matrices3x3 = {};
  60770. for (name in this._matrices3x3) {
  60771. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60772. }
  60773. // Matrix 2x2
  60774. serializationObject.matrices2x2 = {};
  60775. for (name in this._matrices2x2) {
  60776. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60777. }
  60778. // Vector2Array
  60779. serializationObject.vectors2Arrays = {};
  60780. for (name in this._vectors2Arrays) {
  60781. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60782. }
  60783. // Vector3Array
  60784. serializationObject.vectors3Arrays = {};
  60785. for (name in this._vectors3Arrays) {
  60786. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60787. }
  60788. return serializationObject;
  60789. };
  60790. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60791. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60792. var name;
  60793. // Texture
  60794. for (name in source.textures) {
  60795. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60796. }
  60797. // Texture arrays
  60798. for (name in source.textureArrays) {
  60799. var array = source.textureArrays[name];
  60800. var textureArray = new Array();
  60801. for (var index = 0; index < array.length; index++) {
  60802. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60803. }
  60804. material.setTextureArray(name, textureArray);
  60805. }
  60806. // Float
  60807. for (name in source.floats) {
  60808. material.setFloat(name, source.floats[name]);
  60809. }
  60810. // Float s
  60811. for (name in source.floatsArrays) {
  60812. material.setFloats(name, source.floatsArrays[name]);
  60813. }
  60814. // Color3
  60815. for (name in source.colors3) {
  60816. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60817. }
  60818. // Color3 arrays
  60819. for (name in source.colors3Arrays) {
  60820. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60821. if (i % 3 === 0) {
  60822. arr.push([num]);
  60823. }
  60824. else {
  60825. arr[arr.length - 1].push(num);
  60826. }
  60827. return arr;
  60828. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60829. material.setColor3Array(name, colors);
  60830. }
  60831. // Color4
  60832. for (name in source.colors4) {
  60833. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60834. }
  60835. // Vector2
  60836. for (name in source.vectors2) {
  60837. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60838. }
  60839. // Vector3
  60840. for (name in source.vectors3) {
  60841. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60842. }
  60843. // Vector4
  60844. for (name in source.vectors4) {
  60845. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60846. }
  60847. // Matrix
  60848. for (name in source.matrices) {
  60849. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60850. }
  60851. // Matrix 3x3
  60852. for (name in source.matrices3x3) {
  60853. material.setMatrix3x3(name, source.matrices3x3[name]);
  60854. }
  60855. // Matrix 2x2
  60856. for (name in source.matrices2x2) {
  60857. material.setMatrix2x2(name, source.matrices2x2[name]);
  60858. }
  60859. // Vector2Array
  60860. for (name in source.vectors2Arrays) {
  60861. material.setArray2(name, source.vectors2Arrays[name]);
  60862. }
  60863. // Vector3Array
  60864. for (name in source.vectors3Arrays) {
  60865. material.setArray3(name, source.vectors3Arrays[name]);
  60866. }
  60867. return material;
  60868. };
  60869. return ShaderMaterial;
  60870. }(BABYLON.Material));
  60871. BABYLON.ShaderMaterial = ShaderMaterial;
  60872. })(BABYLON || (BABYLON = {}));
  60873. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60874. var BABYLON;
  60875. (function (BABYLON) {
  60876. var GroundMesh = /** @class */ (function (_super) {
  60877. __extends(GroundMesh, _super);
  60878. function GroundMesh(name, scene) {
  60879. var _this = _super.call(this, name, scene) || this;
  60880. _this.generateOctree = false;
  60881. return _this;
  60882. }
  60883. GroundMesh.prototype.getClassName = function () {
  60884. return "GroundMesh";
  60885. };
  60886. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60887. get: function () {
  60888. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60889. },
  60890. enumerable: true,
  60891. configurable: true
  60892. });
  60893. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60894. get: function () {
  60895. return this._subdivisionsX;
  60896. },
  60897. enumerable: true,
  60898. configurable: true
  60899. });
  60900. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60901. get: function () {
  60902. return this._subdivisionsY;
  60903. },
  60904. enumerable: true,
  60905. configurable: true
  60906. });
  60907. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60908. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60909. this._subdivisionsX = chunksCount;
  60910. this._subdivisionsY = chunksCount;
  60911. this.subdivide(chunksCount);
  60912. // Call the octree system optimization if it is defined.
  60913. var thisAsAny = this;
  60914. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  60915. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60916. }
  60917. };
  60918. /**
  60919. * Returns a height (y) value in the Worl system :
  60920. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60921. * Returns the ground y position if (x, z) are outside the ground surface.
  60922. */
  60923. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60924. var world = this.getWorldMatrix();
  60925. var invMat = BABYLON.Tmp.Matrix[5];
  60926. world.invertToRef(invMat);
  60927. var tmpVect = BABYLON.Tmp.Vector3[8];
  60928. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60929. x = tmpVect.x;
  60930. z = tmpVect.z;
  60931. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60932. return this.position.y;
  60933. }
  60934. if (!this._heightQuads || this._heightQuads.length == 0) {
  60935. this._initHeightQuads();
  60936. this._computeHeightQuads();
  60937. }
  60938. var facet = this._getFacetAt(x, z);
  60939. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60940. // return y in the World system
  60941. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60942. return tmpVect.y;
  60943. };
  60944. /**
  60945. * Returns a normalized vector (Vector3) orthogonal to the ground
  60946. * at the ground coordinates (x, z) expressed in the World system.
  60947. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60948. */
  60949. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60950. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60951. this.getNormalAtCoordinatesToRef(x, z, normal);
  60952. return normal;
  60953. };
  60954. /**
  60955. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60956. * at the ground coordinates (x, z) expressed in the World system.
  60957. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60958. * Returns the GroundMesh.
  60959. */
  60960. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60961. var world = this.getWorldMatrix();
  60962. var tmpMat = BABYLON.Tmp.Matrix[5];
  60963. world.invertToRef(tmpMat);
  60964. var tmpVect = BABYLON.Tmp.Vector3[8];
  60965. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60966. x = tmpVect.x;
  60967. z = tmpVect.z;
  60968. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60969. return this;
  60970. }
  60971. if (!this._heightQuads || this._heightQuads.length == 0) {
  60972. this._initHeightQuads();
  60973. this._computeHeightQuads();
  60974. }
  60975. var facet = this._getFacetAt(x, z);
  60976. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60977. return this;
  60978. };
  60979. /**
  60980. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60981. * if the ground has been updated.
  60982. * This can be used in the render loop.
  60983. * Returns the GroundMesh.
  60984. */
  60985. GroundMesh.prototype.updateCoordinateHeights = function () {
  60986. if (!this._heightQuads || this._heightQuads.length == 0) {
  60987. this._initHeightQuads();
  60988. }
  60989. this._computeHeightQuads();
  60990. return this;
  60991. };
  60992. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60993. GroundMesh.prototype._getFacetAt = function (x, z) {
  60994. // retrieve col and row from x, z coordinates in the ground local system
  60995. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60996. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60997. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60998. var facet;
  60999. if (z < quad.slope.x * x + quad.slope.y) {
  61000. facet = quad.facet1;
  61001. }
  61002. else {
  61003. facet = quad.facet2;
  61004. }
  61005. return facet;
  61006. };
  61007. // Creates and populates the heightMap array with "facet" elements :
  61008. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61009. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61010. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61011. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61012. // Returns the GroundMesh.
  61013. GroundMesh.prototype._initHeightQuads = function () {
  61014. var subdivisionsX = this._subdivisionsX;
  61015. var subdivisionsY = this._subdivisionsY;
  61016. this._heightQuads = new Array();
  61017. for (var row = 0; row < subdivisionsY; row++) {
  61018. for (var col = 0; col < subdivisionsX; col++) {
  61019. 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) };
  61020. this._heightQuads[row * subdivisionsX + col] = quad;
  61021. }
  61022. }
  61023. return this;
  61024. };
  61025. // Compute each quad element values and update the the heightMap array :
  61026. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61027. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61028. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61029. // Returns the GroundMesh.
  61030. GroundMesh.prototype._computeHeightQuads = function () {
  61031. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61032. if (!positions) {
  61033. return this;
  61034. }
  61035. var v1 = BABYLON.Tmp.Vector3[3];
  61036. var v2 = BABYLON.Tmp.Vector3[2];
  61037. var v3 = BABYLON.Tmp.Vector3[1];
  61038. var v4 = BABYLON.Tmp.Vector3[0];
  61039. var v1v2 = BABYLON.Tmp.Vector3[4];
  61040. var v1v3 = BABYLON.Tmp.Vector3[5];
  61041. var v1v4 = BABYLON.Tmp.Vector3[6];
  61042. var norm1 = BABYLON.Tmp.Vector3[7];
  61043. var norm2 = BABYLON.Tmp.Vector3[8];
  61044. var i = 0;
  61045. var j = 0;
  61046. var k = 0;
  61047. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61048. var h = 0;
  61049. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61050. var d2 = 0;
  61051. var subdivisionsX = this._subdivisionsX;
  61052. var subdivisionsY = this._subdivisionsY;
  61053. for (var row = 0; row < subdivisionsY; row++) {
  61054. for (var col = 0; col < subdivisionsX; col++) {
  61055. i = col * 3;
  61056. j = row * (subdivisionsX + 1) * 3;
  61057. k = (row + 1) * (subdivisionsX + 1) * 3;
  61058. v1.x = positions[j + i];
  61059. v1.y = positions[j + i + 1];
  61060. v1.z = positions[j + i + 2];
  61061. v2.x = positions[j + i + 3];
  61062. v2.y = positions[j + i + 4];
  61063. v2.z = positions[j + i + 5];
  61064. v3.x = positions[k + i];
  61065. v3.y = positions[k + i + 1];
  61066. v3.z = positions[k + i + 2];
  61067. v4.x = positions[k + i + 3];
  61068. v4.y = positions[k + i + 4];
  61069. v4.z = positions[k + i + 5];
  61070. // 2D slope V1V4
  61071. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61072. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61073. // facet equations :
  61074. // we compute each facet normal vector
  61075. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61076. // we compute the value d by applying the equation to v1 which belongs to the plane
  61077. // then we store the facet equation in a Vector4
  61078. v2.subtractToRef(v1, v1v2);
  61079. v3.subtractToRef(v1, v1v3);
  61080. v4.subtractToRef(v1, v1v4);
  61081. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61082. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61083. norm1.normalize();
  61084. norm2.normalize();
  61085. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61086. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61087. var quad = this._heightQuads[row * subdivisionsX + col];
  61088. quad.slope.copyFromFloats(cd, h);
  61089. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61090. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61091. }
  61092. }
  61093. return this;
  61094. };
  61095. GroundMesh.prototype.serialize = function (serializationObject) {
  61096. _super.prototype.serialize.call(this, serializationObject);
  61097. serializationObject.subdivisionsX = this._subdivisionsX;
  61098. serializationObject.subdivisionsY = this._subdivisionsY;
  61099. serializationObject.minX = this._minX;
  61100. serializationObject.maxX = this._maxX;
  61101. serializationObject.minZ = this._minZ;
  61102. serializationObject.maxZ = this._maxZ;
  61103. serializationObject.width = this._width;
  61104. serializationObject.height = this._height;
  61105. };
  61106. GroundMesh.Parse = function (parsedMesh, scene) {
  61107. var result = new GroundMesh(parsedMesh.name, scene);
  61108. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61109. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61110. result._minX = parsedMesh.minX;
  61111. result._maxX = parsedMesh.maxX;
  61112. result._minZ = parsedMesh.minZ;
  61113. result._maxZ = parsedMesh.maxZ;
  61114. result._width = parsedMesh.width;
  61115. result._height = parsedMesh.height;
  61116. return result;
  61117. };
  61118. return GroundMesh;
  61119. }(BABYLON.Mesh));
  61120. BABYLON.GroundMesh = GroundMesh;
  61121. })(BABYLON || (BABYLON = {}));
  61122. //# sourceMappingURL=babylon.groundMesh.js.map
  61123. var BABYLON;
  61124. (function (BABYLON) {
  61125. /**
  61126. * Creates an instance based on a source mesh.
  61127. */
  61128. var InstancedMesh = /** @class */ (function (_super) {
  61129. __extends(InstancedMesh, _super);
  61130. function InstancedMesh(name, source) {
  61131. var _this = _super.call(this, name, source.getScene()) || this;
  61132. source.instances.push(_this);
  61133. _this._sourceMesh = source;
  61134. _this.position.copyFrom(source.position);
  61135. _this.rotation.copyFrom(source.rotation);
  61136. _this.scaling.copyFrom(source.scaling);
  61137. if (source.rotationQuaternion) {
  61138. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61139. }
  61140. _this.infiniteDistance = source.infiniteDistance;
  61141. _this.setPivotMatrix(source.getPivotMatrix());
  61142. _this.refreshBoundingInfo();
  61143. _this._syncSubMeshes();
  61144. return _this;
  61145. }
  61146. /**
  61147. * Returns the string "InstancedMesh".
  61148. */
  61149. InstancedMesh.prototype.getClassName = function () {
  61150. return "InstancedMesh";
  61151. };
  61152. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61153. // Methods
  61154. get: function () {
  61155. return this._sourceMesh.receiveShadows;
  61156. },
  61157. enumerable: true,
  61158. configurable: true
  61159. });
  61160. Object.defineProperty(InstancedMesh.prototype, "material", {
  61161. get: function () {
  61162. return this._sourceMesh.material;
  61163. },
  61164. enumerable: true,
  61165. configurable: true
  61166. });
  61167. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61168. get: function () {
  61169. return this._sourceMesh.visibility;
  61170. },
  61171. enumerable: true,
  61172. configurable: true
  61173. });
  61174. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61175. get: function () {
  61176. return this._sourceMesh.skeleton;
  61177. },
  61178. enumerable: true,
  61179. configurable: true
  61180. });
  61181. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61182. get: function () {
  61183. return this._sourceMesh.renderingGroupId;
  61184. },
  61185. set: function (value) {
  61186. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61187. return;
  61188. }
  61189. //no-op with warning
  61190. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61191. },
  61192. enumerable: true,
  61193. configurable: true
  61194. });
  61195. /**
  61196. * Returns the total number of vertices (integer).
  61197. */
  61198. InstancedMesh.prototype.getTotalVertices = function () {
  61199. return this._sourceMesh.getTotalVertices();
  61200. };
  61201. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61202. get: function () {
  61203. return this._sourceMesh;
  61204. },
  61205. enumerable: true,
  61206. configurable: true
  61207. });
  61208. /**
  61209. * Is this node ready to be used/rendered
  61210. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61211. * @return {boolean} is it ready
  61212. */
  61213. InstancedMesh.prototype.isReady = function (completeCheck) {
  61214. if (completeCheck === void 0) { completeCheck = false; }
  61215. return this._sourceMesh.isReady(completeCheck, true);
  61216. };
  61217. /**
  61218. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61219. */
  61220. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61221. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61222. };
  61223. /**
  61224. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61225. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61226. * The `data` are either a numeric array either a Float32Array.
  61227. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61228. * 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).
  61229. * Note that a new underlying VertexBuffer object is created each call.
  61230. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61231. *
  61232. * Possible `kind` values :
  61233. * - BABYLON.VertexBuffer.PositionKind
  61234. * - BABYLON.VertexBuffer.UVKind
  61235. * - BABYLON.VertexBuffer.UV2Kind
  61236. * - BABYLON.VertexBuffer.UV3Kind
  61237. * - BABYLON.VertexBuffer.UV4Kind
  61238. * - BABYLON.VertexBuffer.UV5Kind
  61239. * - BABYLON.VertexBuffer.UV6Kind
  61240. * - BABYLON.VertexBuffer.ColorKind
  61241. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61242. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61243. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61244. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61245. *
  61246. * Returns the Mesh.
  61247. */
  61248. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61249. if (this.sourceMesh) {
  61250. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61251. }
  61252. return this.sourceMesh;
  61253. };
  61254. /**
  61255. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61256. * If the mesh has no geometry, it is simply returned as it is.
  61257. * The `data` are either a numeric array either a Float32Array.
  61258. * No new underlying VertexBuffer object is created.
  61259. * 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.
  61260. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61261. *
  61262. * Possible `kind` values :
  61263. * - BABYLON.VertexBuffer.PositionKind
  61264. * - BABYLON.VertexBuffer.UVKind
  61265. * - BABYLON.VertexBuffer.UV2Kind
  61266. * - BABYLON.VertexBuffer.UV3Kind
  61267. * - BABYLON.VertexBuffer.UV4Kind
  61268. * - BABYLON.VertexBuffer.UV5Kind
  61269. * - BABYLON.VertexBuffer.UV6Kind
  61270. * - BABYLON.VertexBuffer.ColorKind
  61271. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61272. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61273. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61274. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61275. *
  61276. * Returns the Mesh.
  61277. */
  61278. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61279. if (this.sourceMesh) {
  61280. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61281. }
  61282. return this.sourceMesh;
  61283. };
  61284. /**
  61285. * Sets the mesh indices.
  61286. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61287. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61288. * This method creates a new index buffer each call.
  61289. * Returns the Mesh.
  61290. */
  61291. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61292. if (totalVertices === void 0) { totalVertices = null; }
  61293. if (this.sourceMesh) {
  61294. this.sourceMesh.setIndices(indices, totalVertices);
  61295. }
  61296. return this.sourceMesh;
  61297. };
  61298. /**
  61299. * Boolean : True if the mesh owns the requested kind of data.
  61300. */
  61301. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61302. return this._sourceMesh.isVerticesDataPresent(kind);
  61303. };
  61304. /**
  61305. * Returns an array of indices (IndicesArray).
  61306. */
  61307. InstancedMesh.prototype.getIndices = function () {
  61308. return this._sourceMesh.getIndices();
  61309. };
  61310. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61311. get: function () {
  61312. return this._sourceMesh._positions;
  61313. },
  61314. enumerable: true,
  61315. configurable: true
  61316. });
  61317. /**
  61318. * Sets a new updated BoundingInfo to the mesh.
  61319. * Returns the mesh.
  61320. */
  61321. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61322. var meshBB = this._sourceMesh.getBoundingInfo();
  61323. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61324. this._updateBoundingInfo();
  61325. return this;
  61326. };
  61327. /** @hidden */
  61328. InstancedMesh.prototype._preActivate = function () {
  61329. if (this._currentLOD) {
  61330. this._currentLOD._preActivate();
  61331. }
  61332. return this;
  61333. };
  61334. /** @hidden */
  61335. InstancedMesh.prototype._activate = function (renderId) {
  61336. if (this._currentLOD) {
  61337. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61338. }
  61339. return this;
  61340. };
  61341. /**
  61342. * Returns the current associated LOD AbstractMesh.
  61343. */
  61344. InstancedMesh.prototype.getLOD = function (camera) {
  61345. if (!camera) {
  61346. return this;
  61347. }
  61348. var boundingInfo = this.getBoundingInfo();
  61349. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61350. if (this._currentLOD === this.sourceMesh) {
  61351. return this;
  61352. }
  61353. return this._currentLOD;
  61354. };
  61355. /** @hidden */
  61356. InstancedMesh.prototype._syncSubMeshes = function () {
  61357. this.releaseSubMeshes();
  61358. if (this._sourceMesh.subMeshes) {
  61359. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61360. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61361. }
  61362. }
  61363. return this;
  61364. };
  61365. /** @hidden */
  61366. InstancedMesh.prototype._generatePointsArray = function () {
  61367. return this._sourceMesh._generatePointsArray();
  61368. };
  61369. /**
  61370. * Creates a new InstancedMesh from the current mesh.
  61371. * - name (string) : the cloned mesh name
  61372. * - newParent (optional Node) : the optional Node to parent the clone to.
  61373. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61374. *
  61375. * Returns the clone.
  61376. */
  61377. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61378. var result = this._sourceMesh.createInstance(name);
  61379. // Deep copy
  61380. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61381. // Bounding info
  61382. this.refreshBoundingInfo();
  61383. // Parent
  61384. if (newParent) {
  61385. result.parent = newParent;
  61386. }
  61387. if (!doNotCloneChildren) {
  61388. // Children
  61389. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61390. var mesh = this.getScene().meshes[index];
  61391. if (mesh.parent === this) {
  61392. mesh.clone(mesh.name, result);
  61393. }
  61394. }
  61395. }
  61396. result.computeWorldMatrix(true);
  61397. return result;
  61398. };
  61399. /**
  61400. * Disposes the InstancedMesh.
  61401. * Returns nothing.
  61402. */
  61403. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61404. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61405. // Remove from mesh
  61406. var index = this._sourceMesh.instances.indexOf(this);
  61407. this._sourceMesh.instances.splice(index, 1);
  61408. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61409. };
  61410. return InstancedMesh;
  61411. }(BABYLON.AbstractMesh));
  61412. BABYLON.InstancedMesh = InstancedMesh;
  61413. })(BABYLON || (BABYLON = {}));
  61414. //# sourceMappingURL=babylon.instancedMesh.js.map
  61415. var BABYLON;
  61416. (function (BABYLON) {
  61417. var LinesMesh = /** @class */ (function (_super) {
  61418. __extends(LinesMesh, _super);
  61419. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61420. if (scene === void 0) { scene = null; }
  61421. if (parent === void 0) { parent = null; }
  61422. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61423. _this.useVertexColor = useVertexColor;
  61424. _this.useVertexAlpha = useVertexAlpha;
  61425. _this.color = new BABYLON.Color3(1, 1, 1);
  61426. _this.alpha = 1;
  61427. if (source) {
  61428. _this.color = source.color.clone();
  61429. _this.alpha = source.alpha;
  61430. _this.useVertexColor = source.useVertexColor;
  61431. _this.useVertexAlpha = source.useVertexAlpha;
  61432. }
  61433. _this._intersectionThreshold = 0.1;
  61434. var defines = [];
  61435. var options = {
  61436. attributes: [BABYLON.VertexBuffer.PositionKind],
  61437. uniforms: ["world", "viewProjection"],
  61438. needAlphaBlending: true,
  61439. defines: defines
  61440. };
  61441. if (useVertexAlpha === false) {
  61442. options.needAlphaBlending = false;
  61443. }
  61444. if (!useVertexColor) {
  61445. options.uniforms.push("color");
  61446. }
  61447. else {
  61448. options.defines.push("#define VERTEXCOLOR");
  61449. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61450. }
  61451. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61452. return _this;
  61453. }
  61454. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61455. /**
  61456. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61457. * This margin is expressed in world space coordinates, so its value may vary.
  61458. * Default value is 0.1
  61459. * @returns the intersection Threshold value.
  61460. */
  61461. get: function () {
  61462. return this._intersectionThreshold;
  61463. },
  61464. /**
  61465. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61466. * This margin is expressed in world space coordinates, so its value may vary.
  61467. * @param value the new threshold to apply
  61468. */
  61469. set: function (value) {
  61470. if (this._intersectionThreshold === value) {
  61471. return;
  61472. }
  61473. this._intersectionThreshold = value;
  61474. if (this.geometry) {
  61475. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61476. }
  61477. },
  61478. enumerable: true,
  61479. configurable: true
  61480. });
  61481. /**
  61482. * Returns the string "LineMesh"
  61483. */
  61484. LinesMesh.prototype.getClassName = function () {
  61485. return "LinesMesh";
  61486. };
  61487. Object.defineProperty(LinesMesh.prototype, "material", {
  61488. /**
  61489. * @hidden
  61490. */
  61491. get: function () {
  61492. return this._colorShader;
  61493. },
  61494. /**
  61495. * @hidden
  61496. */
  61497. set: function (value) {
  61498. // Do nothing
  61499. },
  61500. enumerable: true,
  61501. configurable: true
  61502. });
  61503. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61504. /**
  61505. * @hidden
  61506. */
  61507. get: function () {
  61508. return false;
  61509. },
  61510. enumerable: true,
  61511. configurable: true
  61512. });
  61513. LinesMesh.prototype.createInstance = function (name) {
  61514. throw new Error("LinesMeshes do not support createInstance.");
  61515. };
  61516. /** @hidden */
  61517. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61518. if (!this._geometry) {
  61519. return this;
  61520. }
  61521. // VBOs
  61522. this._geometry._bind(this._colorShader.getEffect());
  61523. // Color
  61524. if (!this.useVertexColor) {
  61525. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61526. }
  61527. return this;
  61528. };
  61529. /** @hidden */
  61530. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61531. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61532. return this;
  61533. }
  61534. var engine = this.getScene().getEngine();
  61535. // Draw order
  61536. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61537. return this;
  61538. };
  61539. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61540. this._colorShader.dispose();
  61541. _super.prototype.dispose.call(this, doNotRecurse);
  61542. };
  61543. /**
  61544. * Returns a new LineMesh object cloned from the current one.
  61545. */
  61546. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61547. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61548. };
  61549. return LinesMesh;
  61550. }(BABYLON.Mesh));
  61551. BABYLON.LinesMesh = LinesMesh;
  61552. })(BABYLON || (BABYLON = {}));
  61553. //# sourceMappingURL=babylon.linesMesh.js.map
  61554. var BABYLON;
  61555. (function (BABYLON) {
  61556. /**
  61557. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61558. * The underlying implementation relies on an associative array to ensure the best performances.
  61559. * The value can be anything including 'null' but except 'undefined'
  61560. */
  61561. var StringDictionary = /** @class */ (function () {
  61562. function StringDictionary() {
  61563. this._count = 0;
  61564. this._data = {};
  61565. }
  61566. /**
  61567. * This will clear this dictionary and copy the content from the 'source' one.
  61568. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61569. * @param source the dictionary to take the content from and copy to this dictionary
  61570. */
  61571. StringDictionary.prototype.copyFrom = function (source) {
  61572. var _this = this;
  61573. this.clear();
  61574. source.forEach(function (t, v) { return _this.add(t, v); });
  61575. };
  61576. /**
  61577. * Get a value based from its key
  61578. * @param key the given key to get the matching value from
  61579. * @return the value if found, otherwise undefined is returned
  61580. */
  61581. StringDictionary.prototype.get = function (key) {
  61582. var val = this._data[key];
  61583. if (val !== undefined) {
  61584. return val;
  61585. }
  61586. return undefined;
  61587. };
  61588. /**
  61589. * Get a value from its key or add it if it doesn't exist.
  61590. * This method will ensure you that a given key/data will be present in the dictionary.
  61591. * @param key the given key to get the matching value from
  61592. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61593. * The factory will only be invoked if there's no data for the given key.
  61594. * @return the value corresponding to the key.
  61595. */
  61596. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61597. var val = this.get(key);
  61598. if (val !== undefined) {
  61599. return val;
  61600. }
  61601. val = factory(key);
  61602. if (val) {
  61603. this.add(key, val);
  61604. }
  61605. return val;
  61606. };
  61607. /**
  61608. * Get a value from its key if present in the dictionary otherwise add it
  61609. * @param key the key to get the value from
  61610. * @param val if there's no such key/value pair in the dictionary add it with this value
  61611. * @return the value corresponding to the key
  61612. */
  61613. StringDictionary.prototype.getOrAdd = function (key, val) {
  61614. var curVal = this.get(key);
  61615. if (curVal !== undefined) {
  61616. return curVal;
  61617. }
  61618. this.add(key, val);
  61619. return val;
  61620. };
  61621. /**
  61622. * Check if there's a given key in the dictionary
  61623. * @param key the key to check for
  61624. * @return true if the key is present, false otherwise
  61625. */
  61626. StringDictionary.prototype.contains = function (key) {
  61627. return this._data[key] !== undefined;
  61628. };
  61629. /**
  61630. * Add a new key and its corresponding value
  61631. * @param key the key to add
  61632. * @param value the value corresponding to the key
  61633. * @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
  61634. */
  61635. StringDictionary.prototype.add = function (key, value) {
  61636. if (this._data[key] !== undefined) {
  61637. return false;
  61638. }
  61639. this._data[key] = value;
  61640. ++this._count;
  61641. return true;
  61642. };
  61643. StringDictionary.prototype.set = function (key, value) {
  61644. if (this._data[key] === undefined) {
  61645. return false;
  61646. }
  61647. this._data[key] = value;
  61648. return true;
  61649. };
  61650. /**
  61651. * Get the element of the given key and remove it from the dictionary
  61652. * @param key
  61653. */
  61654. StringDictionary.prototype.getAndRemove = function (key) {
  61655. var val = this.get(key);
  61656. if (val !== undefined) {
  61657. delete this._data[key];
  61658. --this._count;
  61659. return val;
  61660. }
  61661. return null;
  61662. };
  61663. /**
  61664. * Remove a key/value from the dictionary.
  61665. * @param key the key to remove
  61666. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61667. */
  61668. StringDictionary.prototype.remove = function (key) {
  61669. if (this.contains(key)) {
  61670. delete this._data[key];
  61671. --this._count;
  61672. return true;
  61673. }
  61674. return false;
  61675. };
  61676. /**
  61677. * Clear the whole content of the dictionary
  61678. */
  61679. StringDictionary.prototype.clear = function () {
  61680. this._data = {};
  61681. this._count = 0;
  61682. };
  61683. Object.defineProperty(StringDictionary.prototype, "count", {
  61684. get: function () {
  61685. return this._count;
  61686. },
  61687. enumerable: true,
  61688. configurable: true
  61689. });
  61690. /**
  61691. * Execute a callback on each key/val of the dictionary.
  61692. * Note that you can remove any element in this dictionary in the callback implementation
  61693. * @param callback the callback to execute on a given key/value pair
  61694. */
  61695. StringDictionary.prototype.forEach = function (callback) {
  61696. for (var cur in this._data) {
  61697. var val = this._data[cur];
  61698. callback(cur, val);
  61699. }
  61700. };
  61701. /**
  61702. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61703. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61704. * Note that you can remove any element in this dictionary in the callback implementation
  61705. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61706. */
  61707. StringDictionary.prototype.first = function (callback) {
  61708. for (var cur in this._data) {
  61709. var val = this._data[cur];
  61710. var res = callback(cur, val);
  61711. if (res) {
  61712. return res;
  61713. }
  61714. }
  61715. return null;
  61716. };
  61717. return StringDictionary;
  61718. }());
  61719. BABYLON.StringDictionary = StringDictionary;
  61720. })(BABYLON || (BABYLON = {}));
  61721. //# sourceMappingURL=babylon.stringDictionary.js.map
  61722. var BABYLON;
  61723. (function (BABYLON) {
  61724. var Debug;
  61725. (function (Debug) {
  61726. /**
  61727. * Class used to render a debug view of a given skeleton
  61728. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  61729. */
  61730. var SkeletonViewer = /** @class */ (function () {
  61731. /**
  61732. * Creates a new SkeletonViewer
  61733. * @param skeleton defines the skeleton to render
  61734. * @param mesh defines the mesh attached to the skeleton
  61735. * @param scene defines the hosting scene
  61736. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  61737. * @param renderingGroupId defines the rendering group id to use with the viewer
  61738. */
  61739. function SkeletonViewer(
  61740. /** defines the skeleton to render */
  61741. skeleton,
  61742. /** defines the mesh attached to the skeleton */
  61743. mesh, scene,
  61744. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  61745. autoUpdateBonesMatrices,
  61746. /** defines the rendering group id to use with the viewer */
  61747. renderingGroupId) {
  61748. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61749. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61750. this.skeleton = skeleton;
  61751. this.mesh = mesh;
  61752. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61753. this.renderingGroupId = renderingGroupId;
  61754. /** Gets or sets the color used to render the skeleton */
  61755. this.color = BABYLON.Color3.White();
  61756. this._debugLines = new Array();
  61757. this._isEnabled = false;
  61758. this._scene = scene;
  61759. this.update();
  61760. this._renderFunction = this.update.bind(this);
  61761. }
  61762. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61763. get: function () {
  61764. return this._isEnabled;
  61765. },
  61766. /** Gets or sets a boolean indicating if the viewer is enabled */
  61767. set: function (value) {
  61768. if (this._isEnabled === value) {
  61769. return;
  61770. }
  61771. this._isEnabled = value;
  61772. if (value) {
  61773. this._scene.registerBeforeRender(this._renderFunction);
  61774. }
  61775. else {
  61776. this._scene.unregisterBeforeRender(this._renderFunction);
  61777. }
  61778. },
  61779. enumerable: true,
  61780. configurable: true
  61781. });
  61782. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61783. if (x === void 0) { x = 0; }
  61784. if (y === void 0) { y = 0; }
  61785. if (z === void 0) { z = 0; }
  61786. var tmat = BABYLON.Tmp.Matrix[0];
  61787. var parentBone = bone.getParent();
  61788. tmat.copyFrom(bone.getLocalMatrix());
  61789. if (x !== 0 || y !== 0 || z !== 0) {
  61790. var tmat2 = BABYLON.Tmp.Matrix[1];
  61791. BABYLON.Matrix.IdentityToRef(tmat2);
  61792. tmat2.m[12] = x;
  61793. tmat2.m[13] = y;
  61794. tmat2.m[14] = z;
  61795. tmat2.multiplyToRef(tmat, tmat);
  61796. }
  61797. if (parentBone) {
  61798. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61799. }
  61800. tmat.multiplyToRef(meshMat, tmat);
  61801. position.x = tmat.m[12];
  61802. position.y = tmat.m[13];
  61803. position.z = tmat.m[14];
  61804. };
  61805. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61806. var len = bones.length;
  61807. var meshPos = this.mesh.position;
  61808. for (var i = 0; i < len; i++) {
  61809. var bone = bones[i];
  61810. var points = this._debugLines[i];
  61811. if (!points) {
  61812. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61813. this._debugLines[i] = points;
  61814. }
  61815. this._getBonePosition(points[0], bone, meshMat);
  61816. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61817. points[0].subtractInPlace(meshPos);
  61818. points[1].subtractInPlace(meshPos);
  61819. }
  61820. };
  61821. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61822. var len = bones.length;
  61823. var boneNum = 0;
  61824. var meshPos = this.mesh.position;
  61825. for (var i = len - 1; i >= 0; i--) {
  61826. var childBone = bones[i];
  61827. var parentBone = childBone.getParent();
  61828. if (!parentBone) {
  61829. continue;
  61830. }
  61831. var points = this._debugLines[boneNum];
  61832. if (!points) {
  61833. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61834. this._debugLines[boneNum] = points;
  61835. }
  61836. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61837. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61838. points[0].subtractInPlace(meshPos);
  61839. points[1].subtractInPlace(meshPos);
  61840. boneNum++;
  61841. }
  61842. };
  61843. /** Update the viewer to sync with current skeleton state */
  61844. SkeletonViewer.prototype.update = function () {
  61845. if (this.autoUpdateBonesMatrices) {
  61846. this.skeleton.computeAbsoluteTransforms();
  61847. }
  61848. if (this.skeleton.bones[0].length === undefined) {
  61849. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61850. }
  61851. else {
  61852. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61853. }
  61854. if (!this._debugMesh) {
  61855. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  61856. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61857. }
  61858. else {
  61859. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61860. }
  61861. this._debugMesh.position.copyFrom(this.mesh.position);
  61862. this._debugMesh.color = this.color;
  61863. };
  61864. /** Release associated resources */
  61865. SkeletonViewer.prototype.dispose = function () {
  61866. if (this._debugMesh) {
  61867. this.isEnabled = false;
  61868. this._debugMesh.dispose();
  61869. this._debugMesh = null;
  61870. }
  61871. };
  61872. return SkeletonViewer;
  61873. }());
  61874. Debug.SkeletonViewer = SkeletonViewer;
  61875. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61876. })(BABYLON || (BABYLON = {}));
  61877. //# sourceMappingURL=babylon.skeletonViewer.js.map
  61878. /**
  61879. * Module Debug contains the (visual) components to debug a scene correctly
  61880. */
  61881. var BABYLON;
  61882. (function (BABYLON) {
  61883. var Debug;
  61884. (function (Debug) {
  61885. /**
  61886. * The Axes viewer will show 3 axes in a specific point in space
  61887. */
  61888. var AxesViewer = /** @class */ (function () {
  61889. /**
  61890. * Creates a new AxesViewer
  61891. * @param scene defines the hosting scene
  61892. * @param scaleLines defines a number used to scale line length (1 by default)
  61893. */
  61894. function AxesViewer(scene, scaleLines) {
  61895. if (scaleLines === void 0) { scaleLines = 1; }
  61896. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61897. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61898. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61899. /**
  61900. * Gets or sets a number used to scale line length
  61901. */
  61902. this.scaleLines = 1;
  61903. this.scaleLines = scaleLines;
  61904. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  61905. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  61906. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  61907. this._xmesh.renderingGroupId = 2;
  61908. this._ymesh.renderingGroupId = 2;
  61909. this._zmesh.renderingGroupId = 2;
  61910. this._xmesh.material.checkReadyOnlyOnce = true;
  61911. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  61912. this._ymesh.material.checkReadyOnlyOnce = true;
  61913. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  61914. this._zmesh.material.checkReadyOnlyOnce = true;
  61915. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  61916. this.scene = scene;
  61917. }
  61918. /**
  61919. * Force the viewer to update
  61920. * @param position defines the position of the viewer
  61921. * @param xaxis defines the x axis of the viewer
  61922. * @param yaxis defines the y axis of the viewer
  61923. * @param zaxis defines the z axis of the viewer
  61924. */
  61925. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  61926. var scaleLines = this.scaleLines;
  61927. if (this._xmesh) {
  61928. this._xmesh.position.copyFrom(position);
  61929. }
  61930. if (this._ymesh) {
  61931. this._ymesh.position.copyFrom(position);
  61932. }
  61933. if (this._zmesh) {
  61934. this._zmesh.position.copyFrom(position);
  61935. }
  61936. var point2 = this._xline[1];
  61937. point2.x = xaxis.x * scaleLines;
  61938. point2.y = xaxis.y * scaleLines;
  61939. point2.z = xaxis.z * scaleLines;
  61940. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  61941. point2 = this._yline[1];
  61942. point2.x = yaxis.x * scaleLines;
  61943. point2.y = yaxis.y * scaleLines;
  61944. point2.z = yaxis.z * scaleLines;
  61945. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  61946. point2 = this._zline[1];
  61947. point2.x = zaxis.x * scaleLines;
  61948. point2.y = zaxis.y * scaleLines;
  61949. point2.z = zaxis.z * scaleLines;
  61950. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  61951. };
  61952. /** Releases resources */
  61953. AxesViewer.prototype.dispose = function () {
  61954. if (this._xmesh) {
  61955. this._xmesh.dispose();
  61956. }
  61957. if (this._ymesh) {
  61958. this._ymesh.dispose();
  61959. }
  61960. if (this._zmesh) {
  61961. this._zmesh.dispose();
  61962. }
  61963. this._xmesh = null;
  61964. this._ymesh = null;
  61965. this._zmesh = null;
  61966. this.scene = null;
  61967. };
  61968. return AxesViewer;
  61969. }());
  61970. Debug.AxesViewer = AxesViewer;
  61971. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61972. })(BABYLON || (BABYLON = {}));
  61973. //# sourceMappingURL=babylon.axesViewer.js.map
  61974. var BABYLON;
  61975. (function (BABYLON) {
  61976. var Debug;
  61977. (function (Debug) {
  61978. /**
  61979. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  61980. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  61981. */
  61982. var BoneAxesViewer = /** @class */ (function (_super) {
  61983. __extends(BoneAxesViewer, _super);
  61984. /**
  61985. * Creates a new BoneAxesViewer
  61986. * @param scene defines the hosting scene
  61987. * @param bone defines the target bone
  61988. * @param mesh defines the target mesh
  61989. * @param scaleLines defines a scaling factor for line length (1 by default)
  61990. */
  61991. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61992. if (scaleLines === void 0) { scaleLines = 1; }
  61993. var _this = _super.call(this, scene, scaleLines) || this;
  61994. /** Gets current position */
  61995. _this.pos = BABYLON.Vector3.Zero();
  61996. /** Gets direction of X axis */
  61997. _this.xaxis = BABYLON.Vector3.Zero();
  61998. /** Gets direction of Y axis */
  61999. _this.yaxis = BABYLON.Vector3.Zero();
  62000. /** Gets direction of Z axis */
  62001. _this.zaxis = BABYLON.Vector3.Zero();
  62002. _this.mesh = mesh;
  62003. _this.bone = bone;
  62004. return _this;
  62005. }
  62006. /**
  62007. * Force the viewer to update
  62008. */
  62009. BoneAxesViewer.prototype.update = function () {
  62010. if (!this.mesh || !this.bone) {
  62011. return;
  62012. }
  62013. var bone = this.bone;
  62014. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62015. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62016. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62017. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62018. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62019. };
  62020. /** Releases resources */
  62021. BoneAxesViewer.prototype.dispose = function () {
  62022. if (this.mesh) {
  62023. this.mesh = null;
  62024. this.bone = null;
  62025. _super.prototype.dispose.call(this);
  62026. }
  62027. };
  62028. return BoneAxesViewer;
  62029. }(Debug.AxesViewer));
  62030. Debug.BoneAxesViewer = BoneAxesViewer;
  62031. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62032. })(BABYLON || (BABYLON = {}));
  62033. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62034. var BABYLON;
  62035. (function (BABYLON) {
  62036. var RayHelper = /** @class */ (function () {
  62037. function RayHelper(ray) {
  62038. this.ray = ray;
  62039. }
  62040. RayHelper.CreateAndShow = function (ray, scene, color) {
  62041. var helper = new RayHelper(ray);
  62042. helper.show(scene, color);
  62043. return helper;
  62044. };
  62045. RayHelper.prototype.show = function (scene, color) {
  62046. if (!this._renderFunction && this.ray) {
  62047. var ray = this.ray;
  62048. this._renderFunction = this._render.bind(this);
  62049. this._scene = scene;
  62050. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62051. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62052. if (this._renderFunction) {
  62053. this._scene.registerBeforeRender(this._renderFunction);
  62054. }
  62055. }
  62056. if (color && this._renderLine) {
  62057. this._renderLine.color.copyFrom(color);
  62058. }
  62059. };
  62060. RayHelper.prototype.hide = function () {
  62061. if (this._renderFunction && this._scene) {
  62062. this._scene.unregisterBeforeRender(this._renderFunction);
  62063. this._scene = null;
  62064. this._renderFunction = null;
  62065. if (this._renderLine) {
  62066. this._renderLine.dispose();
  62067. this._renderLine = null;
  62068. }
  62069. this._renderPoints = [];
  62070. }
  62071. };
  62072. RayHelper.prototype._render = function () {
  62073. var ray = this.ray;
  62074. if (!ray) {
  62075. return;
  62076. }
  62077. var point = this._renderPoints[1];
  62078. var len = Math.min(ray.length, 1000000);
  62079. point.copyFrom(ray.direction);
  62080. point.scaleInPlace(len);
  62081. point.addInPlace(ray.origin);
  62082. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62083. };
  62084. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62085. this._attachedToMesh = mesh;
  62086. var ray = this.ray;
  62087. if (!ray) {
  62088. return;
  62089. }
  62090. if (!ray.direction) {
  62091. ray.direction = BABYLON.Vector3.Zero();
  62092. }
  62093. if (!ray.origin) {
  62094. ray.origin = BABYLON.Vector3.Zero();
  62095. }
  62096. if (length) {
  62097. ray.length = length;
  62098. }
  62099. if (!meshSpaceOrigin) {
  62100. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62101. }
  62102. if (!meshSpaceDirection) {
  62103. // -1 so that this will work with Mesh.lookAt
  62104. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62105. }
  62106. if (!this._meshSpaceDirection) {
  62107. this._meshSpaceDirection = meshSpaceDirection.clone();
  62108. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62109. }
  62110. else {
  62111. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62112. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62113. }
  62114. if (!this._updateToMeshFunction) {
  62115. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62116. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62117. }
  62118. this._updateToMesh();
  62119. };
  62120. RayHelper.prototype.detachFromMesh = function () {
  62121. if (this._attachedToMesh) {
  62122. if (this._updateToMeshFunction) {
  62123. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62124. }
  62125. this._attachedToMesh = null;
  62126. this._updateToMeshFunction = null;
  62127. }
  62128. };
  62129. RayHelper.prototype._updateToMesh = function () {
  62130. var ray = this.ray;
  62131. if (!this._attachedToMesh || !ray) {
  62132. return;
  62133. }
  62134. if (this._attachedToMesh._isDisposed) {
  62135. this.detachFromMesh();
  62136. return;
  62137. }
  62138. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62139. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62140. };
  62141. RayHelper.prototype.dispose = function () {
  62142. this.hide();
  62143. this.detachFromMesh();
  62144. this.ray = null;
  62145. };
  62146. return RayHelper;
  62147. }());
  62148. BABYLON.RayHelper = RayHelper;
  62149. })(BABYLON || (BABYLON = {}));
  62150. //# sourceMappingURL=babylon.rayHelper.js.map
  62151. var BABYLON;
  62152. (function (BABYLON) {
  62153. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62154. get: function () {
  62155. if (!this._debugLayer) {
  62156. this._debugLayer = new DebugLayer(this);
  62157. }
  62158. return this._debugLayer;
  62159. },
  62160. enumerable: true,
  62161. configurable: true
  62162. });
  62163. var DebugLayer = /** @class */ (function () {
  62164. function DebugLayer(scene) {
  62165. var _this = this;
  62166. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62167. this.onPropertyChangedObservable = new BABYLON.Observable();
  62168. this._scene = scene;
  62169. this._scene.onDisposeObservable.add(function () {
  62170. // Debug layer
  62171. if (_this._scene._debugLayer) {
  62172. _this._scene._debugLayer.hide();
  62173. }
  62174. });
  62175. }
  62176. /** Creates the inspector window. */
  62177. DebugLayer.prototype._createInspector = function (config) {
  62178. if (config === void 0) { config = {}; }
  62179. var popup = config.popup || false;
  62180. var initialTab = config.initialTab || 0;
  62181. var parentElement = config.parentElement || null;
  62182. if (!this._inspector) {
  62183. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62184. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62185. } // else nothing to do as instance is already created
  62186. };
  62187. DebugLayer.prototype.isVisible = function () {
  62188. if (!this._inspector) {
  62189. return false;
  62190. }
  62191. return true;
  62192. };
  62193. DebugLayer.prototype.hide = function () {
  62194. if (this._inspector) {
  62195. try {
  62196. this._inspector.dispose();
  62197. }
  62198. catch (e) {
  62199. // If the inspector has been removed directly from the inspector tool
  62200. }
  62201. this.onPropertyChangedObservable.clear();
  62202. this._inspector = null;
  62203. }
  62204. };
  62205. /**
  62206. *
  62207. * Launch the debugLayer.
  62208. *
  62209. * initialTab:
  62210. * | Value | Tab Name |
  62211. * | --- | --- |
  62212. * | 0 | Scene |
  62213. * | 1 | Console |
  62214. * | 2 | Stats |
  62215. * | 3 | Textures |
  62216. * | 4 | Mesh |
  62217. * | 5 | Light |
  62218. * | 6 | Material |
  62219. * | 7 | GLTF |
  62220. * | 8 | GUI |
  62221. * | 9 | Physics |
  62222. * | 10 | Camera |
  62223. * | 11 | Audio |
  62224. *
  62225. */
  62226. DebugLayer.prototype.show = function (config) {
  62227. if (config === void 0) { config = {}; }
  62228. if (typeof this.BJSINSPECTOR == 'undefined') {
  62229. // Load inspector and add it to the DOM
  62230. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62231. }
  62232. else {
  62233. // Otherwise creates the inspector
  62234. this._createInspector(config);
  62235. }
  62236. };
  62237. /**
  62238. * Gets the active tab
  62239. * @return the index of the active tab or -1 if the inspector is hidden
  62240. */
  62241. DebugLayer.prototype.getActiveTab = function () {
  62242. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62243. };
  62244. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62245. return DebugLayer;
  62246. }());
  62247. BABYLON.DebugLayer = DebugLayer;
  62248. })(BABYLON || (BABYLON = {}));
  62249. //# sourceMappingURL=babylon.debugLayer.js.map
  62250. var BABYLON;
  62251. (function (BABYLON) {
  62252. var Debug;
  62253. (function (Debug) {
  62254. /**
  62255. * Used to show the physics impostor around the specific mesh
  62256. */
  62257. var PhysicsViewer = /** @class */ (function () {
  62258. /**
  62259. * Creates a new PhysicsViewer
  62260. * @param scene defines the hosting scene
  62261. */
  62262. function PhysicsViewer(scene) {
  62263. /** @hidden */
  62264. this._impostors = [];
  62265. /** @hidden */
  62266. this._meshes = [];
  62267. /** @hidden */
  62268. this._numMeshes = 0;
  62269. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62270. var physicEngine = this._scene.getPhysicsEngine();
  62271. if (physicEngine) {
  62272. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62273. }
  62274. }
  62275. /** @hidden */
  62276. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62277. var plugin = this._physicsEnginePlugin;
  62278. for (var i = 0; i < this._numMeshes; i++) {
  62279. var impostor = this._impostors[i];
  62280. if (!impostor) {
  62281. continue;
  62282. }
  62283. if (impostor.isDisposed) {
  62284. this.hideImpostor(this._impostors[i--]);
  62285. }
  62286. else {
  62287. var mesh = this._meshes[i];
  62288. if (mesh && plugin) {
  62289. plugin.syncMeshWithImpostor(mesh, impostor);
  62290. }
  62291. }
  62292. }
  62293. };
  62294. /**
  62295. * Renders a specified physic impostor
  62296. * @param impostor defines the impostor to render
  62297. */
  62298. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62299. if (!this._scene) {
  62300. return;
  62301. }
  62302. for (var i = 0; i < this._numMeshes; i++) {
  62303. if (this._impostors[i] == impostor) {
  62304. return;
  62305. }
  62306. }
  62307. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62308. if (debugMesh) {
  62309. this._impostors[this._numMeshes] = impostor;
  62310. this._meshes[this._numMeshes] = debugMesh;
  62311. if (this._numMeshes === 0) {
  62312. this._renderFunction = this._updateDebugMeshes.bind(this);
  62313. this._scene.registerBeforeRender(this._renderFunction);
  62314. }
  62315. this._numMeshes++;
  62316. }
  62317. };
  62318. /**
  62319. * Hides a specified physic impostor
  62320. * @param impostor defines the impostor to hide
  62321. */
  62322. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62323. if (!impostor || !this._scene) {
  62324. return;
  62325. }
  62326. var removed = false;
  62327. for (var i = 0; i < this._numMeshes; i++) {
  62328. if (this._impostors[i] == impostor) {
  62329. var mesh = this._meshes[i];
  62330. if (!mesh) {
  62331. continue;
  62332. }
  62333. this._scene.removeMesh(mesh);
  62334. mesh.dispose();
  62335. this._numMeshes--;
  62336. if (this._numMeshes > 0) {
  62337. this._meshes[i] = this._meshes[this._numMeshes];
  62338. this._impostors[i] = this._impostors[this._numMeshes];
  62339. this._meshes[this._numMeshes] = null;
  62340. this._impostors[this._numMeshes] = null;
  62341. }
  62342. else {
  62343. this._meshes[0] = null;
  62344. this._impostors[0] = null;
  62345. }
  62346. removed = true;
  62347. break;
  62348. }
  62349. }
  62350. if (removed && this._numMeshes === 0) {
  62351. this._scene.unregisterBeforeRender(this._renderFunction);
  62352. }
  62353. };
  62354. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62355. if (!this._debugMaterial) {
  62356. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62357. this._debugMaterial.wireframe = true;
  62358. }
  62359. return this._debugMaterial;
  62360. };
  62361. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62362. if (!this._debugBoxMesh) {
  62363. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62364. this._debugBoxMesh.renderingGroupId = 1;
  62365. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62366. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62367. scene.removeMesh(this._debugBoxMesh);
  62368. }
  62369. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62370. };
  62371. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62372. if (!this._debugSphereMesh) {
  62373. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62374. this._debugSphereMesh.renderingGroupId = 1;
  62375. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62376. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62377. scene.removeMesh(this._debugSphereMesh);
  62378. }
  62379. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62380. };
  62381. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62382. var mesh = null;
  62383. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62384. mesh = this._getDebugBoxMesh(scene);
  62385. impostor.getBoxSizeToRef(mesh.scaling);
  62386. }
  62387. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62388. mesh = this._getDebugSphereMesh(scene);
  62389. var radius = impostor.getRadius();
  62390. mesh.scaling.x = radius * 2;
  62391. mesh.scaling.y = radius * 2;
  62392. mesh.scaling.z = radius * 2;
  62393. }
  62394. return mesh;
  62395. };
  62396. /** Releases all resources */
  62397. PhysicsViewer.prototype.dispose = function () {
  62398. for (var i = 0; i < this._numMeshes; i++) {
  62399. this.hideImpostor(this._impostors[i]);
  62400. }
  62401. if (this._debugBoxMesh) {
  62402. this._debugBoxMesh.dispose();
  62403. }
  62404. if (this._debugSphereMesh) {
  62405. this._debugSphereMesh.dispose();
  62406. }
  62407. if (this._debugMaterial) {
  62408. this._debugMaterial.dispose();
  62409. }
  62410. this._impostors.length = 0;
  62411. this._scene = null;
  62412. this._physicsEnginePlugin = null;
  62413. };
  62414. return PhysicsViewer;
  62415. }());
  62416. Debug.PhysicsViewer = PhysicsViewer;
  62417. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62418. })(BABYLON || (BABYLON = {}));
  62419. //# sourceMappingURL=babylon.physicsViewer.js.map
  62420. var BABYLON;
  62421. (function (BABYLON) {
  62422. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  62423. get: function () {
  62424. return this._forceShowBoundingBoxes || false;
  62425. },
  62426. set: function (value) {
  62427. this._forceShowBoundingBoxes = value;
  62428. // Lazyly creates a BB renderer if needed.
  62429. if (value) {
  62430. this.getBoundingBoxRenderer();
  62431. }
  62432. },
  62433. enumerable: true,
  62434. configurable: true
  62435. });
  62436. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  62437. if (!this._boundingBoxRenderer) {
  62438. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  62439. }
  62440. return this._boundingBoxRenderer;
  62441. };
  62442. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  62443. get: function () {
  62444. return this._showBoundingBox || false;
  62445. },
  62446. set: function (value) {
  62447. this._showBoundingBox = value;
  62448. // Lazyly creates a BB renderer if needed.
  62449. if (value) {
  62450. this.getScene().getBoundingBoxRenderer();
  62451. }
  62452. },
  62453. enumerable: true,
  62454. configurable: true
  62455. });
  62456. var BoundingBoxRenderer = /** @class */ (function () {
  62457. function BoundingBoxRenderer(scene) {
  62458. /**
  62459. * The component name helpfull to identify the component in the list of scene components.
  62460. */
  62461. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  62462. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62463. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62464. this.showBackLines = true;
  62465. this.renderList = new BABYLON.SmartArray(32);
  62466. this._vertexBuffers = {};
  62467. this.scene = scene;
  62468. scene._addComponent(this);
  62469. }
  62470. /**
  62471. * Registers the component in a given scene
  62472. */
  62473. BoundingBoxRenderer.prototype.register = function () {
  62474. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  62475. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  62476. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  62477. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  62478. };
  62479. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  62480. if (mesh.showSubMeshesBoundingBox) {
  62481. var boundingInfo = subMesh.getBoundingInfo();
  62482. if (boundingInfo !== null && boundingInfo !== undefined) {
  62483. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62484. this.renderList.push(boundingInfo.boundingBox);
  62485. }
  62486. }
  62487. };
  62488. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  62489. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  62490. var boundingInfo = sourceMesh.getBoundingInfo();
  62491. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62492. this.renderList.push(boundingInfo.boundingBox);
  62493. }
  62494. };
  62495. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62496. if (this._colorShader) {
  62497. return;
  62498. }
  62499. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  62500. attributes: [BABYLON.VertexBuffer.PositionKind],
  62501. uniforms: ["world", "viewProjection", "color"]
  62502. });
  62503. var engine = this.scene.getEngine();
  62504. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62505. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62506. this._createIndexBuffer();
  62507. };
  62508. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  62509. var engine = this.scene.getEngine();
  62510. 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]);
  62511. };
  62512. /**
  62513. * Rebuilds the elements related to this component in case of
  62514. * context lost for instance.
  62515. */
  62516. BoundingBoxRenderer.prototype.rebuild = function () {
  62517. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62518. if (vb) {
  62519. vb._rebuild();
  62520. }
  62521. this._createIndexBuffer();
  62522. };
  62523. BoundingBoxRenderer.prototype.reset = function () {
  62524. this.renderList.reset();
  62525. };
  62526. /**
  62527. * Render the bounding boxes of a specific rendering group
  62528. * @param renderingGroupId defines the rendering group to render
  62529. */
  62530. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  62531. if (this.renderList.length === 0) {
  62532. return;
  62533. }
  62534. this._prepareRessources();
  62535. if (!this._colorShader.isReady()) {
  62536. return;
  62537. }
  62538. var engine = this.scene.getEngine();
  62539. engine.setDepthWrite(false);
  62540. this._colorShader._preBind();
  62541. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62542. var boundingBox = this.renderList.data[boundingBoxIndex];
  62543. if (boundingBox._tag !== renderingGroupId) {
  62544. continue;
  62545. }
  62546. var min = boundingBox.minimum;
  62547. var max = boundingBox.maximum;
  62548. var diff = max.subtract(min);
  62549. var median = min.add(diff.scale(0.5));
  62550. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62551. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62552. .multiply(boundingBox.getWorldMatrix());
  62553. // VBOs
  62554. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62555. if (this.showBackLines) {
  62556. // Back
  62557. engine.setDepthFunctionToGreaterOrEqual();
  62558. this.scene.resetCachedMaterial();
  62559. this._colorShader.setColor4("color", this.backColor.toColor4());
  62560. this._colorShader.bind(worldMatrix);
  62561. // Draw order
  62562. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62563. }
  62564. // Front
  62565. engine.setDepthFunctionToLess();
  62566. this.scene.resetCachedMaterial();
  62567. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62568. this._colorShader.bind(worldMatrix);
  62569. // Draw order
  62570. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62571. }
  62572. this._colorShader.unbind();
  62573. engine.setDepthFunctionToLessOrEqual();
  62574. engine.setDepthWrite(true);
  62575. };
  62576. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  62577. this._prepareRessources();
  62578. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  62579. return;
  62580. }
  62581. var engine = this.scene.getEngine();
  62582. engine.setDepthWrite(false);
  62583. engine.setColorWrite(false);
  62584. this._colorShader._preBind();
  62585. var boundingBox = mesh._boundingInfo.boundingBox;
  62586. var min = boundingBox.minimum;
  62587. var max = boundingBox.maximum;
  62588. var diff = max.subtract(min);
  62589. var median = min.add(diff.scale(0.5));
  62590. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62591. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62592. .multiply(boundingBox.getWorldMatrix());
  62593. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62594. engine.setDepthFunctionToLess();
  62595. this.scene.resetCachedMaterial();
  62596. this._colorShader.bind(worldMatrix);
  62597. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62598. this._colorShader.unbind();
  62599. engine.setDepthFunctionToLessOrEqual();
  62600. engine.setDepthWrite(true);
  62601. engine.setColorWrite(true);
  62602. };
  62603. BoundingBoxRenderer.prototype.dispose = function () {
  62604. if (!this._colorShader) {
  62605. return;
  62606. }
  62607. this.renderList.dispose();
  62608. this._colorShader.dispose();
  62609. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62610. if (buffer) {
  62611. buffer.dispose();
  62612. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62613. }
  62614. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  62615. };
  62616. return BoundingBoxRenderer;
  62617. }());
  62618. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  62619. })(BABYLON || (BABYLON = {}));
  62620. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  62621. var BABYLON;
  62622. (function (BABYLON) {
  62623. BABYLON.Engine.prototype.createTransformFeedback = function () {
  62624. return this._gl.createTransformFeedback();
  62625. };
  62626. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  62627. this._gl.deleteTransformFeedback(value);
  62628. };
  62629. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  62630. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  62631. };
  62632. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  62633. if (usePoints === void 0) { usePoints = true; }
  62634. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  62635. };
  62636. BABYLON.Engine.prototype.endTransformFeedback = function () {
  62637. this._gl.endTransformFeedback();
  62638. };
  62639. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  62640. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  62641. };
  62642. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  62643. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  62644. };
  62645. })(BABYLON || (BABYLON = {}));
  62646. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  62647. var BABYLON;
  62648. (function (BABYLON) {
  62649. /**
  62650. * This represents a GPU particle system in Babylon
  62651. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  62652. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  62653. */
  62654. var GPUParticleSystem = /** @class */ (function (_super) {
  62655. __extends(GPUParticleSystem, _super);
  62656. /**
  62657. * Instantiates a GPU particle system.
  62658. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  62659. * @param name The name of the particle system
  62660. * @param options The options used to create the system
  62661. * @param scene The scene the particle system belongs to
  62662. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  62663. */
  62664. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  62665. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  62666. var _this = _super.call(this, name) || this;
  62667. /**
  62668. * The layer mask we are rendering the particles through.
  62669. */
  62670. _this.layerMask = 0x0FFFFFFF;
  62671. _this._accumulatedCount = 0;
  62672. _this._targetIndex = 0;
  62673. _this._currentRenderId = -1;
  62674. _this._started = false;
  62675. _this._stopped = false;
  62676. _this._timeDelta = 0;
  62677. _this._attributesStrideSize = 21;
  62678. _this._actualFrame = 0;
  62679. _this._rawTextureWidth = 256;
  62680. /**
  62681. * An event triggered when the system is disposed.
  62682. */
  62683. _this.onDisposeObservable = new BABYLON.Observable();
  62684. /**
  62685. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  62686. * to override the particles.
  62687. */
  62688. _this.forceDepthWrite = false;
  62689. _this._preWarmDone = false;
  62690. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62691. // Setup the default processing configuration to the scene.
  62692. _this._attachImageProcessingConfiguration(null);
  62693. _this._engine = _this._scene.getEngine();
  62694. if (!options.randomTextureSize) {
  62695. delete options.randomTextureSize;
  62696. }
  62697. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  62698. var optionsAsNumber = options;
  62699. if (isFinite(optionsAsNumber)) {
  62700. fullOptions.capacity = optionsAsNumber;
  62701. }
  62702. _this._capacity = fullOptions.capacity;
  62703. _this._activeCount = fullOptions.capacity;
  62704. _this._currentActiveCount = 0;
  62705. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  62706. _this._scene.particleSystems.push(_this);
  62707. _this._updateEffectOptions = {
  62708. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  62709. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  62710. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  62711. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  62712. uniformBuffersNames: [],
  62713. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  62714. defines: "",
  62715. fallbacks: null,
  62716. onCompiled: null,
  62717. onError: null,
  62718. indexParameters: null,
  62719. maxSimultaneousLights: 0,
  62720. transformFeedbackVaryings: []
  62721. };
  62722. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  62723. // Random data
  62724. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  62725. var d = [];
  62726. for (var i = 0; i < maxTextureSize; ++i) {
  62727. d.push(Math.random());
  62728. d.push(Math.random());
  62729. d.push(Math.random());
  62730. d.push(Math.random());
  62731. }
  62732. _this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  62733. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62734. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62735. d = [];
  62736. for (var i = 0; i < maxTextureSize; ++i) {
  62737. d.push(Math.random());
  62738. d.push(Math.random());
  62739. d.push(Math.random());
  62740. d.push(Math.random());
  62741. }
  62742. _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  62743. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62744. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62745. _this._randomTextureSize = maxTextureSize;
  62746. return _this;
  62747. }
  62748. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  62749. /**
  62750. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  62751. */
  62752. get: function () {
  62753. if (!BABYLON.Engine.LastCreatedEngine) {
  62754. return false;
  62755. }
  62756. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  62757. },
  62758. enumerable: true,
  62759. configurable: true
  62760. });
  62761. /**
  62762. * Gets the maximum number of particles active at the same time.
  62763. * @returns The max number of active particles.
  62764. */
  62765. GPUParticleSystem.prototype.getCapacity = function () {
  62766. return this._capacity;
  62767. };
  62768. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  62769. /**
  62770. * Gets or set the number of active particles
  62771. */
  62772. get: function () {
  62773. return this._activeCount;
  62774. },
  62775. set: function (value) {
  62776. this._activeCount = Math.min(value, this._capacity);
  62777. },
  62778. enumerable: true,
  62779. configurable: true
  62780. });
  62781. /**
  62782. * Is this system ready to be used/rendered
  62783. * @return true if the system is ready
  62784. */
  62785. GPUParticleSystem.prototype.isReady = function () {
  62786. if (!this._updateEffect) {
  62787. this._recreateUpdateEffect();
  62788. this._recreateRenderEffect();
  62789. return false;
  62790. }
  62791. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  62792. return false;
  62793. }
  62794. return true;
  62795. };
  62796. /**
  62797. * Gets if the system has been started. (Note: this will still be true after stop is called)
  62798. * @returns True if it has been started, otherwise false.
  62799. */
  62800. GPUParticleSystem.prototype.isStarted = function () {
  62801. return this._started;
  62802. };
  62803. /**
  62804. * Starts the particle system and begins to emit
  62805. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  62806. */
  62807. GPUParticleSystem.prototype.start = function (delay) {
  62808. var _this = this;
  62809. if (delay === void 0) { delay = this.startDelay; }
  62810. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  62811. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  62812. }
  62813. if (delay) {
  62814. setTimeout(function () {
  62815. _this.start(0);
  62816. }, delay);
  62817. return;
  62818. }
  62819. this._started = true;
  62820. this._stopped = false;
  62821. this._preWarmDone = false;
  62822. };
  62823. /**
  62824. * Stops the particle system.
  62825. */
  62826. GPUParticleSystem.prototype.stop = function () {
  62827. this._stopped = true;
  62828. };
  62829. /**
  62830. * Remove all active particles
  62831. */
  62832. GPUParticleSystem.prototype.reset = function () {
  62833. this._releaseBuffers();
  62834. this._releaseVAOs();
  62835. this._currentActiveCount = 0;
  62836. this._targetIndex = 0;
  62837. };
  62838. /**
  62839. * Returns the string "GPUParticleSystem"
  62840. * @returns a string containing the class name
  62841. */
  62842. GPUParticleSystem.prototype.getClassName = function () {
  62843. return "GPUParticleSystem";
  62844. };
  62845. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  62846. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  62847. this._releaseBuffers();
  62848. return this;
  62849. };
  62850. /**
  62851. * Adds a new color gradient
  62852. * @param gradient defines the gradient to use (between 0 and 1)
  62853. * @param color1 defines the color to affect to the specified gradient
  62854. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  62855. * @returns the current particle system
  62856. */
  62857. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  62858. if (!this._colorGradients) {
  62859. this._colorGradients = [];
  62860. }
  62861. var colorGradient = new BABYLON.ColorGradient();
  62862. colorGradient.gradient = gradient;
  62863. colorGradient.color1 = color1;
  62864. this._colorGradients.push(colorGradient);
  62865. this._colorGradients.sort(function (a, b) {
  62866. if (a.gradient < b.gradient) {
  62867. return -1;
  62868. }
  62869. else if (a.gradient > b.gradient) {
  62870. return 1;
  62871. }
  62872. return 0;
  62873. });
  62874. if (this._colorGradientsTexture) {
  62875. this._colorGradientsTexture.dispose();
  62876. this._colorGradientsTexture = null;
  62877. }
  62878. this._releaseBuffers();
  62879. return this;
  62880. };
  62881. /**
  62882. * Remove a specific color gradient
  62883. * @param gradient defines the gradient to remove
  62884. * @returns the current particle system
  62885. */
  62886. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  62887. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  62888. this._colorGradientsTexture = null;
  62889. return this;
  62890. };
  62891. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  62892. var valueGradient = new BABYLON.FactorGradient();
  62893. valueGradient.gradient = gradient;
  62894. valueGradient.factor1 = factor;
  62895. factorGradients.push(valueGradient);
  62896. factorGradients.sort(function (a, b) {
  62897. if (a.gradient < b.gradient) {
  62898. return -1;
  62899. }
  62900. else if (a.gradient > b.gradient) {
  62901. return 1;
  62902. }
  62903. return 0;
  62904. });
  62905. this._releaseBuffers();
  62906. };
  62907. /**
  62908. * Adds a new size gradient
  62909. * @param gradient defines the gradient to use (between 0 and 1)
  62910. * @param factor defines the size factor to affect to the specified gradient
  62911. * @returns the current particle system
  62912. */
  62913. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  62914. if (!this._sizeGradients) {
  62915. this._sizeGradients = [];
  62916. }
  62917. this._addFactorGradient(this._sizeGradients, gradient, factor);
  62918. if (this._sizeGradientsTexture) {
  62919. this._sizeGradientsTexture.dispose();
  62920. this._sizeGradientsTexture = null;
  62921. }
  62922. this._releaseBuffers();
  62923. return this;
  62924. };
  62925. /**
  62926. * Remove a specific size gradient
  62927. * @param gradient defines the gradient to remove
  62928. * @returns the current particle system
  62929. */
  62930. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  62931. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  62932. this._sizeGradientsTexture = null;
  62933. return this;
  62934. };
  62935. /**
  62936. * Adds a new angular speed gradient
  62937. * @param gradient defines the gradient to use (between 0 and 1)
  62938. * @param factor defines the angular speed to affect to the specified gradient
  62939. * @returns the current particle system
  62940. */
  62941. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  62942. if (!this._angularSpeedGradients) {
  62943. this._angularSpeedGradients = [];
  62944. }
  62945. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  62946. if (this._angularSpeedGradientsTexture) {
  62947. this._angularSpeedGradientsTexture.dispose();
  62948. this._angularSpeedGradientsTexture = null;
  62949. }
  62950. this._releaseBuffers();
  62951. return this;
  62952. };
  62953. /**
  62954. * Remove a specific angular speed gradient
  62955. * @param gradient defines the gradient to remove
  62956. * @returns the current particle system
  62957. */
  62958. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  62959. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  62960. this._angularSpeedGradientsTexture = null;
  62961. return this;
  62962. };
  62963. /**
  62964. * Adds a new velocity gradient
  62965. * @param gradient defines the gradient to use (between 0 and 1)
  62966. * @param factor defines the velocity to affect to the specified gradient
  62967. * @returns the current particle system
  62968. */
  62969. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  62970. if (!this._velocityGradients) {
  62971. this._velocityGradients = [];
  62972. }
  62973. this._addFactorGradient(this._velocityGradients, gradient, factor);
  62974. if (this._velocityGradientsTexture) {
  62975. this._velocityGradientsTexture.dispose();
  62976. this._velocityGradientsTexture = null;
  62977. }
  62978. this._releaseBuffers();
  62979. return this;
  62980. };
  62981. /**
  62982. * Remove a specific velocity gradient
  62983. * @param gradient defines the gradient to remove
  62984. * @returns the current particle system
  62985. */
  62986. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  62987. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  62988. this._velocityGradientsTexture = null;
  62989. return this;
  62990. };
  62991. /**
  62992. * Adds a new limit velocity gradient
  62993. * @param gradient defines the gradient to use (between 0 and 1)
  62994. * @param factor defines the limit velocity value to affect to the specified gradient
  62995. * @returns the current particle system
  62996. */
  62997. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  62998. if (!this._limitVelocityGradients) {
  62999. this._limitVelocityGradients = [];
  63000. }
  63001. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63002. if (this._limitVelocityGradientsTexture) {
  63003. this._limitVelocityGradientsTexture.dispose();
  63004. this._limitVelocityGradientsTexture = null;
  63005. }
  63006. this._releaseBuffers();
  63007. return this;
  63008. };
  63009. /**
  63010. * Remove a specific limit velocity gradient
  63011. * @param gradient defines the gradient to remove
  63012. * @returns the current particle system
  63013. */
  63014. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63015. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63016. this._limitVelocityGradientsTexture = null;
  63017. return this;
  63018. };
  63019. /**
  63020. * Adds a new drag gradient
  63021. * @param gradient defines the gradient to use (between 0 and 1)
  63022. * @param factor defines the drag value to affect to the specified gradient
  63023. * @returns the current particle system
  63024. */
  63025. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63026. if (!this._dragGradients) {
  63027. this._dragGradients = [];
  63028. }
  63029. this._addFactorGradient(this._dragGradients, gradient, factor);
  63030. if (this._dragGradientsTexture) {
  63031. this._dragGradientsTexture.dispose();
  63032. this._dragGradientsTexture = null;
  63033. }
  63034. this._releaseBuffers();
  63035. return this;
  63036. };
  63037. /**
  63038. * Remove a specific drag gradient
  63039. * @param gradient defines the gradient to remove
  63040. * @returns the current particle system
  63041. */
  63042. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63043. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63044. this._dragGradientsTexture = null;
  63045. return this;
  63046. };
  63047. /**
  63048. * Not supported by GPUParticleSystem
  63049. * @param gradient defines the gradient to use (between 0 and 1)
  63050. * @param factor defines the emit rate value to affect to the specified gradient
  63051. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63052. * @returns the current particle system
  63053. */
  63054. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63055. // Do nothing as emit rate is not supported by GPUParticleSystem
  63056. return this;
  63057. };
  63058. /**
  63059. * Not supported by GPUParticleSystem
  63060. * @param gradient defines the gradient to remove
  63061. * @returns the current particle system
  63062. */
  63063. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63064. // Do nothing as emit rate is not supported by GPUParticleSystem
  63065. return this;
  63066. };
  63067. /**
  63068. * Not supported by GPUParticleSystem
  63069. * @param gradient defines the gradient to use (between 0 and 1)
  63070. * @param factor defines the start size value to affect to the specified gradient
  63071. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63072. * @returns the current particle system
  63073. */
  63074. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63075. // Do nothing as start size is not supported by GPUParticleSystem
  63076. return this;
  63077. };
  63078. /**
  63079. * Not supported by GPUParticleSystem
  63080. * @param gradient defines the gradient to remove
  63081. * @returns the current particle system
  63082. */
  63083. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63084. // Do nothing as start size is not supported by GPUParticleSystem
  63085. return this;
  63086. };
  63087. /**
  63088. * Not supported by GPUParticleSystem
  63089. * @param gradient defines the gradient to use (between 0 and 1)
  63090. * @param min defines the color remap minimal range
  63091. * @param max defines the color remap maximal range
  63092. * @returns the current particle system
  63093. */
  63094. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63095. // Do nothing as start size is not supported by GPUParticleSystem
  63096. return this;
  63097. };
  63098. /**
  63099. * Not supported by GPUParticleSystem
  63100. * @param gradient defines the gradient to remove
  63101. * @returns the current particle system
  63102. */
  63103. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63104. // Do nothing as start size is not supported by GPUParticleSystem
  63105. return this;
  63106. };
  63107. /**
  63108. * Not supported by GPUParticleSystem
  63109. * @param gradient defines the gradient to use (between 0 and 1)
  63110. * @param min defines the alpha remap minimal range
  63111. * @param max defines the alpha remap maximal range
  63112. * @returns the current particle system
  63113. */
  63114. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63115. // Do nothing as start size is not supported by GPUParticleSystem
  63116. return this;
  63117. };
  63118. /**
  63119. * Not supported by GPUParticleSystem
  63120. * @param gradient defines the gradient to remove
  63121. * @returns the current particle system
  63122. */
  63123. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63124. // Do nothing as start size is not supported by GPUParticleSystem
  63125. return this;
  63126. };
  63127. /**
  63128. * Not supported by GPUParticleSystem
  63129. * @param gradient defines the gradient to use (between 0 and 1)
  63130. * @param color defines the color to affect to the specified gradient
  63131. * @returns the current particle system
  63132. */
  63133. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63134. //Not supported by GPUParticleSystem
  63135. return this;
  63136. };
  63137. /**
  63138. * Not supported by GPUParticleSystem
  63139. * @param gradient defines the gradient to remove
  63140. * @returns the current particle system
  63141. */
  63142. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63143. //Not supported by GPUParticleSystem
  63144. return this;
  63145. };
  63146. /**
  63147. * Not supported by GPUParticleSystem
  63148. * @returns the list of ramp gradients
  63149. */
  63150. GPUParticleSystem.prototype.getRampGradients = function () {
  63151. return null;
  63152. };
  63153. GPUParticleSystem.prototype._reset = function () {
  63154. this._releaseBuffers();
  63155. };
  63156. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63157. var updateVertexBuffers = {};
  63158. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63159. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63160. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63161. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63162. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63163. var offset = 12;
  63164. if (!this._colorGradientsTexture) {
  63165. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63166. offset += 4;
  63167. }
  63168. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63169. offset += 3;
  63170. if (!this._isBillboardBased) {
  63171. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63172. offset += 3;
  63173. }
  63174. if (this._angularSpeedGradientsTexture) {
  63175. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63176. offset += 1;
  63177. }
  63178. else {
  63179. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63180. offset += 2;
  63181. }
  63182. if (this._isAnimationSheetEnabled) {
  63183. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63184. offset += 1;
  63185. if (this.spriteRandomStartCell) {
  63186. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63187. offset += 1;
  63188. }
  63189. }
  63190. if (this.noiseTexture) {
  63191. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63192. offset += 3;
  63193. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63194. offset += 3;
  63195. }
  63196. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63197. this._engine.bindArrayBuffer(null);
  63198. return vao;
  63199. };
  63200. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63201. var renderVertexBuffers = {};
  63202. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63203. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63204. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63205. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63206. var offset = 12;
  63207. if (!this._colorGradientsTexture) {
  63208. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63209. offset += 4;
  63210. }
  63211. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63212. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63213. }
  63214. offset += 3; // Direction
  63215. if (!this._isBillboardBased) {
  63216. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63217. offset += 3;
  63218. }
  63219. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63220. if (this._angularSpeedGradientsTexture) {
  63221. offset++;
  63222. }
  63223. else {
  63224. offset += 2;
  63225. }
  63226. if (this._isAnimationSheetEnabled) {
  63227. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63228. offset += 1;
  63229. if (this.spriteRandomStartCell) {
  63230. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63231. offset += 1;
  63232. }
  63233. }
  63234. if (this.noiseTexture) {
  63235. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63236. offset += 3;
  63237. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63238. offset += 3;
  63239. }
  63240. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63241. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63242. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63243. this._engine.bindArrayBuffer(null);
  63244. return vao;
  63245. };
  63246. GPUParticleSystem.prototype._initialize = function (force) {
  63247. if (force === void 0) { force = false; }
  63248. if (this._buffer0 && !force) {
  63249. return;
  63250. }
  63251. var engine = this._scene.getEngine();
  63252. var data = new Array();
  63253. if (!this.isBillboardBased) {
  63254. this._attributesStrideSize += 3;
  63255. }
  63256. if (this._colorGradientsTexture) {
  63257. this._attributesStrideSize -= 4;
  63258. }
  63259. if (this._angularSpeedGradientsTexture) {
  63260. this._attributesStrideSize -= 1;
  63261. }
  63262. if (this._isAnimationSheetEnabled) {
  63263. this._attributesStrideSize += 1;
  63264. if (this.spriteRandomStartCell) {
  63265. this._attributesStrideSize += 1;
  63266. }
  63267. }
  63268. if (this.noiseTexture) {
  63269. this._attributesStrideSize += 6;
  63270. }
  63271. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63272. // position
  63273. data.push(0.0);
  63274. data.push(0.0);
  63275. data.push(0.0);
  63276. // Age and life
  63277. data.push(0.0); // create the particle as a dead one to create a new one at start
  63278. data.push(0.0);
  63279. // Seed
  63280. data.push(Math.random());
  63281. data.push(Math.random());
  63282. data.push(Math.random());
  63283. data.push(Math.random());
  63284. // Size
  63285. data.push(0.0);
  63286. data.push(0.0);
  63287. data.push(0.0);
  63288. if (!this._colorGradientsTexture) {
  63289. // color
  63290. data.push(0.0);
  63291. data.push(0.0);
  63292. data.push(0.0);
  63293. data.push(0.0);
  63294. }
  63295. // direction
  63296. data.push(0.0);
  63297. data.push(0.0);
  63298. data.push(0.0);
  63299. if (!this.isBillboardBased) {
  63300. // initialDirection
  63301. data.push(0.0);
  63302. data.push(0.0);
  63303. data.push(0.0);
  63304. }
  63305. // angle
  63306. data.push(0.0);
  63307. if (!this._angularSpeedGradientsTexture) {
  63308. data.push(0.0);
  63309. }
  63310. if (this._isAnimationSheetEnabled) {
  63311. data.push(0.0);
  63312. if (this.spriteRandomStartCell) {
  63313. data.push(0.0);
  63314. }
  63315. }
  63316. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  63317. data.push(Math.random());
  63318. data.push(Math.random());
  63319. data.push(Math.random());
  63320. data.push(Math.random());
  63321. data.push(Math.random());
  63322. data.push(Math.random());
  63323. }
  63324. }
  63325. // Sprite data
  63326. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  63327. -0.5, 0.5, 0, 1,
  63328. -0.5, -0.5, 0, 0,
  63329. 0.5, -0.5, 1, 0]);
  63330. // Buffers
  63331. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63332. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63333. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  63334. // Update VAO
  63335. this._updateVAO = [];
  63336. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  63337. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  63338. // Render VAO
  63339. this._renderVAO = [];
  63340. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  63341. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  63342. // Links
  63343. this._sourceBuffer = this._buffer0;
  63344. this._targetBuffer = this._buffer1;
  63345. };
  63346. /** @hidden */
  63347. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  63348. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  63349. if (this._isBillboardBased) {
  63350. defines += "\n#define BILLBOARD";
  63351. }
  63352. if (this._colorGradientsTexture) {
  63353. defines += "\n#define COLORGRADIENTS";
  63354. }
  63355. if (this._sizeGradientsTexture) {
  63356. defines += "\n#define SIZEGRADIENTS";
  63357. }
  63358. if (this._angularSpeedGradientsTexture) {
  63359. defines += "\n#define ANGULARSPEEDGRADIENTS";
  63360. }
  63361. if (this._velocityGradientsTexture) {
  63362. defines += "\n#define VELOCITYGRADIENTS";
  63363. }
  63364. if (this._limitVelocityGradientsTexture) {
  63365. defines += "\n#define LIMITVELOCITYGRADIENTS";
  63366. }
  63367. if (this._dragGradientsTexture) {
  63368. defines += "\n#define DRAGGRADIENTS";
  63369. }
  63370. if (this.isAnimationSheetEnabled) {
  63371. defines += "\n#define ANIMATESHEET";
  63372. if (this.spriteRandomStartCell) {
  63373. defines += "\n#define ANIMATESHEETRANDOMSTART";
  63374. }
  63375. }
  63376. if (this.noiseTexture) {
  63377. defines += "\n#define NOISE";
  63378. }
  63379. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  63380. return;
  63381. }
  63382. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  63383. if (!this._colorGradientsTexture) {
  63384. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  63385. }
  63386. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  63387. if (!this._isBillboardBased) {
  63388. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  63389. }
  63390. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  63391. if (this.isAnimationSheetEnabled) {
  63392. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  63393. if (this.spriteRandomStartCell) {
  63394. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  63395. }
  63396. }
  63397. if (this.noiseTexture) {
  63398. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  63399. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  63400. }
  63401. this._updateEffectOptions.defines = defines;
  63402. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  63403. };
  63404. /** @hidden */
  63405. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  63406. var defines = "";
  63407. if (this._scene.clipPlane) {
  63408. defines = "\n#define CLIPPLANE";
  63409. }
  63410. if (this._scene.clipPlane2) {
  63411. defines = "\n#define CLIPPLANE2";
  63412. }
  63413. if (this._scene.clipPlane3) {
  63414. defines = "\n#define CLIPPLANE3";
  63415. }
  63416. if (this._scene.clipPlane4) {
  63417. defines = "\n#define CLIPPLANE4";
  63418. }
  63419. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  63420. defines = "\n#define BLENDMULTIPLYMODE";
  63421. }
  63422. if (this._isBillboardBased) {
  63423. defines += "\n#define BILLBOARD";
  63424. switch (this.billboardMode) {
  63425. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  63426. defines += "\n#define BILLBOARDY";
  63427. break;
  63428. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  63429. defines += "\n#define BILLBOARDSTRETCHED";
  63430. break;
  63431. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  63432. default:
  63433. break;
  63434. }
  63435. }
  63436. if (this._colorGradientsTexture) {
  63437. defines += "\n#define COLORGRADIENTS";
  63438. }
  63439. if (this.isAnimationSheetEnabled) {
  63440. defines += "\n#define ANIMATESHEET";
  63441. }
  63442. if (this._imageProcessingConfiguration) {
  63443. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  63444. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  63445. }
  63446. if (this._renderEffect && this._renderEffect.defines === defines) {
  63447. return;
  63448. }
  63449. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  63450. var samplers = ["textureSampler", "colorGradientSampler"];
  63451. if (BABYLON.ImageProcessingConfiguration) {
  63452. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  63453. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  63454. }
  63455. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  63456. };
  63457. /**
  63458. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  63459. * @param preWarm defines if we are in the pre-warmimg phase
  63460. */
  63461. GPUParticleSystem.prototype.animate = function (preWarm) {
  63462. if (preWarm === void 0) { preWarm = false; }
  63463. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  63464. this._actualFrame += this._timeDelta;
  63465. if (!this._stopped) {
  63466. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  63467. this.stop();
  63468. }
  63469. }
  63470. };
  63471. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  63472. var texture = this[textureName];
  63473. if (!factorGradients || !factorGradients.length || texture) {
  63474. return;
  63475. }
  63476. var data = new Float32Array(this._rawTextureWidth);
  63477. for (var x = 0; x < this._rawTextureWidth; x++) {
  63478. var ratio = x / this._rawTextureWidth;
  63479. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  63480. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  63481. });
  63482. }
  63483. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63484. };
  63485. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  63486. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  63487. };
  63488. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  63489. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  63490. };
  63491. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  63492. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  63493. };
  63494. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  63495. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  63496. };
  63497. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  63498. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  63499. };
  63500. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  63501. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  63502. return;
  63503. }
  63504. var data = new Uint8Array(this._rawTextureWidth * 4);
  63505. var tmpColor = BABYLON.Tmp.Color4[0];
  63506. for (var x = 0; x < this._rawTextureWidth; x++) {
  63507. var ratio = x / this._rawTextureWidth;
  63508. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  63509. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  63510. data[x * 4] = tmpColor.r * 255;
  63511. data[x * 4 + 1] = tmpColor.g * 255;
  63512. data[x * 4 + 2] = tmpColor.b * 255;
  63513. data[x * 4 + 3] = tmpColor.a * 255;
  63514. });
  63515. }
  63516. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63517. };
  63518. /**
  63519. * Renders the particle system in its current state
  63520. * @param preWarm defines if the system should only update the particles but not render them
  63521. * @returns the current number of particles
  63522. */
  63523. GPUParticleSystem.prototype.render = function (preWarm) {
  63524. if (preWarm === void 0) { preWarm = false; }
  63525. if (!this._started) {
  63526. return 0;
  63527. }
  63528. this._createColorGradientTexture();
  63529. this._createSizeGradientTexture();
  63530. this._createAngularSpeedGradientTexture();
  63531. this._createVelocityGradientTexture();
  63532. this._createLimitVelocityGradientTexture();
  63533. this._createDragGradientTexture();
  63534. this._recreateUpdateEffect();
  63535. this._recreateRenderEffect();
  63536. if (!this.isReady()) {
  63537. return 0;
  63538. }
  63539. if (!preWarm) {
  63540. if (!this._preWarmDone && this.preWarmCycles) {
  63541. for (var index = 0; index < this.preWarmCycles; index++) {
  63542. this.animate(true);
  63543. this.render(true);
  63544. }
  63545. this._preWarmDone = true;
  63546. }
  63547. if (this._currentRenderId === this._scene.getRenderId()) {
  63548. return 0;
  63549. }
  63550. this._currentRenderId = this._scene.getRenderId();
  63551. }
  63552. // Get everything ready to render
  63553. this._initialize();
  63554. this._accumulatedCount += this.emitRate * this._timeDelta;
  63555. if (this._accumulatedCount > 1) {
  63556. var intPart = this._accumulatedCount | 0;
  63557. this._accumulatedCount -= intPart;
  63558. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  63559. }
  63560. if (!this._currentActiveCount) {
  63561. return 0;
  63562. }
  63563. // Enable update effect
  63564. this._engine.enableEffect(this._updateEffect);
  63565. this._engine.setState(false);
  63566. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  63567. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  63568. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  63569. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  63570. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  63571. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  63572. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  63573. if (!this._colorGradientsTexture) {
  63574. this._updateEffect.setDirectColor4("color1", this.color1);
  63575. this._updateEffect.setDirectColor4("color2", this.color2);
  63576. }
  63577. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  63578. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  63579. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  63580. this._updateEffect.setVector3("gravity", this.gravity);
  63581. if (this._sizeGradientsTexture) {
  63582. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  63583. }
  63584. if (this._angularSpeedGradientsTexture) {
  63585. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  63586. }
  63587. if (this._velocityGradientsTexture) {
  63588. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  63589. }
  63590. if (this._limitVelocityGradientsTexture) {
  63591. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  63592. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  63593. }
  63594. if (this._dragGradientsTexture) {
  63595. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  63596. }
  63597. if (this.particleEmitterType) {
  63598. this.particleEmitterType.applyToShader(this._updateEffect);
  63599. }
  63600. if (this._isAnimationSheetEnabled) {
  63601. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  63602. }
  63603. if (this.noiseTexture) {
  63604. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  63605. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  63606. }
  63607. var emitterWM;
  63608. if (this.emitter.position) {
  63609. var emitterMesh = this.emitter;
  63610. emitterWM = emitterMesh.getWorldMatrix();
  63611. }
  63612. else {
  63613. var emitterPosition = this.emitter;
  63614. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  63615. }
  63616. this._updateEffect.setMatrix("emitterWM", emitterWM);
  63617. // Bind source VAO
  63618. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  63619. // Update
  63620. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  63621. this._engine.setRasterizerState(false);
  63622. this._engine.beginTransformFeedback(true);
  63623. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  63624. this._engine.endTransformFeedback();
  63625. this._engine.setRasterizerState(true);
  63626. this._engine.bindTransformFeedbackBuffer(null);
  63627. if (!preWarm) {
  63628. // Enable render effect
  63629. this._engine.enableEffect(this._renderEffect);
  63630. var viewMatrix = this._scene.getViewMatrix();
  63631. this._renderEffect.setMatrix("view", viewMatrix);
  63632. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  63633. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  63634. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  63635. if (this._colorGradientsTexture) {
  63636. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  63637. }
  63638. else {
  63639. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  63640. }
  63641. if (this._isAnimationSheetEnabled && this.particleTexture) {
  63642. var baseSize = this.particleTexture.getBaseSize();
  63643. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  63644. }
  63645. if (this._isBillboardBased) {
  63646. var camera = this._scene.activeCamera;
  63647. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  63648. }
  63649. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  63650. var invView = viewMatrix.clone();
  63651. invView.invert();
  63652. this._renderEffect.setMatrix("invView", invView);
  63653. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  63654. }
  63655. // image processing
  63656. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  63657. this._imageProcessingConfiguration.bind(this._renderEffect);
  63658. }
  63659. // Draw order
  63660. switch (this.blendMode) {
  63661. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  63662. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  63663. break;
  63664. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  63665. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  63666. break;
  63667. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  63668. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  63669. break;
  63670. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  63671. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  63672. break;
  63673. }
  63674. if (this.forceDepthWrite) {
  63675. this._engine.setDepthWrite(true);
  63676. }
  63677. // Bind source VAO
  63678. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  63679. // Render
  63680. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  63681. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  63682. }
  63683. // Switch VAOs
  63684. this._targetIndex++;
  63685. if (this._targetIndex === 2) {
  63686. this._targetIndex = 0;
  63687. }
  63688. // Switch buffers
  63689. var tmpBuffer = this._sourceBuffer;
  63690. this._sourceBuffer = this._targetBuffer;
  63691. this._targetBuffer = tmpBuffer;
  63692. return this._currentActiveCount;
  63693. };
  63694. /**
  63695. * Rebuilds the particle system
  63696. */
  63697. GPUParticleSystem.prototype.rebuild = function () {
  63698. this._initialize(true);
  63699. };
  63700. GPUParticleSystem.prototype._releaseBuffers = function () {
  63701. if (this._buffer0) {
  63702. this._buffer0.dispose();
  63703. this._buffer0 = null;
  63704. }
  63705. if (this._buffer1) {
  63706. this._buffer1.dispose();
  63707. this._buffer1 = null;
  63708. }
  63709. if (this._spriteBuffer) {
  63710. this._spriteBuffer.dispose();
  63711. this._spriteBuffer = null;
  63712. }
  63713. };
  63714. GPUParticleSystem.prototype._releaseVAOs = function () {
  63715. if (!this._updateVAO) {
  63716. return;
  63717. }
  63718. for (var index = 0; index < this._updateVAO.length; index++) {
  63719. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  63720. }
  63721. this._updateVAO = [];
  63722. for (var index = 0; index < this._renderVAO.length; index++) {
  63723. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  63724. }
  63725. this._renderVAO = [];
  63726. };
  63727. /**
  63728. * Disposes the particle system and free the associated resources
  63729. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  63730. */
  63731. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  63732. if (disposeTexture === void 0) { disposeTexture = true; }
  63733. var index = this._scene.particleSystems.indexOf(this);
  63734. if (index > -1) {
  63735. this._scene.particleSystems.splice(index, 1);
  63736. }
  63737. this._releaseBuffers();
  63738. this._releaseVAOs();
  63739. if (this._colorGradientsTexture) {
  63740. this._colorGradientsTexture.dispose();
  63741. this._colorGradientsTexture = null;
  63742. }
  63743. if (this._sizeGradientsTexture) {
  63744. this._sizeGradientsTexture.dispose();
  63745. this._sizeGradientsTexture = null;
  63746. }
  63747. if (this._angularSpeedGradientsTexture) {
  63748. this._angularSpeedGradientsTexture.dispose();
  63749. this._angularSpeedGradientsTexture = null;
  63750. }
  63751. if (this._velocityGradientsTexture) {
  63752. this._velocityGradientsTexture.dispose();
  63753. this._velocityGradientsTexture = null;
  63754. }
  63755. if (this._limitVelocityGradientsTexture) {
  63756. this._limitVelocityGradientsTexture.dispose();
  63757. this._limitVelocityGradientsTexture = null;
  63758. }
  63759. if (this._dragGradientsTexture) {
  63760. this._dragGradientsTexture.dispose();
  63761. this._dragGradientsTexture = null;
  63762. }
  63763. if (this._randomTexture) {
  63764. this._randomTexture.dispose();
  63765. this._randomTexture = null;
  63766. }
  63767. if (this._randomTexture2) {
  63768. this._randomTexture2.dispose();
  63769. this._randomTexture2 = null;
  63770. }
  63771. if (disposeTexture && this.particleTexture) {
  63772. this.particleTexture.dispose();
  63773. this.particleTexture = null;
  63774. }
  63775. if (disposeTexture && this.noiseTexture) {
  63776. this.noiseTexture.dispose();
  63777. this.noiseTexture = null;
  63778. }
  63779. // Callback
  63780. this.onDisposeObservable.notifyObservers(this);
  63781. this.onDisposeObservable.clear();
  63782. };
  63783. /**
  63784. * Clones the particle system.
  63785. * @param name The name of the cloned object
  63786. * @param newEmitter The new emitter to use
  63787. * @returns the cloned particle system
  63788. */
  63789. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  63790. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  63791. BABYLON.Tools.DeepCopy(this, result);
  63792. if (newEmitter === undefined) {
  63793. newEmitter = this.emitter;
  63794. }
  63795. result.emitter = newEmitter;
  63796. if (this.particleTexture) {
  63797. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  63798. }
  63799. return result;
  63800. };
  63801. /**
  63802. * Serializes the particle system to a JSON object.
  63803. * @returns the JSON object
  63804. */
  63805. GPUParticleSystem.prototype.serialize = function () {
  63806. var serializationObject = {};
  63807. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  63808. serializationObject.activeParticleCount = this.activeParticleCount;
  63809. return serializationObject;
  63810. };
  63811. /**
  63812. * Parses a JSON object to create a GPU particle system.
  63813. * @param parsedParticleSystem The JSON object to parse
  63814. * @param scene The scene to create the particle system in
  63815. * @param rootUrl The root url to use to load external dependencies like texture
  63816. * @returns the parsed GPU particle system
  63817. */
  63818. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  63819. var name = parsedParticleSystem.name;
  63820. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  63821. if (parsedParticleSystem.activeParticleCount) {
  63822. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  63823. }
  63824. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  63825. return particleSystem;
  63826. };
  63827. return GPUParticleSystem;
  63828. }(BABYLON.BaseParticleSystem));
  63829. BABYLON.GPUParticleSystem = GPUParticleSystem;
  63830. })(BABYLON || (BABYLON = {}));
  63831. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  63832. var BABYLON;
  63833. (function (BABYLON) {
  63834. /**
  63835. * Represents one particle of a solid particle system.
  63836. */
  63837. var SolidParticle = /** @class */ (function () {
  63838. /**
  63839. * Creates a Solid Particle object.
  63840. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  63841. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  63842. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  63843. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  63844. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  63845. * @param shapeId (integer) is the model shape identifier in the SPS.
  63846. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  63847. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  63848. */
  63849. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  63850. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  63851. /**
  63852. * particle global index
  63853. */
  63854. this.idx = 0;
  63855. /**
  63856. * The color of the particle
  63857. */
  63858. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  63859. /**
  63860. * The world space position of the particle.
  63861. */
  63862. this.position = BABYLON.Vector3.Zero();
  63863. /**
  63864. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  63865. */
  63866. this.rotation = BABYLON.Vector3.Zero();
  63867. /**
  63868. * The scaling of the particle.
  63869. */
  63870. this.scaling = BABYLON.Vector3.One();
  63871. /**
  63872. * The uvs of the particle.
  63873. */
  63874. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  63875. /**
  63876. * The current speed of the particle.
  63877. */
  63878. this.velocity = BABYLON.Vector3.Zero();
  63879. /**
  63880. * The pivot point in the particle local space.
  63881. */
  63882. this.pivot = BABYLON.Vector3.Zero();
  63883. /**
  63884. * Must the particle be translated from its pivot point in its local space ?
  63885. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  63886. * Default : false
  63887. */
  63888. this.translateFromPivot = false;
  63889. /**
  63890. * Is the particle active or not ?
  63891. */
  63892. this.alive = true;
  63893. /**
  63894. * Is the particle visible or not ?
  63895. */
  63896. this.isVisible = true;
  63897. /**
  63898. * Index of this particle in the global "positions" array (Internal use)
  63899. * @hidden
  63900. */
  63901. this._pos = 0;
  63902. /**
  63903. * @hidden Index of this particle in the global "indices" array (Internal use)
  63904. */
  63905. this._ind = 0;
  63906. /**
  63907. * ModelShape id of this particle
  63908. */
  63909. this.shapeId = 0;
  63910. /**
  63911. * Index of the particle in its shape id (Internal use)
  63912. */
  63913. this.idxInShape = 0;
  63914. /**
  63915. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  63916. */
  63917. this._stillInvisible = false;
  63918. /**
  63919. * @hidden Last computed particle rotation matrix
  63920. */
  63921. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  63922. /**
  63923. * Parent particle Id, if any.
  63924. * Default null.
  63925. */
  63926. this.parentId = null;
  63927. /**
  63928. * @hidden Internal global position in the SPS.
  63929. */
  63930. this._globalPosition = BABYLON.Vector3.Zero();
  63931. this.idx = particleIndex;
  63932. this._pos = positionIndex;
  63933. this._ind = indiceIndex;
  63934. this._model = model;
  63935. this.shapeId = shapeId;
  63936. this.idxInShape = idxInShape;
  63937. this._sps = sps;
  63938. if (modelBoundingInfo) {
  63939. this._modelBoundingInfo = modelBoundingInfo;
  63940. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  63941. }
  63942. }
  63943. Object.defineProperty(SolidParticle.prototype, "scale", {
  63944. /**
  63945. * Legacy support, changed scale to scaling
  63946. */
  63947. get: function () {
  63948. return this.scaling;
  63949. },
  63950. /**
  63951. * Legacy support, changed scale to scaling
  63952. */
  63953. set: function (scale) {
  63954. this.scaling = scale;
  63955. },
  63956. enumerable: true,
  63957. configurable: true
  63958. });
  63959. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  63960. /**
  63961. * Legacy support, changed quaternion to rotationQuaternion
  63962. */
  63963. get: function () {
  63964. return this.rotationQuaternion;
  63965. },
  63966. /**
  63967. * Legacy support, changed quaternion to rotationQuaternion
  63968. */
  63969. set: function (q) {
  63970. this.rotationQuaternion = q;
  63971. },
  63972. enumerable: true,
  63973. configurable: true
  63974. });
  63975. /**
  63976. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  63977. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  63978. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  63979. * @returns true if it intersects
  63980. */
  63981. SolidParticle.prototype.intersectsMesh = function (target) {
  63982. if (!this._boundingInfo || !target._boundingInfo) {
  63983. return false;
  63984. }
  63985. if (this._sps._bSphereOnly) {
  63986. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  63987. }
  63988. return this._boundingInfo.intersects(target._boundingInfo, false);
  63989. };
  63990. return SolidParticle;
  63991. }());
  63992. BABYLON.SolidParticle = SolidParticle;
  63993. /**
  63994. * Represents the shape of the model used by one particle of a solid particle system.
  63995. * SPS internal tool, don't use it manually.
  63996. */
  63997. var ModelShape = /** @class */ (function () {
  63998. /**
  63999. * 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.
  64000. * SPS internal tool, don't use it manually.
  64001. * @hidden
  64002. */
  64003. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64004. /**
  64005. * length of the shape in the model indices array (internal use)
  64006. * @hidden
  64007. */
  64008. this._indicesLength = 0;
  64009. this.shapeID = id;
  64010. this._shape = shape;
  64011. this._indicesLength = indicesLength;
  64012. this._shapeUV = shapeUV;
  64013. this._positionFunction = posFunction;
  64014. this._vertexFunction = vtxFunction;
  64015. }
  64016. return ModelShape;
  64017. }());
  64018. BABYLON.ModelShape = ModelShape;
  64019. /**
  64020. * Represents a Depth Sorted Particle in the solid particle system.
  64021. */
  64022. var DepthSortedParticle = /** @class */ (function () {
  64023. function DepthSortedParticle() {
  64024. /**
  64025. * Index of the particle in the "indices" array
  64026. */
  64027. this.ind = 0;
  64028. /**
  64029. * Length of the particle shape in the "indices" array
  64030. */
  64031. this.indicesLength = 0;
  64032. /**
  64033. * Squared distance from the particle to the camera
  64034. */
  64035. this.sqDistance = 0.0;
  64036. }
  64037. return DepthSortedParticle;
  64038. }());
  64039. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64040. })(BABYLON || (BABYLON = {}));
  64041. //# sourceMappingURL=babylon.solidParticle.js.map
  64042. var BABYLON;
  64043. (function (BABYLON) {
  64044. /**
  64045. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64046. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  64047. * The SPS is also a particle system. It provides some methods to manage the particles.
  64048. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64049. *
  64050. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64051. */
  64052. var SolidParticleSystem = /** @class */ (function () {
  64053. /**
  64054. * Creates a SPS (Solid Particle System) object.
  64055. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64056. * @param scene (Scene) is the scene in which the SPS is added.
  64057. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64058. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64059. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64060. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64061. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64062. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64063. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64064. */
  64065. function SolidParticleSystem(name, scene, options) {
  64066. /**
  64067. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64068. * Example : var p = SPS.particles[i];
  64069. */
  64070. this.particles = new Array();
  64071. /**
  64072. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64073. */
  64074. this.nbParticles = 0;
  64075. /**
  64076. * If the particles must ever face the camera (default false). Useful for planar particles.
  64077. */
  64078. this.billboard = false;
  64079. /**
  64080. * Recompute normals when adding a shape
  64081. */
  64082. this.recomputeNormals = true;
  64083. /**
  64084. * This a counter ofr your own usage. It's not set by any SPS functions.
  64085. */
  64086. this.counter = 0;
  64087. /**
  64088. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64089. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64090. */
  64091. this.vars = {};
  64092. /**
  64093. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64094. * @hidden
  64095. */
  64096. this._bSphereOnly = false;
  64097. /**
  64098. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64099. * @hidden
  64100. */
  64101. this._bSphereRadiusFactor = 1.0;
  64102. this._positions = new Array();
  64103. this._indices = new Array();
  64104. this._normals = new Array();
  64105. this._colors = new Array();
  64106. this._uvs = new Array();
  64107. this._index = 0; // indices index
  64108. this._updatable = true;
  64109. this._pickable = false;
  64110. this._isVisibilityBoxLocked = false;
  64111. this._alwaysVisible = false;
  64112. this._depthSort = false;
  64113. this._shapeCounter = 0;
  64114. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64115. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64116. this._computeParticleColor = true;
  64117. this._computeParticleTexture = true;
  64118. this._computeParticleRotation = true;
  64119. this._computeParticleVertex = false;
  64120. this._computeBoundingBox = false;
  64121. this._depthSortParticles = true;
  64122. this._cam_axisZ = BABYLON.Vector3.Zero();
  64123. this._cam_axisY = BABYLON.Vector3.Zero();
  64124. this._cam_axisX = BABYLON.Vector3.Zero();
  64125. this._axisZ = BABYLON.Axis.Z;
  64126. this._camDir = BABYLON.Vector3.Zero();
  64127. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64128. this._rotMatrix = new BABYLON.Matrix();
  64129. this._invertMatrix = new BABYLON.Matrix();
  64130. this._rotated = BABYLON.Vector3.Zero();
  64131. this._quaternion = new BABYLON.Quaternion();
  64132. this._vertex = BABYLON.Vector3.Zero();
  64133. this._normal = BABYLON.Vector3.Zero();
  64134. this._yaw = 0.0;
  64135. this._pitch = 0.0;
  64136. this._roll = 0.0;
  64137. this._halfroll = 0.0;
  64138. this._halfpitch = 0.0;
  64139. this._halfyaw = 0.0;
  64140. this._sinRoll = 0.0;
  64141. this._cosRoll = 0.0;
  64142. this._sinPitch = 0.0;
  64143. this._cosPitch = 0.0;
  64144. this._sinYaw = 0.0;
  64145. this._cosYaw = 0.0;
  64146. this._mustUnrotateFixedNormals = false;
  64147. this._minimum = BABYLON.Vector3.Zero();
  64148. this._maximum = BABYLON.Vector3.Zero();
  64149. this._minBbox = BABYLON.Vector3.Zero();
  64150. this._maxBbox = BABYLON.Vector3.Zero();
  64151. this._particlesIntersect = false;
  64152. this._depthSortFunction = function (p1, p2) {
  64153. return (p2.sqDistance - p1.sqDistance);
  64154. };
  64155. this._needs32Bits = false;
  64156. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64157. this._scaledPivot = BABYLON.Vector3.Zero();
  64158. this._particleHasParent = false;
  64159. this.name = name;
  64160. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64161. this._camera = scene.activeCamera;
  64162. this._pickable = options ? options.isPickable : false;
  64163. this._depthSort = options ? options.enableDepthSort : false;
  64164. this._particlesIntersect = options ? options.particleIntersection : false;
  64165. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64166. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64167. if (options && options.updatable !== undefined) {
  64168. this._updatable = options.updatable;
  64169. }
  64170. else {
  64171. this._updatable = true;
  64172. }
  64173. if (this._pickable) {
  64174. this.pickedParticles = [];
  64175. }
  64176. if (this._depthSort) {
  64177. this.depthSortedParticles = [];
  64178. }
  64179. }
  64180. /**
  64181. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64182. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64183. * @returns the created mesh
  64184. */
  64185. SolidParticleSystem.prototype.buildMesh = function () {
  64186. if (this.nbParticles === 0) {
  64187. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64188. this.addShape(triangle, 1);
  64189. triangle.dispose();
  64190. }
  64191. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64192. this._positions32 = new Float32Array(this._positions);
  64193. this._uvs32 = new Float32Array(this._uvs);
  64194. this._colors32 = new Float32Array(this._colors);
  64195. if (this.recomputeNormals) {
  64196. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64197. }
  64198. this._normals32 = new Float32Array(this._normals);
  64199. this._fixedNormal32 = new Float32Array(this._normals);
  64200. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64201. this._unrotateFixedNormals();
  64202. }
  64203. var vertexData = new BABYLON.VertexData();
  64204. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64205. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64206. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64207. if (this._uvs32.length > 0) {
  64208. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64209. }
  64210. if (this._colors32.length > 0) {
  64211. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64212. }
  64213. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64214. vertexData.applyToMesh(mesh, this._updatable);
  64215. this.mesh = mesh;
  64216. this.mesh.isPickable = this._pickable;
  64217. // free memory
  64218. if (!this._depthSort) {
  64219. this._indices = null;
  64220. }
  64221. this._positions = null;
  64222. this._normals = null;
  64223. this._uvs = null;
  64224. this._colors = null;
  64225. if (!this._updatable) {
  64226. this.particles.length = 0;
  64227. }
  64228. return mesh;
  64229. };
  64230. /**
  64231. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64232. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64233. * Thus the particles generated from `digest()` have their property `position` set yet.
  64234. * @param mesh ( Mesh ) is the mesh to be digested
  64235. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  64236. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64237. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64238. * @returns the current SPS
  64239. */
  64240. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64241. var size = (options && options.facetNb) || 1;
  64242. var number = (options && options.number) || 0;
  64243. var delta = (options && options.delta) || 0;
  64244. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64245. var meshInd = mesh.getIndices();
  64246. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64247. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64248. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64249. var f = 0; // facet counter
  64250. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64251. // compute size from number
  64252. if (number) {
  64253. number = (number > totalFacets) ? totalFacets : number;
  64254. size = Math.round(totalFacets / number);
  64255. delta = 0;
  64256. }
  64257. else {
  64258. size = (size > totalFacets) ? totalFacets : size;
  64259. }
  64260. var facetPos = []; // submesh positions
  64261. var facetInd = []; // submesh indices
  64262. var facetUV = []; // submesh UV
  64263. var facetCol = []; // submesh colors
  64264. var barycenter = BABYLON.Vector3.Zero();
  64265. var sizeO = size;
  64266. while (f < totalFacets) {
  64267. size = sizeO + Math.floor((1 + delta) * Math.random());
  64268. if (f > totalFacets - size) {
  64269. size = totalFacets - f;
  64270. }
  64271. // reset temp arrays
  64272. facetPos.length = 0;
  64273. facetInd.length = 0;
  64274. facetUV.length = 0;
  64275. facetCol.length = 0;
  64276. // iterate over "size" facets
  64277. var fi = 0;
  64278. for (var j = f * 3; j < (f + size) * 3; j++) {
  64279. facetInd.push(fi);
  64280. var i = meshInd[j];
  64281. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  64282. if (meshUV) {
  64283. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  64284. }
  64285. if (meshCol) {
  64286. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  64287. }
  64288. fi++;
  64289. }
  64290. // create a model shape for each single particle
  64291. var idx = this.nbParticles;
  64292. var shape = this._posToShape(facetPos);
  64293. var shapeUV = this._uvsToShapeUV(facetUV);
  64294. // compute the barycenter of the shape
  64295. var v;
  64296. for (v = 0; v < shape.length; v++) {
  64297. barycenter.addInPlace(shape[v]);
  64298. }
  64299. barycenter.scaleInPlace(1 / shape.length);
  64300. // shift the shape from its barycenter to the origin
  64301. for (v = 0; v < shape.length; v++) {
  64302. shape[v].subtractInPlace(barycenter);
  64303. }
  64304. var bInfo;
  64305. if (this._particlesIntersect) {
  64306. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  64307. }
  64308. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  64309. // add the particle in the SPS
  64310. var currentPos = this._positions.length;
  64311. var currentInd = this._indices.length;
  64312. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  64313. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  64314. // initialize the particle position
  64315. this.particles[this.nbParticles].position.addInPlace(barycenter);
  64316. this._index += shape.length;
  64317. idx++;
  64318. this.nbParticles++;
  64319. this._shapeCounter++;
  64320. f += size;
  64321. }
  64322. return this;
  64323. };
  64324. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  64325. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  64326. var index = 0;
  64327. var idx = 0;
  64328. for (var p = 0; p < this.particles.length; p++) {
  64329. this._particle = this.particles[p];
  64330. this._shape = this._particle._model._shape;
  64331. if (this._particle.rotationQuaternion) {
  64332. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64333. }
  64334. else {
  64335. this._yaw = this._particle.rotation.y;
  64336. this._pitch = this._particle.rotation.x;
  64337. this._roll = this._particle.rotation.z;
  64338. this._quaternionRotationYPR();
  64339. }
  64340. this._quaternionToRotationMatrix();
  64341. this._rotMatrix.invertToRef(this._invertMatrix);
  64342. for (var pt = 0; pt < this._shape.length; pt++) {
  64343. idx = index + pt * 3;
  64344. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  64345. this._fixedNormal32[idx] = this._normal.x;
  64346. this._fixedNormal32[idx + 1] = this._normal.y;
  64347. this._fixedNormal32[idx + 2] = this._normal.z;
  64348. }
  64349. index = idx + 3;
  64350. }
  64351. };
  64352. //reset copy
  64353. SolidParticleSystem.prototype._resetCopy = function () {
  64354. this._copy.position.x = 0;
  64355. this._copy.position.y = 0;
  64356. this._copy.position.z = 0;
  64357. this._copy.rotation.x = 0;
  64358. this._copy.rotation.y = 0;
  64359. this._copy.rotation.z = 0;
  64360. this._copy.rotationQuaternion = null;
  64361. this._copy.scaling.x = 1.0;
  64362. this._copy.scaling.y = 1.0;
  64363. this._copy.scaling.z = 1.0;
  64364. this._copy.uvs.x = 0;
  64365. this._copy.uvs.y = 0;
  64366. this._copy.uvs.z = 1.0;
  64367. this._copy.uvs.w = 1.0;
  64368. this._copy.color = null;
  64369. this._copy.translateFromPivot = false;
  64370. };
  64371. // _meshBuilder : inserts the shape model in the global SPS mesh
  64372. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  64373. var i;
  64374. var u = 0;
  64375. var c = 0;
  64376. var n = 0;
  64377. this._resetCopy();
  64378. if (options && options.positionFunction) { // call to custom positionFunction
  64379. options.positionFunction(this._copy, idx, idxInShape);
  64380. this._mustUnrotateFixedNormals = true;
  64381. }
  64382. if (this._copy.rotationQuaternion) {
  64383. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64384. }
  64385. else {
  64386. this._yaw = this._copy.rotation.y;
  64387. this._pitch = this._copy.rotation.x;
  64388. this._roll = this._copy.rotation.z;
  64389. this._quaternionRotationYPR();
  64390. }
  64391. this._quaternionToRotationMatrix();
  64392. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  64393. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  64394. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  64395. if (this._copy.translateFromPivot) {
  64396. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64397. }
  64398. else {
  64399. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64400. }
  64401. for (i = 0; i < shape.length; i++) {
  64402. this._vertex.x = shape[i].x;
  64403. this._vertex.y = shape[i].y;
  64404. this._vertex.z = shape[i].z;
  64405. if (options && options.vertexFunction) {
  64406. options.vertexFunction(this._copy, this._vertex, i);
  64407. }
  64408. this._vertex.x *= this._copy.scaling.x;
  64409. this._vertex.y *= this._copy.scaling.y;
  64410. this._vertex.z *= this._copy.scaling.z;
  64411. this._vertex.x -= this._scaledPivot.x;
  64412. this._vertex.y -= this._scaledPivot.y;
  64413. this._vertex.z -= this._scaledPivot.z;
  64414. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64415. this._rotated.addInPlace(this._pivotBackTranslation);
  64416. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  64417. if (meshUV) {
  64418. 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);
  64419. u += 2;
  64420. }
  64421. if (this._copy.color) {
  64422. this._color = this._copy.color;
  64423. }
  64424. else if (meshCol && meshCol[c] !== undefined) {
  64425. this._color.r = meshCol[c];
  64426. this._color.g = meshCol[c + 1];
  64427. this._color.b = meshCol[c + 2];
  64428. this._color.a = meshCol[c + 3];
  64429. }
  64430. else {
  64431. this._color.r = 1.0;
  64432. this._color.g = 1.0;
  64433. this._color.b = 1.0;
  64434. this._color.a = 1.0;
  64435. }
  64436. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  64437. c += 4;
  64438. if (!this.recomputeNormals && meshNor) {
  64439. this._normal.x = meshNor[n];
  64440. this._normal.y = meshNor[n + 1];
  64441. this._normal.z = meshNor[n + 2];
  64442. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  64443. normals.push(this._normal.x, this._normal.y, this._normal.z);
  64444. n += 3;
  64445. }
  64446. }
  64447. for (i = 0; i < meshInd.length; i++) {
  64448. var current_ind = p + meshInd[i];
  64449. indices.push(current_ind);
  64450. if (current_ind > 65535) {
  64451. this._needs32Bits = true;
  64452. }
  64453. }
  64454. if (this._pickable) {
  64455. var nbfaces = meshInd.length / 3;
  64456. for (i = 0; i < nbfaces; i++) {
  64457. this.pickedParticles.push({ idx: idx, faceId: i });
  64458. }
  64459. }
  64460. if (this._depthSort) {
  64461. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  64462. }
  64463. return this._copy;
  64464. };
  64465. // returns a shape array from positions array
  64466. SolidParticleSystem.prototype._posToShape = function (positions) {
  64467. var shape = [];
  64468. for (var i = 0; i < positions.length; i += 3) {
  64469. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  64470. }
  64471. return shape;
  64472. };
  64473. // returns a shapeUV array from a Vector4 uvs
  64474. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  64475. var shapeUV = [];
  64476. if (uvs) {
  64477. for (var i = 0; i < uvs.length; i++)
  64478. shapeUV.push(uvs[i]);
  64479. }
  64480. return shapeUV;
  64481. };
  64482. // adds a new particle object in the particles array
  64483. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  64484. if (bInfo === void 0) { bInfo = null; }
  64485. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  64486. this.particles.push(sp);
  64487. return sp;
  64488. };
  64489. /**
  64490. * Adds some particles to the SPS from the model shape. Returns the shape id.
  64491. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  64492. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  64493. * @param nb (positive integer) the number of particles to be created from this model
  64494. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  64495. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  64496. * @returns the number of shapes in the system
  64497. */
  64498. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  64499. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64500. var meshInd = mesh.getIndices();
  64501. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64502. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64503. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64504. var bbInfo;
  64505. if (this._particlesIntersect) {
  64506. bbInfo = mesh.getBoundingInfo();
  64507. }
  64508. var shape = this._posToShape(meshPos);
  64509. var shapeUV = this._uvsToShapeUV(meshUV);
  64510. var posfunc = options ? options.positionFunction : null;
  64511. var vtxfunc = options ? options.vertexFunction : null;
  64512. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  64513. // particles
  64514. var sp;
  64515. var currentCopy;
  64516. var idx = this.nbParticles;
  64517. for (var i = 0; i < nb; i++) {
  64518. var currentPos = this._positions.length;
  64519. var currentInd = this._indices.length;
  64520. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  64521. if (this._updatable) {
  64522. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  64523. sp.position.copyFrom(currentCopy.position);
  64524. sp.rotation.copyFrom(currentCopy.rotation);
  64525. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  64526. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  64527. }
  64528. if (currentCopy.color && sp.color) {
  64529. sp.color.copyFrom(currentCopy.color);
  64530. }
  64531. sp.scaling.copyFrom(currentCopy.scaling);
  64532. sp.uvs.copyFrom(currentCopy.uvs);
  64533. }
  64534. this._index += shape.length;
  64535. idx++;
  64536. }
  64537. this.nbParticles += nb;
  64538. this._shapeCounter++;
  64539. return this._shapeCounter - 1;
  64540. };
  64541. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  64542. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  64543. this._resetCopy();
  64544. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  64545. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  64546. }
  64547. if (this._copy.rotationQuaternion) {
  64548. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64549. }
  64550. else {
  64551. this._yaw = this._copy.rotation.y;
  64552. this._pitch = this._copy.rotation.x;
  64553. this._roll = this._copy.rotation.z;
  64554. this._quaternionRotationYPR();
  64555. }
  64556. this._quaternionToRotationMatrix();
  64557. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  64558. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  64559. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  64560. if (this._copy.translateFromPivot) {
  64561. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64562. }
  64563. else {
  64564. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64565. }
  64566. this._shape = particle._model._shape;
  64567. for (var pt = 0; pt < this._shape.length; pt++) {
  64568. this._vertex.x = this._shape[pt].x;
  64569. this._vertex.y = this._shape[pt].y;
  64570. this._vertex.z = this._shape[pt].z;
  64571. if (particle._model._vertexFunction) {
  64572. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  64573. }
  64574. this._vertex.x *= this._copy.scaling.x;
  64575. this._vertex.y *= this._copy.scaling.y;
  64576. this._vertex.z *= this._copy.scaling.z;
  64577. this._vertex.x -= this._scaledPivot.x;
  64578. this._vertex.y -= this._scaledPivot.y;
  64579. this._vertex.z -= this._scaledPivot.z;
  64580. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64581. this._rotated.addInPlace(this._pivotBackTranslation);
  64582. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  64583. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  64584. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  64585. }
  64586. particle.position.x = 0.0;
  64587. particle.position.y = 0.0;
  64588. particle.position.z = 0.0;
  64589. particle.rotation.x = 0.0;
  64590. particle.rotation.y = 0.0;
  64591. particle.rotation.z = 0.0;
  64592. particle.rotationQuaternion = null;
  64593. particle.scaling.x = 1.0;
  64594. particle.scaling.y = 1.0;
  64595. particle.scaling.z = 1.0;
  64596. particle.uvs.x = 0.0;
  64597. particle.uvs.y = 0.0;
  64598. particle.uvs.z = 1.0;
  64599. particle.uvs.w = 1.0;
  64600. particle.pivot.x = 0.0;
  64601. particle.pivot.y = 0.0;
  64602. particle.pivot.z = 0.0;
  64603. particle.translateFromPivot = false;
  64604. particle.parentId = null;
  64605. };
  64606. /**
  64607. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  64608. * @returns the SPS.
  64609. */
  64610. SolidParticleSystem.prototype.rebuildMesh = function () {
  64611. for (var p = 0; p < this.particles.length; p++) {
  64612. this._rebuildParticle(this.particles[p]);
  64613. }
  64614. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  64615. return this;
  64616. };
  64617. /**
  64618. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  64619. * This method calls `updateParticle()` for each particle of the SPS.
  64620. * For an animated SPS, it is usually called within the render loop.
  64621. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  64622. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  64623. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  64624. * @returns the SPS.
  64625. */
  64626. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  64627. if (start === void 0) { start = 0; }
  64628. if (end === void 0) { end = this.nbParticles - 1; }
  64629. if (update === void 0) { update = true; }
  64630. if (!this._updatable) {
  64631. return this;
  64632. }
  64633. // custom beforeUpdate
  64634. this.beforeUpdateParticles(start, end, update);
  64635. this._cam_axisX.x = 1.0;
  64636. this._cam_axisX.y = 0.0;
  64637. this._cam_axisX.z = 0.0;
  64638. this._cam_axisY.x = 0.0;
  64639. this._cam_axisY.y = 1.0;
  64640. this._cam_axisY.z = 0.0;
  64641. this._cam_axisZ.x = 0.0;
  64642. this._cam_axisZ.y = 0.0;
  64643. this._cam_axisZ.z = 1.0;
  64644. // cases when the World Matrix is to be computed first
  64645. if (this.billboard || this._depthSort) {
  64646. this.mesh.computeWorldMatrix(true);
  64647. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  64648. }
  64649. // if the particles will always face the camera
  64650. if (this.billboard) {
  64651. // compute the camera position and un-rotate it by the current mesh rotation
  64652. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  64653. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  64654. this._cam_axisZ.normalize();
  64655. // same for camera up vector extracted from the cam view matrix
  64656. var view = this._camera.getViewMatrix(true);
  64657. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  64658. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  64659. this._cam_axisY.normalize();
  64660. this._cam_axisX.normalize();
  64661. }
  64662. // if depthSort, compute the camera global position in the mesh local system
  64663. if (this._depthSort) {
  64664. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  64665. }
  64666. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  64667. var idx = 0; // current position index in the global array positions32
  64668. var index = 0; // position start index in the global array positions32 of the current particle
  64669. var colidx = 0; // current color index in the global array colors32
  64670. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  64671. var uvidx = 0; // current uv index in the global array uvs32
  64672. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  64673. var pt = 0; // current index in the particle model shape
  64674. if (this.mesh.isFacetDataEnabled) {
  64675. this._computeBoundingBox = true;
  64676. }
  64677. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  64678. if (this._computeBoundingBox) {
  64679. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  64680. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  64681. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  64682. }
  64683. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  64684. if (this.mesh._boundingInfo) {
  64685. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  64686. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  64687. }
  64688. }
  64689. }
  64690. // particle loop
  64691. index = this.particles[start]._pos;
  64692. var vpos = (index / 3) | 0;
  64693. colorIndex = vpos * 4;
  64694. uvIndex = vpos * 2;
  64695. for (var p = start; p <= end; p++) {
  64696. this._particle = this.particles[p];
  64697. this._shape = this._particle._model._shape;
  64698. this._shapeUV = this._particle._model._shapeUV;
  64699. // call to custom user function to update the particle properties
  64700. this.updateParticle(this._particle);
  64701. // camera-particle distance for depth sorting
  64702. if (this._depthSort && this._depthSortParticles) {
  64703. var dsp = this.depthSortedParticles[p];
  64704. dsp.ind = this._particle._ind;
  64705. dsp.indicesLength = this._particle._model._indicesLength;
  64706. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  64707. }
  64708. // skip the computations for inactive or already invisible particles
  64709. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  64710. // increment indexes for the next particle
  64711. pt = this._shape.length;
  64712. index += pt * 3;
  64713. colorIndex += pt * 4;
  64714. uvIndex += pt * 2;
  64715. continue;
  64716. }
  64717. if (this._particle.isVisible) {
  64718. this._particle._stillInvisible = false; // un-mark permanent invisibility
  64719. this._particleHasParent = (this._particle.parentId !== null);
  64720. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  64721. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  64722. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  64723. // particle rotation matrix
  64724. if (this.billboard) {
  64725. this._particle.rotation.x = 0.0;
  64726. this._particle.rotation.y = 0.0;
  64727. }
  64728. if (this._computeParticleRotation || this.billboard) {
  64729. if (this._particle.rotationQuaternion) {
  64730. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64731. }
  64732. else {
  64733. this._yaw = this._particle.rotation.y;
  64734. this._pitch = this._particle.rotation.x;
  64735. this._roll = this._particle.rotation.z;
  64736. this._quaternionRotationYPR();
  64737. }
  64738. this._quaternionToRotationMatrix();
  64739. }
  64740. if (this._particleHasParent) {
  64741. this._parent = this.particles[this._particle.parentId];
  64742. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  64743. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  64744. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  64745. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  64746. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  64747. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  64748. if (this._computeParticleRotation || this.billboard) {
  64749. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  64750. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  64751. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  64752. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  64753. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  64754. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  64755. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  64756. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  64757. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  64758. }
  64759. }
  64760. else {
  64761. this._particle._globalPosition.x = this._particle.position.x;
  64762. this._particle._globalPosition.y = this._particle.position.y;
  64763. this._particle._globalPosition.z = this._particle.position.z;
  64764. if (this._computeParticleRotation || this.billboard) {
  64765. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  64766. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  64767. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  64768. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  64769. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  64770. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  64771. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  64772. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  64773. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  64774. }
  64775. }
  64776. if (this._particle.translateFromPivot) {
  64777. this._pivotBackTranslation.x = 0.0;
  64778. this._pivotBackTranslation.y = 0.0;
  64779. this._pivotBackTranslation.z = 0.0;
  64780. }
  64781. else {
  64782. this._pivotBackTranslation.x = this._scaledPivot.x;
  64783. this._pivotBackTranslation.y = this._scaledPivot.y;
  64784. this._pivotBackTranslation.z = this._scaledPivot.z;
  64785. }
  64786. // particle vertex loop
  64787. for (pt = 0; pt < this._shape.length; pt++) {
  64788. idx = index + pt * 3;
  64789. colidx = colorIndex + pt * 4;
  64790. uvidx = uvIndex + pt * 2;
  64791. this._vertex.x = this._shape[pt].x;
  64792. this._vertex.y = this._shape[pt].y;
  64793. this._vertex.z = this._shape[pt].z;
  64794. if (this._computeParticleVertex) {
  64795. this.updateParticleVertex(this._particle, this._vertex, pt);
  64796. }
  64797. // positions
  64798. this._vertex.x *= this._particle.scaling.x;
  64799. this._vertex.y *= this._particle.scaling.y;
  64800. this._vertex.z *= this._particle.scaling.z;
  64801. this._vertex.x -= this._scaledPivot.x;
  64802. this._vertex.y -= this._scaledPivot.y;
  64803. this._vertex.z -= this._scaledPivot.z;
  64804. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  64805. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  64806. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  64807. this._rotated.x += this._pivotBackTranslation.x;
  64808. this._rotated.y += this._pivotBackTranslation.y;
  64809. this._rotated.z += this._pivotBackTranslation.z;
  64810. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  64811. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  64812. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  64813. if (this._computeBoundingBox) {
  64814. if (this._positions32[idx] < this._minimum.x) {
  64815. this._minimum.x = this._positions32[idx];
  64816. }
  64817. if (this._positions32[idx] > this._maximum.x) {
  64818. this._maximum.x = this._positions32[idx];
  64819. }
  64820. if (this._positions32[idx + 1] < this._minimum.y) {
  64821. this._minimum.y = this._positions32[idx + 1];
  64822. }
  64823. if (this._positions32[idx + 1] > this._maximum.y) {
  64824. this._maximum.y = this._positions32[idx + 1];
  64825. }
  64826. if (this._positions32[idx + 2] < this._minimum.z) {
  64827. this._minimum.z = this._positions32[idx + 2];
  64828. }
  64829. if (this._positions32[idx + 2] > this._maximum.z) {
  64830. this._maximum.z = this._positions32[idx + 2];
  64831. }
  64832. }
  64833. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  64834. if (!this._computeParticleVertex) {
  64835. this._normal.x = this._fixedNormal32[idx];
  64836. this._normal.y = this._fixedNormal32[idx + 1];
  64837. this._normal.z = this._fixedNormal32[idx + 2];
  64838. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  64839. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  64840. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  64841. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  64842. 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;
  64843. 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;
  64844. }
  64845. if (this._computeParticleColor && this._particle.color) {
  64846. this._colors32[colidx] = this._particle.color.r;
  64847. this._colors32[colidx + 1] = this._particle.color.g;
  64848. this._colors32[colidx + 2] = this._particle.color.b;
  64849. this._colors32[colidx + 3] = this._particle.color.a;
  64850. }
  64851. if (this._computeParticleTexture) {
  64852. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  64853. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  64854. }
  64855. }
  64856. }
  64857. // particle just set invisible : scaled to zero and positioned at the origin
  64858. else {
  64859. this._particle._stillInvisible = true; // mark the particle as invisible
  64860. for (pt = 0; pt < this._shape.length; pt++) {
  64861. idx = index + pt * 3;
  64862. colidx = colorIndex + pt * 4;
  64863. uvidx = uvIndex + pt * 2;
  64864. this._positions32[idx] = 0.0;
  64865. this._positions32[idx + 1] = 0.0;
  64866. this._positions32[idx + 2] = 0.0;
  64867. this._normals32[idx] = 0.0;
  64868. this._normals32[idx + 1] = 0.0;
  64869. this._normals32[idx + 2] = 0.0;
  64870. if (this._computeParticleColor && this._particle.color) {
  64871. this._colors32[colidx] = this._particle.color.r;
  64872. this._colors32[colidx + 1] = this._particle.color.g;
  64873. this._colors32[colidx + 2] = this._particle.color.b;
  64874. this._colors32[colidx + 3] = this._particle.color.a;
  64875. }
  64876. if (this._computeParticleTexture) {
  64877. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  64878. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  64879. }
  64880. }
  64881. }
  64882. // if the particle intersections must be computed : update the bbInfo
  64883. if (this._particlesIntersect) {
  64884. var bInfo = this._particle._boundingInfo;
  64885. var bBox = bInfo.boundingBox;
  64886. var bSphere = bInfo.boundingSphere;
  64887. if (!this._bSphereOnly) {
  64888. // place, scale and rotate the particle bbox within the SPS local system, then update it
  64889. for (var b = 0; b < bBox.vectors.length; b++) {
  64890. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  64891. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  64892. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  64893. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  64894. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  64895. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  64896. 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;
  64897. 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;
  64898. 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;
  64899. }
  64900. bBox._update(this.mesh._worldMatrix);
  64901. }
  64902. // place and scale the particle bouding sphere in the SPS local system, then update it
  64903. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  64904. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  64905. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  64906. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  64907. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  64908. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  64909. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  64910. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  64911. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  64912. 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));
  64913. bSphere._update(this.mesh._worldMatrix);
  64914. }
  64915. // increment indexes for the next particle
  64916. index = idx + 3;
  64917. colorIndex = colidx + 4;
  64918. uvIndex = uvidx + 2;
  64919. }
  64920. // if the VBO must be updated
  64921. if (update) {
  64922. if (this._computeParticleColor) {
  64923. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  64924. }
  64925. if (this._computeParticleTexture) {
  64926. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  64927. }
  64928. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  64929. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  64930. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  64931. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  64932. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  64933. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  64934. for (var i = 0; i < this._normals32.length; i++) {
  64935. this._fixedNormal32[i] = this._normals32[i];
  64936. }
  64937. }
  64938. if (!this.mesh.areNormalsFrozen) {
  64939. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  64940. }
  64941. }
  64942. if (this._depthSort && this._depthSortParticles) {
  64943. this.depthSortedParticles.sort(this._depthSortFunction);
  64944. var dspl = this.depthSortedParticles.length;
  64945. var sorted = 0;
  64946. var lind = 0;
  64947. var sind = 0;
  64948. var sid = 0;
  64949. for (sorted = 0; sorted < dspl; sorted++) {
  64950. lind = this.depthSortedParticles[sorted].indicesLength;
  64951. sind = this.depthSortedParticles[sorted].ind;
  64952. for (var i = 0; i < lind; i++) {
  64953. this._indices32[sid] = this._indices[sind + i];
  64954. sid++;
  64955. }
  64956. }
  64957. this.mesh.updateIndices(this._indices32);
  64958. }
  64959. }
  64960. if (this._computeBoundingBox) {
  64961. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  64962. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  64963. }
  64964. this.afterUpdateParticles(start, end, update);
  64965. return this;
  64966. };
  64967. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  64968. this._halfroll = this._roll * 0.5;
  64969. this._halfpitch = this._pitch * 0.5;
  64970. this._halfyaw = this._yaw * 0.5;
  64971. this._sinRoll = Math.sin(this._halfroll);
  64972. this._cosRoll = Math.cos(this._halfroll);
  64973. this._sinPitch = Math.sin(this._halfpitch);
  64974. this._cosPitch = Math.cos(this._halfpitch);
  64975. this._sinYaw = Math.sin(this._halfyaw);
  64976. this._cosYaw = Math.cos(this._halfyaw);
  64977. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  64978. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  64979. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  64980. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  64981. };
  64982. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  64983. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  64984. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  64985. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  64986. this._rotMatrix.m[3] = 0;
  64987. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  64988. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  64989. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  64990. this._rotMatrix.m[7] = 0;
  64991. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  64992. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  64993. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  64994. this._rotMatrix.m[11] = 0;
  64995. this._rotMatrix.m[12] = 0;
  64996. this._rotMatrix.m[13] = 0;
  64997. this._rotMatrix.m[14] = 0;
  64998. this._rotMatrix.m[15] = 1.0;
  64999. };
  65000. /**
  65001. * Disposes the SPS.
  65002. */
  65003. SolidParticleSystem.prototype.dispose = function () {
  65004. this.mesh.dispose();
  65005. this.vars = null;
  65006. // drop references to internal big arrays for the GC
  65007. this._positions = null;
  65008. this._indices = null;
  65009. this._normals = null;
  65010. this._uvs = null;
  65011. this._colors = null;
  65012. this._indices32 = null;
  65013. this._positions32 = null;
  65014. this._normals32 = null;
  65015. this._fixedNormal32 = null;
  65016. this._uvs32 = null;
  65017. this._colors32 = null;
  65018. this.pickedParticles = null;
  65019. };
  65020. /**
  65021. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65022. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65023. * @returns the SPS.
  65024. */
  65025. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65026. if (!this._isVisibilityBoxLocked) {
  65027. this.mesh.refreshBoundingInfo();
  65028. }
  65029. return this;
  65030. };
  65031. /**
  65032. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65033. * @param size the size (float) of the visibility box
  65034. * note : this doesn't lock the SPS mesh bounding box.
  65035. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65036. */
  65037. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65038. var vis = size / 2;
  65039. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65040. };
  65041. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65042. /**
  65043. * Gets whether the SPS as always visible or not
  65044. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65045. */
  65046. get: function () {
  65047. return this._alwaysVisible;
  65048. },
  65049. /**
  65050. * Sets the SPS as always visible or not
  65051. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65052. */
  65053. set: function (val) {
  65054. this._alwaysVisible = val;
  65055. this.mesh.alwaysSelectAsActiveMesh = val;
  65056. },
  65057. enumerable: true,
  65058. configurable: true
  65059. });
  65060. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65061. /**
  65062. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65063. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65064. */
  65065. get: function () {
  65066. return this._isVisibilityBoxLocked;
  65067. },
  65068. /**
  65069. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65070. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65071. */
  65072. set: function (val) {
  65073. this._isVisibilityBoxLocked = val;
  65074. var boundingInfo = this.mesh.getBoundingInfo();
  65075. boundingInfo.isLocked = val;
  65076. },
  65077. enumerable: true,
  65078. configurable: true
  65079. });
  65080. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65081. /**
  65082. * Gets if `setParticles()` computes the particle rotations or not.
  65083. * Default value : true. The SPS is faster when it's set to false.
  65084. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65085. */
  65086. get: function () {
  65087. return this._computeParticleRotation;
  65088. },
  65089. /**
  65090. * Tells to `setParticles()` to compute the particle rotations or not.
  65091. * Default value : true. The SPS is faster when it's set to false.
  65092. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65093. */
  65094. set: function (val) {
  65095. this._computeParticleRotation = val;
  65096. },
  65097. enumerable: true,
  65098. configurable: true
  65099. });
  65100. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65101. /**
  65102. * Gets if `setParticles()` computes the particle colors or not.
  65103. * Default value : true. The SPS is faster when it's set to false.
  65104. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65105. */
  65106. get: function () {
  65107. return this._computeParticleColor;
  65108. },
  65109. /**
  65110. * Tells to `setParticles()` to compute the particle colors or not.
  65111. * Default value : true. The SPS is faster when it's set to false.
  65112. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65113. */
  65114. set: function (val) {
  65115. this._computeParticleColor = val;
  65116. },
  65117. enumerable: true,
  65118. configurable: true
  65119. });
  65120. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65121. /**
  65122. * Gets if `setParticles()` computes the particle textures or not.
  65123. * Default value : true. The SPS is faster when it's set to false.
  65124. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65125. */
  65126. get: function () {
  65127. return this._computeParticleTexture;
  65128. },
  65129. set: function (val) {
  65130. this._computeParticleTexture = val;
  65131. },
  65132. enumerable: true,
  65133. configurable: true
  65134. });
  65135. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65136. /**
  65137. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65138. * Default value : false. The SPS is faster when it's set to false.
  65139. * Note : the particle custom vertex positions aren't stored values.
  65140. */
  65141. get: function () {
  65142. return this._computeParticleVertex;
  65143. },
  65144. /**
  65145. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65146. * Default value : false. The SPS is faster when it's set to false.
  65147. * Note : the particle custom vertex positions aren't stored values.
  65148. */
  65149. set: function (val) {
  65150. this._computeParticleVertex = val;
  65151. },
  65152. enumerable: true,
  65153. configurable: true
  65154. });
  65155. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65156. /**
  65157. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65158. */
  65159. get: function () {
  65160. return this._computeBoundingBox;
  65161. },
  65162. /**
  65163. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65164. */
  65165. set: function (val) {
  65166. this._computeBoundingBox = val;
  65167. },
  65168. enumerable: true,
  65169. configurable: true
  65170. });
  65171. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65172. /**
  65173. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65174. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65175. * Default : `true`
  65176. */
  65177. get: function () {
  65178. return this._depthSortParticles;
  65179. },
  65180. /**
  65181. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65182. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65183. * Default : `true`
  65184. */
  65185. set: function (val) {
  65186. this._depthSortParticles = val;
  65187. },
  65188. enumerable: true,
  65189. configurable: true
  65190. });
  65191. // =======================================================================
  65192. // Particle behavior logic
  65193. // these following methods may be overwritten by the user to fit his needs
  65194. /**
  65195. * This function does nothing. It may be overwritten to set all the particle first values.
  65196. * The SPS doesn't call this function, you may have to call it by your own.
  65197. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65198. */
  65199. SolidParticleSystem.prototype.initParticles = function () {
  65200. };
  65201. /**
  65202. * This function does nothing. It may be overwritten to recycle a particle.
  65203. * The SPS doesn't call this function, you may have to call it by your own.
  65204. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65205. * @param particle The particle to recycle
  65206. * @returns the recycled particle
  65207. */
  65208. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65209. return particle;
  65210. };
  65211. /**
  65212. * Updates a particle : this function should be overwritten by the user.
  65213. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65214. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65215. * @example : just set a particle position or velocity and recycle conditions
  65216. * @param particle The particle to update
  65217. * @returns the updated particle
  65218. */
  65219. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65220. return particle;
  65221. };
  65222. /**
  65223. * Updates a vertex of a particle : it can be overwritten by the user.
  65224. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65225. * @param particle the current particle
  65226. * @param vertex the current index of the current particle
  65227. * @param pt the index of the current vertex in the particle shape
  65228. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65229. * @example : just set a vertex particle position
  65230. * @returns the updated vertex
  65231. */
  65232. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65233. return vertex;
  65234. };
  65235. /**
  65236. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65237. * This does nothing and may be overwritten by the user.
  65238. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65239. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65240. * @param update the boolean update value actually passed to setParticles()
  65241. */
  65242. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65243. };
  65244. /**
  65245. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65246. * This will be passed three parameters.
  65247. * This does nothing and may be overwritten by the user.
  65248. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65249. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65250. * @param update the boolean update value actually passed to setParticles()
  65251. */
  65252. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65253. };
  65254. return SolidParticleSystem;
  65255. }());
  65256. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65257. })(BABYLON || (BABYLON = {}));
  65258. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65259. var BABYLON;
  65260. (function (BABYLON) {
  65261. /**
  65262. * Class containing static functions to help procedurally build meshes
  65263. */
  65264. var MeshBuilder = /** @class */ (function () {
  65265. function MeshBuilder() {
  65266. }
  65267. MeshBuilder.updateSideOrientation = function (orientation) {
  65268. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65269. return BABYLON.Mesh.DOUBLESIDE;
  65270. }
  65271. if (orientation === undefined || orientation === null) {
  65272. return BABYLON.Mesh.FRONTSIDE;
  65273. }
  65274. return orientation;
  65275. };
  65276. /**
  65277. * Creates a box mesh
  65278. * * The parameter `size` sets the size (float) of each box side (default 1)
  65279. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  65280. * * 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)
  65281. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65282. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65283. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65284. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65285. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  65286. * @param name defines the name of the mesh
  65287. * @param options defines the options used to create the mesh
  65288. * @param scene defines the hosting scene
  65289. * @returns the box mesh
  65290. */
  65291. MeshBuilder.CreateBox = function (name, options, scene) {
  65292. if (scene === void 0) { scene = null; }
  65293. var box = new BABYLON.Mesh(name, scene);
  65294. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65295. box._originalBuilderSideOrientation = options.sideOrientation;
  65296. var vertexData = BABYLON.VertexData.CreateBox(options);
  65297. vertexData.applyToMesh(box, options.updatable);
  65298. return box;
  65299. };
  65300. /**
  65301. * Creates a sphere mesh
  65302. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  65303. * * 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`)
  65304. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  65305. * * 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
  65306. * * 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)
  65307. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65308. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65309. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65310. * @param name defines the name of the mesh
  65311. * @param options defines the options used to create the mesh
  65312. * @param scene defines the hosting scene
  65313. * @returns the sphere mesh
  65314. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  65315. */
  65316. MeshBuilder.CreateSphere = function (name, options, scene) {
  65317. var sphere = new BABYLON.Mesh(name, scene);
  65318. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65319. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65320. var vertexData = BABYLON.VertexData.CreateSphere(options);
  65321. vertexData.applyToMesh(sphere, options.updatable);
  65322. return sphere;
  65323. };
  65324. /**
  65325. * Creates a plane polygonal mesh. By default, this is a disc
  65326. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65327. * * 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
  65328. * * 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
  65329. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65330. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65331. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65332. * @param name defines the name of the mesh
  65333. * @param options defines the options used to create the mesh
  65334. * @param scene defines the hosting scene
  65335. * @returns the plane polygonal mesh
  65336. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  65337. */
  65338. MeshBuilder.CreateDisc = function (name, options, scene) {
  65339. if (scene === void 0) { scene = null; }
  65340. var disc = new BABYLON.Mesh(name, scene);
  65341. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65342. disc._originalBuilderSideOrientation = options.sideOrientation;
  65343. var vertexData = BABYLON.VertexData.CreateDisc(options);
  65344. vertexData.applyToMesh(disc, options.updatable);
  65345. return disc;
  65346. };
  65347. /**
  65348. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  65349. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  65350. * * 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`)
  65351. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  65352. * * 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
  65353. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65354. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65355. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65356. * @param name defines the name of the mesh
  65357. * @param options defines the options used to create the mesh
  65358. * @param scene defines the hosting scene
  65359. * @returns the icosahedron mesh
  65360. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  65361. */
  65362. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  65363. var sphere = new BABYLON.Mesh(name, scene);
  65364. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65365. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65366. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  65367. vertexData.applyToMesh(sphere, options.updatable);
  65368. return sphere;
  65369. };
  65370. ;
  65371. /**
  65372. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65373. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  65374. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  65375. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  65376. * * 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
  65377. * * 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
  65378. * * 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
  65379. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65380. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65381. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65382. * * 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
  65383. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  65384. * * 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 if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  65385. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  65386. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65387. * @param name defines the name of the mesh
  65388. * @param options defines the options used to create the mesh
  65389. * @param scene defines the hosting scene
  65390. * @returns the ribbon mesh
  65391. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  65392. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65393. */
  65394. MeshBuilder.CreateRibbon = function (name, options, scene) {
  65395. if (scene === void 0) { scene = null; }
  65396. var pathArray = options.pathArray;
  65397. var closeArray = options.closeArray;
  65398. var closePath = options.closePath;
  65399. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65400. var instance = options.instance;
  65401. var updatable = options.updatable;
  65402. if (instance) { // existing ribbon instance update
  65403. // positionFunction : ribbon case
  65404. // only pathArray and sideOrientation parameters are taken into account for positions update
  65405. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  65406. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  65407. var positionFunction = function (positions) {
  65408. var minlg = pathArray[0].length;
  65409. var i = 0;
  65410. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  65411. for (var si = 1; si <= ns; si++) {
  65412. for (var p = 0; p < pathArray.length; p++) {
  65413. var path = pathArray[p];
  65414. var l = path.length;
  65415. minlg = (minlg < l) ? minlg : l;
  65416. var j = 0;
  65417. while (j < minlg) {
  65418. positions[i] = path[j].x;
  65419. positions[i + 1] = path[j].y;
  65420. positions[i + 2] = path[j].z;
  65421. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  65422. BABYLON.Tmp.Vector3[0].x = path[j].x;
  65423. }
  65424. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  65425. BABYLON.Tmp.Vector3[1].x = path[j].x;
  65426. }
  65427. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  65428. BABYLON.Tmp.Vector3[0].y = path[j].y;
  65429. }
  65430. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  65431. BABYLON.Tmp.Vector3[1].y = path[j].y;
  65432. }
  65433. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  65434. BABYLON.Tmp.Vector3[0].z = path[j].z;
  65435. }
  65436. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  65437. BABYLON.Tmp.Vector3[1].z = path[j].z;
  65438. }
  65439. j++;
  65440. i += 3;
  65441. }
  65442. if (instance._closePath) {
  65443. positions[i] = path[0].x;
  65444. positions[i + 1] = path[0].y;
  65445. positions[i + 2] = path[0].z;
  65446. i += 3;
  65447. }
  65448. }
  65449. }
  65450. };
  65451. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65452. positionFunction(positions);
  65453. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  65454. instance._boundingInfo.update(instance._worldMatrix);
  65455. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65456. if (options.colors) {
  65457. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65458. for (var c = 0; c < options.colors.length; c++) {
  65459. colors[c * 4] = options.colors[c].r;
  65460. colors[c * 4 + 1] = options.colors[c].g;
  65461. colors[c * 4 + 2] = options.colors[c].b;
  65462. colors[c * 4 + 3] = options.colors[c].a;
  65463. }
  65464. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  65465. }
  65466. if (options.uvs) {
  65467. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65468. for (var i = 0; i < options.uvs.length; i++) {
  65469. uvs[i * 2] = options.uvs[i].x;
  65470. uvs[i * 2 + 1] = options.uvs[i].y;
  65471. }
  65472. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  65473. }
  65474. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  65475. var indices = instance.getIndices();
  65476. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65477. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  65478. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  65479. if (instance._closePath) {
  65480. var indexFirst = 0;
  65481. var indexLast = 0;
  65482. for (var p = 0; p < pathArray.length; p++) {
  65483. indexFirst = instance._idx[p] * 3;
  65484. if (p + 1 < pathArray.length) {
  65485. indexLast = (instance._idx[p + 1] - 1) * 3;
  65486. }
  65487. else {
  65488. indexLast = normals.length - 3;
  65489. }
  65490. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  65491. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  65492. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  65493. normals[indexLast] = normals[indexFirst];
  65494. normals[indexLast + 1] = normals[indexFirst + 1];
  65495. normals[indexLast + 2] = normals[indexFirst + 2];
  65496. }
  65497. }
  65498. if (!(instance.areNormalsFrozen)) {
  65499. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  65500. }
  65501. }
  65502. return instance;
  65503. }
  65504. else { // new ribbon creation
  65505. var ribbon = new BABYLON.Mesh(name, scene);
  65506. ribbon._originalBuilderSideOrientation = sideOrientation;
  65507. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  65508. if (closePath) {
  65509. ribbon._idx = vertexData._idx;
  65510. }
  65511. ribbon._closePath = closePath;
  65512. ribbon._closeArray = closeArray;
  65513. vertexData.applyToMesh(ribbon, updatable);
  65514. return ribbon;
  65515. }
  65516. };
  65517. /**
  65518. * Creates a cylinder or a cone mesh
  65519. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  65520. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  65521. * * 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.
  65522. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  65523. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  65524. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  65525. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  65526. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  65527. * * 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).
  65528. * * 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
  65529. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  65530. * * 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
  65531. * * 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.
  65532. * * If `enclose` is false, a ring surface is one element.
  65533. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  65534. * * 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
  65535. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65536. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65537. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65538. * @param name defines the name of the mesh
  65539. * @param options defines the options used to create the mesh
  65540. * @param scene defines the hosting scene
  65541. * @returns the cylinder mesh
  65542. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  65543. */
  65544. MeshBuilder.CreateCylinder = function (name, options, scene) {
  65545. var cylinder = new BABYLON.Mesh(name, scene);
  65546. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65547. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  65548. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  65549. vertexData.applyToMesh(cylinder, options.updatable);
  65550. return cylinder;
  65551. };
  65552. /**
  65553. * Creates a torus mesh
  65554. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  65555. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  65556. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  65557. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65558. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65559. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65560. * @param name defines the name of the mesh
  65561. * @param options defines the options used to create the mesh
  65562. * @param scene defines the hosting scene
  65563. * @returns the torus mesh
  65564. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  65565. */
  65566. MeshBuilder.CreateTorus = function (name, options, scene) {
  65567. var torus = new BABYLON.Mesh(name, scene);
  65568. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65569. torus._originalBuilderSideOrientation = options.sideOrientation;
  65570. var vertexData = BABYLON.VertexData.CreateTorus(options);
  65571. vertexData.applyToMesh(torus, options.updatable);
  65572. return torus;
  65573. };
  65574. /**
  65575. * Creates a torus knot mesh
  65576. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  65577. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  65578. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  65579. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  65580. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65581. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65582. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65583. * @param name defines the name of the mesh
  65584. * @param options defines the options used to create the mesh
  65585. * @param scene defines the hosting scene
  65586. * @returns the torus knot mesh
  65587. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  65588. */
  65589. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  65590. var torusKnot = new BABYLON.Mesh(name, scene);
  65591. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65592. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  65593. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  65594. vertexData.applyToMesh(torusKnot, options.updatable);
  65595. return torusKnot;
  65596. };
  65597. /**
  65598. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  65599. * * 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
  65600. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  65601. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  65602. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  65603. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  65604. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  65605. * * 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
  65606. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  65607. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65608. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  65609. * @param name defines the name of the new line system
  65610. * @param options defines the options used to create the line system
  65611. * @param scene defines the hosting scene
  65612. * @returns a new line system mesh
  65613. */
  65614. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  65615. var instance = options.instance;
  65616. var lines = options.lines;
  65617. var colors = options.colors;
  65618. if (instance) { // lines update
  65619. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65620. var vertexColor;
  65621. var lineColors;
  65622. if (colors) {
  65623. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65624. }
  65625. var i = 0;
  65626. var c = 0;
  65627. for (var l = 0; l < lines.length; l++) {
  65628. var points = lines[l];
  65629. for (var p = 0; p < points.length; p++) {
  65630. positions[i] = points[p].x;
  65631. positions[i + 1] = points[p].y;
  65632. positions[i + 2] = points[p].z;
  65633. if (colors && vertexColor) {
  65634. lineColors = colors[l];
  65635. vertexColor[c] = lineColors[p].r;
  65636. vertexColor[c + 1] = lineColors[p].g;
  65637. vertexColor[c + 2] = lineColors[p].b;
  65638. vertexColor[c + 3] = lineColors[p].a;
  65639. c += 4;
  65640. }
  65641. i += 3;
  65642. }
  65643. }
  65644. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65645. if (colors && vertexColor) {
  65646. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  65647. }
  65648. return instance;
  65649. }
  65650. // line system creation
  65651. var useVertexColor = (colors) ? true : false;
  65652. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  65653. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  65654. vertexData.applyToMesh(lineSystem, options.updatable);
  65655. return lineSystem;
  65656. };
  65657. /**
  65658. * Creates a line mesh
  65659. * 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
  65660. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  65661. * * The parameter `points` is an array successive Vector3
  65662. * * 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
  65663. * * The optional parameter `colors` is an array of successive Color4, one per line point
  65664. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  65665. * * When updating an instance, remember that only point positions can change, not the number of points
  65666. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65667. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  65668. * @param name defines the name of the new line system
  65669. * @param options defines the options used to create the line system
  65670. * @param scene defines the hosting scene
  65671. * @returns a new line mesh
  65672. */
  65673. MeshBuilder.CreateLines = function (name, options, scene) {
  65674. if (scene === void 0) { scene = null; }
  65675. var colors = (options.colors) ? [options.colors] : null;
  65676. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  65677. return lines;
  65678. };
  65679. /**
  65680. * Creates a dashed line mesh
  65681. * * 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
  65682. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  65683. * * The parameter `points` is an array successive Vector3
  65684. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  65685. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  65686. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  65687. * * 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
  65688. * * When updating an instance, remember that only point positions can change, not the number of points
  65689. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65690. * @param name defines the name of the mesh
  65691. * @param options defines the options used to create the mesh
  65692. * @param scene defines the hosting scene
  65693. * @returns the dashed line mesh
  65694. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  65695. */
  65696. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  65697. if (scene === void 0) { scene = null; }
  65698. var points = options.points;
  65699. var instance = options.instance;
  65700. var gapSize = options.gapSize || 1;
  65701. var dashSize = options.dashSize || 3;
  65702. if (instance) { // dashed lines update
  65703. var positionFunction = function (positions) {
  65704. var curvect = BABYLON.Vector3.Zero();
  65705. var nbSeg = positions.length / 6;
  65706. var lg = 0;
  65707. var nb = 0;
  65708. var shft = 0;
  65709. var dashshft = 0;
  65710. var curshft = 0;
  65711. var p = 0;
  65712. var i = 0;
  65713. var j = 0;
  65714. for (i = 0; i < points.length - 1; i++) {
  65715. points[i + 1].subtractToRef(points[i], curvect);
  65716. lg += curvect.length();
  65717. }
  65718. shft = lg / nbSeg;
  65719. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  65720. for (i = 0; i < points.length - 1; i++) {
  65721. points[i + 1].subtractToRef(points[i], curvect);
  65722. nb = Math.floor(curvect.length() / shft);
  65723. curvect.normalize();
  65724. j = 0;
  65725. while (j < nb && p < positions.length) {
  65726. curshft = shft * j;
  65727. positions[p] = points[i].x + curshft * curvect.x;
  65728. positions[p + 1] = points[i].y + curshft * curvect.y;
  65729. positions[p + 2] = points[i].z + curshft * curvect.z;
  65730. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  65731. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  65732. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  65733. p += 6;
  65734. j++;
  65735. }
  65736. }
  65737. while (p < positions.length) {
  65738. positions[p] = points[i].x;
  65739. positions[p + 1] = points[i].y;
  65740. positions[p + 2] = points[i].z;
  65741. p += 3;
  65742. }
  65743. };
  65744. instance.updateMeshPositions(positionFunction, false);
  65745. return instance;
  65746. }
  65747. // dashed lines creation
  65748. var dashedLines = new BABYLON.LinesMesh(name, scene);
  65749. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  65750. vertexData.applyToMesh(dashedLines, options.updatable);
  65751. dashedLines.dashSize = dashSize;
  65752. dashedLines.gapSize = gapSize;
  65753. return dashedLines;
  65754. };
  65755. /**
  65756. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  65757. * * 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 extruded along the Z axis.
  65758. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  65759. * * 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.
  65760. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  65761. * * 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
  65762. * * 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
  65763. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  65764. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65765. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65766. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  65767. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65768. * @param name defines the name of the mesh
  65769. * @param options defines the options used to create the mesh
  65770. * @param scene defines the hosting scene
  65771. * @returns the extruded shape mesh
  65772. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65773. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65774. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65775. */
  65776. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  65777. if (scene === void 0) { scene = null; }
  65778. var path = options.path;
  65779. var shape = options.shape;
  65780. var scale = options.scale || 1;
  65781. var rotation = options.rotation || 0;
  65782. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  65783. var updatable = options.updatable;
  65784. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65785. var instance = options.instance || null;
  65786. var invertUV = options.invertUV || false;
  65787. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
  65788. };
  65789. /**
  65790. * Creates an custom extruded shape mesh.
  65791. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  65792. * * 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 extruded along the Z axis.
  65793. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  65794. * * 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 and the distance of this point from the begining of the path
  65795. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  65796. * * 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 and the distance of this point from the begining of the path
  65797. * * It must returns a float value that will be the scale value applied to the shape on each path point
  65798. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  65799. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  65800. * * 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
  65801. * * 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
  65802. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  65803. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65804. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65805. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65806. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65807. * @param name defines the name of the mesh
  65808. * @param options defines the options used to create the mesh
  65809. * @param scene defines the hosting scene
  65810. * @returns the custom extruded shape mesh
  65811. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  65812. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65813. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65814. */
  65815. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  65816. var path = options.path;
  65817. var shape = options.shape;
  65818. var scaleFunction = options.scaleFunction || (function () { return 1; });
  65819. var rotationFunction = options.rotationFunction || (function () { return 0; });
  65820. var ribbonCloseArray = options.ribbonCloseArray || false;
  65821. var ribbonClosePath = options.ribbonClosePath || false;
  65822. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  65823. var updatable = options.updatable;
  65824. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65825. var instance = options.instance;
  65826. var invertUV = options.invertUV || false;
  65827. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
  65828. };
  65829. /**
  65830. * Creates lathe mesh.
  65831. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  65832. * * 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  65833. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  65834. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  65835. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  65836. * * 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
  65837. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  65838. * * 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
  65839. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65840. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65841. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65842. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65843. * @param name defines the name of the mesh
  65844. * @param options defines the options used to create the mesh
  65845. * @param scene defines the hosting scene
  65846. * @returns the lathe mesh
  65847. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  65848. */
  65849. MeshBuilder.CreateLathe = function (name, options, scene) {
  65850. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  65851. var closed = (options.closed === undefined) ? true : options.closed;
  65852. var shape = options.shape;
  65853. var radius = options.radius || 1;
  65854. var tessellation = options.tessellation || 64;
  65855. var clip = options.clip || 0;
  65856. var updatable = options.updatable;
  65857. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65858. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  65859. var pi2 = Math.PI * 2;
  65860. var paths = new Array();
  65861. var invertUV = options.invertUV || false;
  65862. var i = 0;
  65863. var p = 0;
  65864. var step = pi2 / tessellation * arc;
  65865. var rotated;
  65866. var path = new Array();
  65867. for (i = 0; i <= tessellation - clip; i++) {
  65868. var path = [];
  65869. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  65870. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  65871. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  65872. }
  65873. for (p = 0; p < shape.length; p++) {
  65874. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  65875. path.push(rotated);
  65876. }
  65877. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  65878. 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));
  65879. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  65880. }
  65881. paths.push(path);
  65882. }
  65883. // lathe ribbon
  65884. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  65885. return lathe;
  65886. };
  65887. /**
  65888. * Creates a plane mesh
  65889. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  65890. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  65891. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  65892. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65893. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65894. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65895. * @param name defines the name of the mesh
  65896. * @param options defines the options used to create the mesh
  65897. * @param scene defines the hosting scene
  65898. * @returns the plane mesh
  65899. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  65900. */
  65901. MeshBuilder.CreatePlane = function (name, options, scene) {
  65902. var plane = new BABYLON.Mesh(name, scene);
  65903. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65904. plane._originalBuilderSideOrientation = options.sideOrientation;
  65905. var vertexData = BABYLON.VertexData.CreatePlane(options);
  65906. vertexData.applyToMesh(plane, options.updatable);
  65907. if (options.sourcePlane) {
  65908. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  65909. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  65910. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  65911. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  65912. plane.rotate(vectorProduct, product);
  65913. }
  65914. }
  65915. return plane;
  65916. };
  65917. /**
  65918. * Creates a ground mesh
  65919. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  65920. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  65921. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65922. * @param name defines the name of the mesh
  65923. * @param options defines the options used to create the mesh
  65924. * @param scene defines the hosting scene
  65925. * @returns the ground mesh
  65926. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  65927. */
  65928. MeshBuilder.CreateGround = function (name, options, scene) {
  65929. var ground = new BABYLON.GroundMesh(name, scene);
  65930. ground._setReady(false);
  65931. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  65932. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  65933. ground._width = options.width || 1;
  65934. ground._height = options.height || 1;
  65935. ground._maxX = ground._width / 2;
  65936. ground._maxZ = ground._height / 2;
  65937. ground._minX = -ground._maxX;
  65938. ground._minZ = -ground._maxZ;
  65939. var vertexData = BABYLON.VertexData.CreateGround(options);
  65940. vertexData.applyToMesh(ground, options.updatable);
  65941. ground._setReady(true);
  65942. return ground;
  65943. };
  65944. /**
  65945. * Creates a tiled ground mesh
  65946. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  65947. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  65948. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  65949. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  65950. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65951. * @param name defines the name of the mesh
  65952. * @param options defines the options used to create the mesh
  65953. * @param scene defines the hosting scene
  65954. * @returns the tiled ground mesh
  65955. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  65956. */
  65957. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  65958. var tiledGround = new BABYLON.Mesh(name, scene);
  65959. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  65960. vertexData.applyToMesh(tiledGround, options.updatable);
  65961. return tiledGround;
  65962. };
  65963. /**
  65964. * Creates a ground mesh from a height map
  65965. * * The parameter `url` sets the URL of the height map image resource.
  65966. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  65967. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  65968. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  65969. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  65970. * * 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.
  65971. * * 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).
  65972. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  65973. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65974. * @param name defines the name of the mesh
  65975. * @param url defines the url to the height map
  65976. * @param options defines the options used to create the mesh
  65977. * @param scene defines the hosting scene
  65978. * @returns the ground mesh
  65979. * @see http://doc.babylonjs.com/babylon101/height_map
  65980. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  65981. */
  65982. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  65983. var width = options.width || 10.0;
  65984. var height = options.height || 10.0;
  65985. var subdivisions = options.subdivisions || 1 | 0;
  65986. var minHeight = options.minHeight || 0.0;
  65987. var maxHeight = options.maxHeight || 1.0;
  65988. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  65989. var alphaFilter = options.alphaFilter || 0.0;
  65990. var updatable = options.updatable;
  65991. var onReady = options.onReady;
  65992. var ground = new BABYLON.GroundMesh(name, scene);
  65993. ground._subdivisionsX = subdivisions;
  65994. ground._subdivisionsY = subdivisions;
  65995. ground._width = width;
  65996. ground._height = height;
  65997. ground._maxX = ground._width / 2.0;
  65998. ground._maxZ = ground._height / 2.0;
  65999. ground._minX = -ground._maxX;
  66000. ground._minZ = -ground._maxZ;
  66001. ground._setReady(false);
  66002. var onload = function (img) {
  66003. // Getting height map data
  66004. var canvas = document.createElement("canvas");
  66005. var context = canvas.getContext("2d");
  66006. if (!context) {
  66007. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66008. }
  66009. if (scene.isDisposed) {
  66010. return;
  66011. }
  66012. var bufferWidth = img.width;
  66013. var bufferHeight = img.height;
  66014. canvas.width = bufferWidth;
  66015. canvas.height = bufferHeight;
  66016. context.drawImage(img, 0, 0);
  66017. // Create VertexData from map data
  66018. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66019. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66020. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66021. width: width, height: height,
  66022. subdivisions: subdivisions,
  66023. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66024. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66025. alphaFilter: alphaFilter
  66026. });
  66027. vertexData.applyToMesh(ground, updatable);
  66028. //execute ready callback, if set
  66029. if (onReady) {
  66030. onReady(ground);
  66031. }
  66032. ground._setReady(true);
  66033. };
  66034. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66035. return ground;
  66036. };
  66037. /**
  66038. * Creates a polygon mesh
  66039. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66040. * * 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
  66041. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66042. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66043. * * 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)
  66044. * * Remember you can only change the shape positions, not their number when updating a polygon
  66045. * @param name defines the name of the mesh
  66046. * @param options defines the options used to create the mesh
  66047. * @param scene defines the hosting scene
  66048. * @returns the polygon mesh
  66049. */
  66050. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66051. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66052. var shape = options.shape;
  66053. var holes = options.holes || [];
  66054. var depth = options.depth || 0;
  66055. var contours = [];
  66056. var hole = [];
  66057. for (var i = 0; i < shape.length; i++) {
  66058. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66059. }
  66060. var epsilon = 0.00000001;
  66061. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66062. contours.pop();
  66063. }
  66064. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66065. for (var hNb = 0; hNb < holes.length; hNb++) {
  66066. hole = [];
  66067. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66068. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66069. }
  66070. polygonTriangulation.addHole(hole);
  66071. }
  66072. var polygon = polygonTriangulation.build(options.updatable, depth);
  66073. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66074. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66075. vertexData.applyToMesh(polygon, options.updatable);
  66076. return polygon;
  66077. };
  66078. ;
  66079. /**
  66080. * Creates an extruded polygon mesh, with depth in the Y direction.
  66081. * * 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)
  66082. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66083. * @param name defines the name of the mesh
  66084. * @param options defines the options used to create the mesh
  66085. * @param scene defines the hosting scene
  66086. * @returns the polygon mesh
  66087. */
  66088. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66089. return MeshBuilder.CreatePolygon(name, options, scene);
  66090. };
  66091. ;
  66092. /**
  66093. * Creates a tube mesh.
  66094. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66095. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66096. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66097. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66098. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66099. * * 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. It must return a radius value (positive float)
  66100. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66101. * * 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
  66102. * * 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
  66103. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66104. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  66105. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66106. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66107. * @param name defines the name of the mesh
  66108. * @param options defines the options used to create the mesh
  66109. * @param scene defines the hosting scene
  66110. * @returns the tube mesh
  66111. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66112. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66113. */
  66114. MeshBuilder.CreateTube = function (name, options, scene) {
  66115. var path = options.path;
  66116. var instance = options.instance;
  66117. var radius = 1.0;
  66118. if (instance) {
  66119. radius = instance.radius;
  66120. }
  66121. if (options.radius !== undefined) {
  66122. radius = options.radius;
  66123. }
  66124. ;
  66125. var tessellation = options.tessellation || 64 | 0;
  66126. var radiusFunction = options.radiusFunction || null;
  66127. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66128. var invertUV = options.invertUV || false;
  66129. var updatable = options.updatable;
  66130. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66131. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66132. // tube geometry
  66133. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66134. var tangents = path3D.getTangents();
  66135. var normals = path3D.getNormals();
  66136. var distances = path3D.getDistances();
  66137. var pi2 = Math.PI * 2;
  66138. var step = pi2 / tessellation * arc;
  66139. var returnRadius = function () { return radius; };
  66140. var radiusFunctionFinal = radiusFunction || returnRadius;
  66141. var circlePath;
  66142. var rad;
  66143. var normal;
  66144. var rotated;
  66145. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66146. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66147. for (var i = 0; i < path.length; i++) {
  66148. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66149. circlePath = Array(); // current circle array
  66150. normal = normals[i]; // current normal
  66151. for (var t = 0; t < tessellation; t++) {
  66152. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66153. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66154. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66155. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66156. circlePath[t] = rotated;
  66157. }
  66158. circlePaths[index] = circlePath;
  66159. index++;
  66160. }
  66161. // cap
  66162. var capPath = function (nbPoints, pathIndex) {
  66163. var pointCap = Array();
  66164. for (var i = 0; i < nbPoints; i++) {
  66165. pointCap.push(path[pathIndex]);
  66166. }
  66167. return pointCap;
  66168. };
  66169. switch (cap) {
  66170. case BABYLON.Mesh.NO_CAP:
  66171. break;
  66172. case BABYLON.Mesh.CAP_START:
  66173. circlePaths[0] = capPath(tessellation, 0);
  66174. circlePaths[1] = circlePaths[2].slice(0);
  66175. break;
  66176. case BABYLON.Mesh.CAP_END:
  66177. circlePaths[index] = circlePaths[index - 1].slice(0);
  66178. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66179. break;
  66180. case BABYLON.Mesh.CAP_ALL:
  66181. circlePaths[0] = capPath(tessellation, 0);
  66182. circlePaths[1] = circlePaths[2].slice(0);
  66183. circlePaths[index] = circlePaths[index - 1].slice(0);
  66184. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66185. break;
  66186. default:
  66187. break;
  66188. }
  66189. return circlePaths;
  66190. };
  66191. var path3D;
  66192. var pathArray;
  66193. if (instance) { // tube update
  66194. var arc = options.arc || instance.arc;
  66195. path3D = (instance.path3D).update(path);
  66196. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66197. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66198. instance.path3D = path3D;
  66199. instance.pathArray = pathArray;
  66200. instance.arc = arc;
  66201. instance.radius = radius;
  66202. return instance;
  66203. }
  66204. // tube creation
  66205. path3D = new BABYLON.Path3D(path);
  66206. var newPathArray = new Array();
  66207. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66208. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66209. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66210. tube.pathArray = pathArray;
  66211. tube.path3D = path3D;
  66212. tube.tessellation = tessellation;
  66213. tube.cap = cap;
  66214. tube.arc = options.arc;
  66215. tube.radius = radius;
  66216. return tube;
  66217. };
  66218. /**
  66219. * Creates a polyhedron mesh
  66220. * * 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 to choose the wanted type
  66221. * * The parameter `size` (positive float, default 1) sets the polygon size
  66222. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66223. * * 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`
  66224. * * 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
  66225. * * 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)`)
  66226. * * 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
  66227. * * 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
  66228. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66229. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  66230. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66231. * @param name defines the name of the mesh
  66232. * @param options defines the options used to create the mesh
  66233. * @param scene defines the hosting scene
  66234. * @returns the polyhedron mesh
  66235. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66236. */
  66237. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66238. var polyhedron = new BABYLON.Mesh(name, scene);
  66239. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66240. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66241. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66242. vertexData.applyToMesh(polyhedron, options.updatable);
  66243. return polyhedron;
  66244. };
  66245. /**
  66246. * Creates a decal mesh.
  66247. * 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
  66248. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66249. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66250. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66251. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66252. * @param name defines the name of the mesh
  66253. * @param sourceMesh defines the mesh where the decal must be applied
  66254. * @param options defines the options used to create the mesh
  66255. * @param scene defines the hosting scene
  66256. * @returns the decal mesh
  66257. * @see http://doc.babylonjs.com/how_to/decals
  66258. */
  66259. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66260. var indices = sourceMesh.getIndices();
  66261. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66262. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66263. var position = options.position || BABYLON.Vector3.Zero();
  66264. var normal = options.normal || BABYLON.Vector3.Up();
  66265. var size = options.size || BABYLON.Vector3.One();
  66266. var angle = options.angle || 0;
  66267. // Getting correct rotation
  66268. if (!normal) {
  66269. var target = new BABYLON.Vector3(0, 0, 1);
  66270. var camera = sourceMesh.getScene().activeCamera;
  66271. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66272. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66273. }
  66274. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66275. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66276. var pitch = Math.atan2(normal.y, len);
  66277. // Matrix
  66278. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66279. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66280. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  66281. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  66282. var vertexData = new BABYLON.VertexData();
  66283. vertexData.indices = [];
  66284. vertexData.positions = [];
  66285. vertexData.normals = [];
  66286. vertexData.uvs = [];
  66287. var currentVertexDataIndex = 0;
  66288. var extractDecalVector3 = function (indexId) {
  66289. var result = new BABYLON.PositionNormalVertex();
  66290. if (!indices || !positions || !normals) {
  66291. return result;
  66292. }
  66293. var vertexId = indices[indexId];
  66294. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  66295. // Send vector to decal local world
  66296. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  66297. // Get normal
  66298. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  66299. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  66300. return result;
  66301. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  66302. var clip = function (vertices, axis) {
  66303. if (vertices.length === 0) {
  66304. return vertices;
  66305. }
  66306. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  66307. var clipVertices = function (v0, v1) {
  66308. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  66309. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  66310. };
  66311. var result = new Array();
  66312. for (var index = 0; index < vertices.length; index += 3) {
  66313. var v1Out;
  66314. var v2Out;
  66315. var v3Out;
  66316. var total = 0;
  66317. var nV1 = null;
  66318. var nV2 = null;
  66319. var nV3 = null;
  66320. var nV4 = null;
  66321. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  66322. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  66323. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  66324. v1Out = d1 > 0;
  66325. v2Out = d2 > 0;
  66326. v3Out = d3 > 0;
  66327. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  66328. switch (total) {
  66329. case 0:
  66330. result.push(vertices[index]);
  66331. result.push(vertices[index + 1]);
  66332. result.push(vertices[index + 2]);
  66333. break;
  66334. case 1:
  66335. if (v1Out) {
  66336. nV1 = vertices[index + 1];
  66337. nV2 = vertices[index + 2];
  66338. nV3 = clipVertices(vertices[index], nV1);
  66339. nV4 = clipVertices(vertices[index], nV2);
  66340. }
  66341. if (v2Out) {
  66342. nV1 = vertices[index];
  66343. nV2 = vertices[index + 2];
  66344. nV3 = clipVertices(vertices[index + 1], nV1);
  66345. nV4 = clipVertices(vertices[index + 1], nV2);
  66346. result.push(nV3);
  66347. result.push(nV2.clone());
  66348. result.push(nV1.clone());
  66349. result.push(nV2.clone());
  66350. result.push(nV3.clone());
  66351. result.push(nV4);
  66352. break;
  66353. }
  66354. if (v3Out) {
  66355. nV1 = vertices[index];
  66356. nV2 = vertices[index + 1];
  66357. nV3 = clipVertices(vertices[index + 2], nV1);
  66358. nV4 = clipVertices(vertices[index + 2], nV2);
  66359. }
  66360. if (nV1 && nV2 && nV3 && nV4) {
  66361. result.push(nV1.clone());
  66362. result.push(nV2.clone());
  66363. result.push(nV3);
  66364. result.push(nV4);
  66365. result.push(nV3.clone());
  66366. result.push(nV2.clone());
  66367. }
  66368. break;
  66369. case 2:
  66370. if (!v1Out) {
  66371. nV1 = vertices[index].clone();
  66372. nV2 = clipVertices(nV1, vertices[index + 1]);
  66373. nV3 = clipVertices(nV1, vertices[index + 2]);
  66374. result.push(nV1);
  66375. result.push(nV2);
  66376. result.push(nV3);
  66377. }
  66378. if (!v2Out) {
  66379. nV1 = vertices[index + 1].clone();
  66380. nV2 = clipVertices(nV1, vertices[index + 2]);
  66381. nV3 = clipVertices(nV1, vertices[index]);
  66382. result.push(nV1);
  66383. result.push(nV2);
  66384. result.push(nV3);
  66385. }
  66386. if (!v3Out) {
  66387. nV1 = vertices[index + 2].clone();
  66388. nV2 = clipVertices(nV1, vertices[index]);
  66389. nV3 = clipVertices(nV1, vertices[index + 1]);
  66390. result.push(nV1);
  66391. result.push(nV2);
  66392. result.push(nV3);
  66393. }
  66394. break;
  66395. case 3:
  66396. break;
  66397. }
  66398. }
  66399. return result;
  66400. };
  66401. for (var index = 0; index < indices.length; index += 3) {
  66402. var faceVertices = new Array();
  66403. faceVertices.push(extractDecalVector3(index));
  66404. faceVertices.push(extractDecalVector3(index + 1));
  66405. faceVertices.push(extractDecalVector3(index + 2));
  66406. // Clip
  66407. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  66408. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  66409. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  66410. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  66411. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  66412. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  66413. if (faceVertices.length === 0) {
  66414. continue;
  66415. }
  66416. // Add UVs and get back to world
  66417. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  66418. var vertex = faceVertices[vIndex];
  66419. //TODO check for Int32Array | Uint32Array | Uint16Array
  66420. vertexData.indices.push(currentVertexDataIndex);
  66421. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  66422. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  66423. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  66424. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  66425. currentVertexDataIndex++;
  66426. }
  66427. }
  66428. // Return mesh
  66429. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  66430. vertexData.applyToMesh(decal);
  66431. decal.position = position.clone();
  66432. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  66433. return decal;
  66434. };
  66435. // Privates
  66436. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  66437. // extrusion geometry
  66438. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  66439. var tangents = path3D.getTangents();
  66440. var normals = path3D.getNormals();
  66441. var binormals = path3D.getBinormals();
  66442. var distances = path3D.getDistances();
  66443. var angle = 0;
  66444. var returnScale = function () { return scale !== null ? scale : 1; };
  66445. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  66446. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  66447. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  66448. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66449. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66450. for (var i = 0; i < curve.length; i++) {
  66451. var shapePath = new Array();
  66452. var angleStep = rotate(i, distances[i]);
  66453. var scaleRatio = scl(i, distances[i]);
  66454. for (var p = 0; p < shape.length; p++) {
  66455. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  66456. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  66457. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  66458. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  66459. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  66460. shapePath[p] = rotated;
  66461. }
  66462. shapePaths[index] = shapePath;
  66463. angle += angleStep;
  66464. index++;
  66465. }
  66466. // cap
  66467. var capPath = function (shapePath) {
  66468. var pointCap = Array();
  66469. var barycenter = BABYLON.Vector3.Zero();
  66470. var i;
  66471. for (i = 0; i < shapePath.length; i++) {
  66472. barycenter.addInPlace(shapePath[i]);
  66473. }
  66474. barycenter.scaleInPlace(1.0 / shapePath.length);
  66475. for (i = 0; i < shapePath.length; i++) {
  66476. pointCap.push(barycenter);
  66477. }
  66478. return pointCap;
  66479. };
  66480. switch (cap) {
  66481. case BABYLON.Mesh.NO_CAP:
  66482. break;
  66483. case BABYLON.Mesh.CAP_START:
  66484. shapePaths[0] = capPath(shapePaths[2]);
  66485. shapePaths[1] = shapePaths[2];
  66486. break;
  66487. case BABYLON.Mesh.CAP_END:
  66488. shapePaths[index] = shapePaths[index - 1];
  66489. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66490. break;
  66491. case BABYLON.Mesh.CAP_ALL:
  66492. shapePaths[0] = capPath(shapePaths[2]);
  66493. shapePaths[1] = shapePaths[2];
  66494. shapePaths[index] = shapePaths[index - 1];
  66495. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66496. break;
  66497. default:
  66498. break;
  66499. }
  66500. return shapePaths;
  66501. };
  66502. var path3D;
  66503. var pathArray;
  66504. if (instance) { // instance update
  66505. path3D = (instance.path3D).update(curve);
  66506. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  66507. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  66508. return instance;
  66509. }
  66510. // extruded shape creation
  66511. path3D = new BABYLON.Path3D(curve);
  66512. var newShapePaths = new Array();
  66513. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66514. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  66515. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  66516. extrudedGeneric.pathArray = pathArray;
  66517. extrudedGeneric.path3D = path3D;
  66518. extrudedGeneric.cap = cap;
  66519. return extrudedGeneric;
  66520. };
  66521. return MeshBuilder;
  66522. }());
  66523. BABYLON.MeshBuilder = MeshBuilder;
  66524. })(BABYLON || (BABYLON = {}));
  66525. //# sourceMappingURL=babylon.meshBuilder.js.map
  66526. var BABYLON;
  66527. (function (BABYLON) {
  66528. /**
  66529. * Draco compression (https://google.github.io/draco/)
  66530. *
  66531. * This class wraps the Draco module.
  66532. *
  66533. * **Encoder**
  66534. *
  66535. * The encoder is not currently implemented.
  66536. *
  66537. * **Decoder**
  66538. *
  66539. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  66540. *
  66541. * To update the configuration, use the following code:
  66542. * ```javascript
  66543. * BABYLON.DracoCompression.Configuration = {
  66544. * decoder: {
  66545. * wasmUrl: "<url to the WebAssembly library>",
  66546. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  66547. * fallbackUrl: "<url to the fallback JavaScript library>",
  66548. * }
  66549. * };
  66550. * ```
  66551. *
  66552. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  66553. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  66554. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  66555. *
  66556. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  66557. * ```javascript
  66558. * var dracoCompression = new BABYLON.DracoCompression();
  66559. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  66560. * [BABYLON.VertexBuffer.PositionKind]: 0
  66561. * });
  66562. * ```
  66563. *
  66564. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  66565. */
  66566. var DracoCompression = /** @class */ (function () {
  66567. /**
  66568. * Constructor
  66569. */
  66570. function DracoCompression() {
  66571. }
  66572. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  66573. /**
  66574. * Returns true if the decoder is available.
  66575. */
  66576. get: function () {
  66577. if (typeof DracoDecoderModule !== "undefined") {
  66578. return true;
  66579. }
  66580. var decoder = DracoCompression.Configuration.decoder;
  66581. if (decoder) {
  66582. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  66583. return true;
  66584. }
  66585. if (decoder.fallbackUrl) {
  66586. return true;
  66587. }
  66588. }
  66589. return false;
  66590. },
  66591. enumerable: true,
  66592. configurable: true
  66593. });
  66594. /**
  66595. * Stop all async operations and release resources.
  66596. */
  66597. DracoCompression.prototype.dispose = function () {
  66598. };
  66599. /**
  66600. * Decode Draco compressed mesh data to vertex data.
  66601. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  66602. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  66603. * @returns A promise that resolves with the decoded vertex data
  66604. */
  66605. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  66606. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  66607. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  66608. var module = wrappedModule.module;
  66609. var vertexData = new BABYLON.VertexData();
  66610. var buffer = new module.DecoderBuffer();
  66611. buffer.Init(dataView, dataView.byteLength);
  66612. var decoder = new module.Decoder();
  66613. var geometry;
  66614. var status;
  66615. try {
  66616. var type = decoder.GetEncodedGeometryType(buffer);
  66617. switch (type) {
  66618. case module.TRIANGULAR_MESH:
  66619. geometry = new module.Mesh();
  66620. status = decoder.DecodeBufferToMesh(buffer, geometry);
  66621. break;
  66622. case module.POINT_CLOUD:
  66623. geometry = new module.PointCloud();
  66624. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  66625. break;
  66626. default:
  66627. throw new Error("Invalid geometry type " + type);
  66628. }
  66629. if (!status.ok() || !geometry.ptr) {
  66630. throw new Error(status.error_msg());
  66631. }
  66632. var numPoints = geometry.num_points();
  66633. if (type === module.TRIANGULAR_MESH) {
  66634. var numFaces = geometry.num_faces();
  66635. var faceIndices = new module.DracoInt32Array();
  66636. try {
  66637. var indices = new Uint32Array(numFaces * 3);
  66638. for (var i = 0; i < numFaces; i++) {
  66639. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  66640. var offset = i * 3;
  66641. indices[offset + 0] = faceIndices.GetValue(0);
  66642. indices[offset + 1] = faceIndices.GetValue(1);
  66643. indices[offset + 2] = faceIndices.GetValue(2);
  66644. }
  66645. vertexData.indices = indices;
  66646. }
  66647. finally {
  66648. module.destroy(faceIndices);
  66649. }
  66650. }
  66651. for (var kind in attributes) {
  66652. var uniqueId = attributes[kind];
  66653. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  66654. var dracoData = new module.DracoFloat32Array();
  66655. try {
  66656. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  66657. var babylonData = new Float32Array(numPoints * attribute.num_components());
  66658. for (var i = 0; i < babylonData.length; i++) {
  66659. babylonData[i] = dracoData.GetValue(i);
  66660. }
  66661. vertexData.set(babylonData, kind);
  66662. }
  66663. finally {
  66664. module.destroy(dracoData);
  66665. }
  66666. }
  66667. }
  66668. finally {
  66669. if (geometry) {
  66670. module.destroy(geometry);
  66671. }
  66672. module.destroy(decoder);
  66673. module.destroy(buffer);
  66674. }
  66675. return vertexData;
  66676. });
  66677. };
  66678. DracoCompression._GetDecoderModule = function () {
  66679. if (!DracoCompression._DecoderModulePromise) {
  66680. var promise = null;
  66681. var config_1 = {};
  66682. if (typeof DracoDecoderModule !== "undefined") {
  66683. promise = Promise.resolve();
  66684. }
  66685. else {
  66686. var decoder = DracoCompression.Configuration.decoder;
  66687. if (decoder) {
  66688. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  66689. promise = Promise.all([
  66690. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  66691. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  66692. config_1.wasmBinary = data;
  66693. })
  66694. ]);
  66695. }
  66696. else if (decoder.fallbackUrl) {
  66697. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  66698. }
  66699. }
  66700. }
  66701. if (!promise) {
  66702. throw new Error("Draco decoder module is not available");
  66703. }
  66704. DracoCompression._DecoderModulePromise = promise.then(function () {
  66705. return new Promise(function (resolve) {
  66706. config_1.onModuleLoaded = function (decoderModule) {
  66707. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  66708. resolve({ module: decoderModule });
  66709. };
  66710. DracoDecoderModule(config_1);
  66711. });
  66712. });
  66713. }
  66714. return DracoCompression._DecoderModulePromise;
  66715. };
  66716. DracoCompression._LoadScriptAsync = function (url) {
  66717. return new Promise(function (resolve, reject) {
  66718. BABYLON.Tools.LoadScript(url, function () {
  66719. resolve();
  66720. }, function (message) {
  66721. reject(new Error(message));
  66722. });
  66723. });
  66724. };
  66725. DracoCompression._LoadFileAsync = function (url) {
  66726. return new Promise(function (resolve, reject) {
  66727. BABYLON.Tools.LoadFile(url, function (data) {
  66728. resolve(data);
  66729. }, undefined, undefined, true, function (request, exception) {
  66730. reject(exception);
  66731. });
  66732. });
  66733. };
  66734. /**
  66735. * The configuration. Defaults to the following urls:
  66736. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  66737. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  66738. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  66739. */
  66740. DracoCompression.Configuration = {
  66741. decoder: {
  66742. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  66743. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  66744. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  66745. }
  66746. };
  66747. return DracoCompression;
  66748. }());
  66749. BABYLON.DracoCompression = DracoCompression;
  66750. })(BABYLON || (BABYLON = {}));
  66751. //# sourceMappingURL=babylon.dracoCompression.js.map
  66752. var BABYLON;
  66753. (function (BABYLON) {
  66754. // Sets the default audio engine to Babylon JS.
  66755. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  66756. /**
  66757. * This represents the default audio engine used in babylon.
  66758. * It is responsible to play, synchronize and analyse sounds throughout the application.
  66759. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66760. */
  66761. var AudioEngine = /** @class */ (function () {
  66762. /**
  66763. * Instantiates a new audio engine.
  66764. *
  66765. * There should be only one per page as some browsers restrict the number
  66766. * of audio contexts you can create.
  66767. * @param engine defines the hosting engine
  66768. */
  66769. function AudioEngine(engine) {
  66770. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  66771. var _this = this;
  66772. this._audioContext = null;
  66773. this._audioContextInitialized = false;
  66774. this._muteButtonDisplayed = false;
  66775. /**
  66776. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  66777. */
  66778. this.canUseWebAudio = false;
  66779. /**
  66780. * Defines if Babylon should emit a warning if WebAudio is not supported.
  66781. * @ignoreNaming
  66782. */
  66783. this.WarnedWebAudioUnsupported = false;
  66784. /**
  66785. * Gets whether or not mp3 are supported by your browser.
  66786. */
  66787. this.isMP3supported = false;
  66788. /**
  66789. * Gets whether or not ogg are supported by your browser.
  66790. */
  66791. this.isOGGsupported = false;
  66792. /**
  66793. * Gets whether audio has been unlocked on the device.
  66794. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  66795. * a user interaction has happened.
  66796. */
  66797. this.unlocked = false;
  66798. /**
  66799. * Event raised when audio has been unlocked on the browser.
  66800. */
  66801. this.onAudioUnlockedObservable = new BABYLON.Observable();
  66802. this._onResize = function () {
  66803. _this._moveButtonToTopLeft();
  66804. };
  66805. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  66806. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  66807. this.canUseWebAudio = true;
  66808. }
  66809. var audioElem = document.createElement('audio');
  66810. this._engine = engine;
  66811. try {
  66812. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  66813. this.isMP3supported = true;
  66814. }
  66815. }
  66816. catch (e) {
  66817. // protect error during capability check.
  66818. }
  66819. try {
  66820. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  66821. this.isOGGsupported = true;
  66822. }
  66823. }
  66824. catch (e) {
  66825. // protect error during capability check.
  66826. }
  66827. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  66828. this._unlockiOSaudio();
  66829. }
  66830. }
  66831. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  66832. /**
  66833. * Gets the current AudioContext if available.
  66834. */
  66835. get: function () {
  66836. if (!this._audioContextInitialized) {
  66837. this._initializeAudioContext();
  66838. }
  66839. else {
  66840. if (!this.unlocked && !this._muteButtonDisplayed) {
  66841. this._displayMuteButton();
  66842. }
  66843. }
  66844. return this._audioContext;
  66845. },
  66846. enumerable: true,
  66847. configurable: true
  66848. });
  66849. AudioEngine.prototype._unlockiOSaudio = function () {
  66850. var _this = this;
  66851. this._displayMuteButton(true);
  66852. var unlockaudio = function () {
  66853. if (!_this.audioContext) {
  66854. return;
  66855. }
  66856. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  66857. var source = _this.audioContext.createBufferSource();
  66858. source.buffer = buffer;
  66859. source.connect(_this.audioContext.destination);
  66860. source.start(0);
  66861. setTimeout(function () {
  66862. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  66863. _this._triggerRunningState();
  66864. _this._muteButton.removeEventListener('touchend', unlockaudio, false);
  66865. }
  66866. }, 0);
  66867. };
  66868. this._muteButton.addEventListener('touchend', unlockaudio, false);
  66869. };
  66870. AudioEngine.prototype._resumeAudioContext = function () {
  66871. this._audioContext.resume();
  66872. };
  66873. AudioEngine.prototype._initializeAudioContext = function () {
  66874. var _this = this;
  66875. try {
  66876. if (this.canUseWebAudio) {
  66877. this._audioContext = new AudioContext();
  66878. // create a global volume gain node
  66879. this.masterGain = this._audioContext.createGain();
  66880. this.masterGain.gain.value = 1;
  66881. this.masterGain.connect(this._audioContext.destination);
  66882. this._audioContextInitialized = true;
  66883. if (this._audioContext.state === "running") {
  66884. this._triggerRunningState();
  66885. }
  66886. else {
  66887. if (!this._muteButtonDisplayed) {
  66888. this._displayMuteButton();
  66889. }
  66890. // 3 possible states: https://webaudio.github.io/web-audio-api/#BaseAudioContext
  66891. this._audioContext.addEventListener("statechange", function () {
  66892. if (_this._audioContext.state === "running") {
  66893. _this._triggerRunningState();
  66894. }
  66895. else {
  66896. _this._triggerSuspendedState();
  66897. }
  66898. });
  66899. }
  66900. }
  66901. }
  66902. catch (e) {
  66903. this.canUseWebAudio = false;
  66904. BABYLON.Tools.Error("Web Audio: " + e.message);
  66905. }
  66906. };
  66907. AudioEngine.prototype._triggerRunningState = function () {
  66908. this.unlocked = true;
  66909. if (this._muteButtonDisplayed) {
  66910. this._hideMuteButton();
  66911. }
  66912. // Notify users that the audio stack is unlocked/unmuted
  66913. this.onAudioUnlockedObservable.notifyObservers(this);
  66914. };
  66915. AudioEngine.prototype._triggerSuspendedState = function () {
  66916. this.unlocked = false;
  66917. this._displayMuteButton();
  66918. };
  66919. AudioEngine.prototype._displayMuteButton = function (iOS) {
  66920. var _this = this;
  66921. if (iOS === void 0) { iOS = false; }
  66922. this._muteButton = document.createElement("BUTTON");
  66923. this._muteButton.className = "babylonUnmuteIcon";
  66924. this._muteButton.id = "babylonUnmuteIconBtn";
  66925. this._muteButton.title = "Unmute";
  66926. var css = ".babylonUnmuteIcon { position: absolute; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 90%; background-repeat:no-repeat; border: none; outline: none; } }";
  66927. var style = document.createElement('style');
  66928. style.appendChild(document.createTextNode(css));
  66929. document.getElementsByTagName('head')[0].appendChild(style);
  66930. this._moveButtonToTopLeft();
  66931. document.body.appendChild(this._muteButton);
  66932. if (!iOS) {
  66933. this._muteButton.addEventListener('mousedown', function () { _this._resumeAudioContext(); }, false);
  66934. }
  66935. this._muteButtonDisplayed = true;
  66936. this._canvas = this._engine.getRenderingCanvas();
  66937. window.addEventListener("resize", this._onResize);
  66938. };
  66939. AudioEngine.prototype._moveButtonToTopLeft = function () {
  66940. if (this._canvas && this._muteButton) {
  66941. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  66942. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  66943. }
  66944. };
  66945. AudioEngine.prototype._hideMuteButton = function () {
  66946. if (this._muteButtonDisplayed) {
  66947. document.body.removeChild(this._muteButton);
  66948. this._muteButtonDisplayed = false;
  66949. }
  66950. };
  66951. /**
  66952. * Destroy and release the resources associated with the audio ccontext.
  66953. */
  66954. AudioEngine.prototype.dispose = function () {
  66955. if (this.canUseWebAudio && this._audioContextInitialized) {
  66956. if (this._connectedAnalyser && this._audioContext) {
  66957. this._connectedAnalyser.stopDebugCanvas();
  66958. this._connectedAnalyser.dispose();
  66959. this.masterGain.disconnect();
  66960. this.masterGain.connect(this._audioContext.destination);
  66961. this._connectedAnalyser = null;
  66962. }
  66963. this.masterGain.gain.value = 1;
  66964. }
  66965. this.WarnedWebAudioUnsupported = false;
  66966. this._hideMuteButton();
  66967. window.removeEventListener("resize", this._onResize);
  66968. this.onAudioUnlockedObservable.clear();
  66969. };
  66970. /**
  66971. * Gets the global volume sets on the master gain.
  66972. * @returns the global volume if set or -1 otherwise
  66973. */
  66974. AudioEngine.prototype.getGlobalVolume = function () {
  66975. if (this.canUseWebAudio && this._audioContextInitialized) {
  66976. return this.masterGain.gain.value;
  66977. }
  66978. else {
  66979. return -1;
  66980. }
  66981. };
  66982. /**
  66983. * Sets the global volume of your experience (sets on the master gain).
  66984. * @param newVolume Defines the new global volume of the application
  66985. */
  66986. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  66987. if (this.canUseWebAudio && this._audioContextInitialized) {
  66988. this.masterGain.gain.value = newVolume;
  66989. }
  66990. };
  66991. /**
  66992. * Connect the audio engine to an audio analyser allowing some amazing
  66993. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  66994. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  66995. * @param analyser The analyser to connect to the engine
  66996. */
  66997. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  66998. if (this._connectedAnalyser) {
  66999. this._connectedAnalyser.stopDebugCanvas();
  67000. }
  67001. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67002. this._connectedAnalyser = analyser;
  67003. this.masterGain.disconnect();
  67004. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67005. }
  67006. };
  67007. return AudioEngine;
  67008. }());
  67009. BABYLON.AudioEngine = AudioEngine;
  67010. })(BABYLON || (BABYLON = {}));
  67011. //# sourceMappingURL=babylon.audioEngine.js.map
  67012. var BABYLON;
  67013. (function (BABYLON) {
  67014. /**
  67015. * Defines a sound that can be played in the application.
  67016. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67017. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67018. */
  67019. var Sound = /** @class */ (function () {
  67020. /**
  67021. * Create a sound and attach it to a scene
  67022. * @param name Name of your sound
  67023. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67024. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67025. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67026. */
  67027. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67028. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67029. var _this = this;
  67030. /**
  67031. * Does the sound autoplay once loaded.
  67032. */
  67033. this.autoplay = false;
  67034. /**
  67035. * Does the sound loop after it finishes playing once.
  67036. */
  67037. this.loop = false;
  67038. /**
  67039. * Does the sound use a custom attenuation curve to simulate the falloff
  67040. * happening when the source gets further away from the camera.
  67041. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67042. */
  67043. this.useCustomAttenuation = false;
  67044. /**
  67045. * Does this sound enables spatial sound.
  67046. */
  67047. this.spatialSound = false;
  67048. this.refDistance = 1;
  67049. this.rolloffFactor = 1;
  67050. this.maxDistance = 100;
  67051. this.distanceModel = "linear";
  67052. this._panningModel = "equalpower";
  67053. /**
  67054. * Observable event when the current playing sound finishes.
  67055. */
  67056. this.onEndedObservable = new BABYLON.Observable();
  67057. this._playbackRate = 1;
  67058. this._streaming = false;
  67059. this._startTime = 0;
  67060. this._startOffset = 0;
  67061. this._position = BABYLON.Vector3.Zero();
  67062. /** @hidden */
  67063. this._positionInEmitterSpace = false;
  67064. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67065. this._volume = 1;
  67066. this._isReadyToPlay = false;
  67067. this.isPlaying = false;
  67068. this.isPaused = false;
  67069. this._isDirectional = false;
  67070. // Used if you'd like to create a directional sound.
  67071. // If not set, the sound will be omnidirectional
  67072. this._coneInnerAngle = 360;
  67073. this._coneOuterAngle = 360;
  67074. this._coneOuterGain = 0;
  67075. this._isOutputConnected = false;
  67076. this._urlType = "Unknown";
  67077. this.name = name;
  67078. this._scene = scene;
  67079. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67080. if (!compo) {
  67081. compo = new BABYLON.AudioSceneComponent(scene);
  67082. scene._addComponent(compo);
  67083. }
  67084. this._readyToPlayCallback = readyToPlayCallback;
  67085. // Default custom attenuation function is a linear attenuation
  67086. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67087. if (currentDistance < maxDistance) {
  67088. return currentVolume * (1 - currentDistance / maxDistance);
  67089. }
  67090. else {
  67091. return 0;
  67092. }
  67093. };
  67094. if (options) {
  67095. this.autoplay = options.autoplay || false;
  67096. this.loop = options.loop || false;
  67097. // if volume === 0, we need another way to check this option
  67098. if (options.volume !== undefined) {
  67099. this._volume = options.volume;
  67100. }
  67101. this.spatialSound = options.spatialSound || false;
  67102. this.maxDistance = options.maxDistance || 100;
  67103. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67104. this.rolloffFactor = options.rolloffFactor || 1;
  67105. this.refDistance = options.refDistance || 1;
  67106. this.distanceModel = options.distanceModel || "linear";
  67107. this._playbackRate = options.playbackRate || 1;
  67108. this._streaming = options.streaming || false;
  67109. }
  67110. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67111. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67112. this._soundGain.gain.value = this._volume;
  67113. this._inputAudioNode = this._soundGain;
  67114. this._outputAudioNode = this._soundGain;
  67115. if (this.spatialSound) {
  67116. this._createSpatialParameters();
  67117. }
  67118. this._scene.mainSoundTrack.AddSound(this);
  67119. var validParameter = true;
  67120. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67121. if (urlOrArrayBuffer) {
  67122. try {
  67123. if (typeof (urlOrArrayBuffer) === "string") {
  67124. this._urlType = "String";
  67125. }
  67126. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67127. this._urlType = "ArrayBuffer";
  67128. }
  67129. else if (urlOrArrayBuffer instanceof MediaStream) {
  67130. this._urlType = "MediaStream";
  67131. }
  67132. else if (Array.isArray(urlOrArrayBuffer)) {
  67133. this._urlType = "Array";
  67134. }
  67135. var urls = [];
  67136. var codecSupportedFound = false;
  67137. switch (this._urlType) {
  67138. case "MediaStream":
  67139. this._streaming = true;
  67140. this._isReadyToPlay = true;
  67141. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67142. if (this.autoplay) {
  67143. this.play();
  67144. }
  67145. if (this._readyToPlayCallback) {
  67146. this._readyToPlayCallback();
  67147. }
  67148. break;
  67149. case "ArrayBuffer":
  67150. if (urlOrArrayBuffer.byteLength > 0) {
  67151. codecSupportedFound = true;
  67152. this._soundLoaded(urlOrArrayBuffer);
  67153. }
  67154. break;
  67155. case "String":
  67156. urls.push(urlOrArrayBuffer);
  67157. case "Array":
  67158. if (urls.length === 0)
  67159. urls = urlOrArrayBuffer;
  67160. // If we found a supported format, we load it immediately and stop the loop
  67161. for (var i = 0; i < urls.length; i++) {
  67162. var url = urls[i];
  67163. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67164. codecSupportedFound = true;
  67165. }
  67166. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67167. codecSupportedFound = true;
  67168. }
  67169. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67170. codecSupportedFound = true;
  67171. }
  67172. if (url.indexOf("blob:") !== -1) {
  67173. codecSupportedFound = true;
  67174. }
  67175. if (codecSupportedFound) {
  67176. // Loading sound using XHR2
  67177. if (!this._streaming) {
  67178. this._scene._loadFile(url, function (data) {
  67179. _this._soundLoaded(data);
  67180. }, undefined, true, true, function (exception) {
  67181. if (exception) {
  67182. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67183. }
  67184. BABYLON.Tools.Error("Sound creation aborted.");
  67185. _this._scene.mainSoundTrack.RemoveSound(_this);
  67186. });
  67187. }
  67188. // Streaming sound using HTML5 Audio tag
  67189. else {
  67190. this._htmlAudioElement = new Audio(url);
  67191. this._htmlAudioElement.controls = false;
  67192. this._htmlAudioElement.loop = this.loop;
  67193. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67194. this._htmlAudioElement.preload = "auto";
  67195. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67196. _this._isReadyToPlay = true;
  67197. if (_this.autoplay) {
  67198. _this.play();
  67199. }
  67200. if (_this._readyToPlayCallback) {
  67201. _this._readyToPlayCallback();
  67202. }
  67203. });
  67204. document.body.appendChild(this._htmlAudioElement);
  67205. }
  67206. break;
  67207. }
  67208. }
  67209. break;
  67210. default:
  67211. validParameter = false;
  67212. break;
  67213. }
  67214. if (!validParameter) {
  67215. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67216. }
  67217. else {
  67218. if (!codecSupportedFound) {
  67219. this._isReadyToPlay = true;
  67220. // Simulating a ready to play event to avoid breaking code path
  67221. if (this._readyToPlayCallback) {
  67222. window.setTimeout(function () {
  67223. if (_this._readyToPlayCallback) {
  67224. _this._readyToPlayCallback();
  67225. }
  67226. }, 1000);
  67227. }
  67228. }
  67229. }
  67230. }
  67231. catch (ex) {
  67232. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67233. this._scene.mainSoundTrack.RemoveSound(this);
  67234. }
  67235. }
  67236. }
  67237. else {
  67238. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  67239. this._scene.mainSoundTrack.AddSound(this);
  67240. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  67241. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  67242. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  67243. }
  67244. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  67245. if (this._readyToPlayCallback) {
  67246. window.setTimeout(function () {
  67247. if (_this._readyToPlayCallback) {
  67248. _this._readyToPlayCallback();
  67249. }
  67250. }, 1000);
  67251. }
  67252. }
  67253. }
  67254. Sound.prototype.dispose = function () {
  67255. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67256. if (this.isPlaying) {
  67257. this.stop();
  67258. }
  67259. this._isReadyToPlay = false;
  67260. if (this.soundTrackId === -1) {
  67261. this._scene.mainSoundTrack.RemoveSound(this);
  67262. }
  67263. else if (this._scene.soundTracks) {
  67264. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  67265. }
  67266. if (this._soundGain) {
  67267. this._soundGain.disconnect();
  67268. this._soundGain = null;
  67269. }
  67270. if (this._soundPanner) {
  67271. this._soundPanner.disconnect();
  67272. this._soundPanner = null;
  67273. }
  67274. if (this._soundSource) {
  67275. this._soundSource.disconnect();
  67276. this._soundSource = null;
  67277. }
  67278. this._audioBuffer = null;
  67279. if (this._htmlAudioElement) {
  67280. this._htmlAudioElement.pause();
  67281. this._htmlAudioElement.src = "";
  67282. document.body.removeChild(this._htmlAudioElement);
  67283. }
  67284. if (this._streamingSource) {
  67285. this._streamingSource.disconnect();
  67286. }
  67287. if (this._connectedMesh && this._registerFunc) {
  67288. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67289. this._connectedMesh = null;
  67290. }
  67291. }
  67292. };
  67293. Sound.prototype.isReady = function () {
  67294. return this._isReadyToPlay;
  67295. };
  67296. Sound.prototype._soundLoaded = function (audioData) {
  67297. var _this = this;
  67298. if (!BABYLON.Engine.audioEngine.audioContext) {
  67299. return;
  67300. }
  67301. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  67302. _this._audioBuffer = buffer;
  67303. _this._isReadyToPlay = true;
  67304. if (_this.autoplay) {
  67305. _this.play();
  67306. }
  67307. if (_this._readyToPlayCallback) {
  67308. _this._readyToPlayCallback();
  67309. }
  67310. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  67311. };
  67312. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  67313. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67314. this._audioBuffer = audioBuffer;
  67315. this._isReadyToPlay = true;
  67316. }
  67317. };
  67318. Sound.prototype.updateOptions = function (options) {
  67319. if (options) {
  67320. this.loop = options.loop || this.loop;
  67321. this.maxDistance = options.maxDistance || this.maxDistance;
  67322. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  67323. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  67324. this.refDistance = options.refDistance || this.refDistance;
  67325. this.distanceModel = options.distanceModel || this.distanceModel;
  67326. this._playbackRate = options.playbackRate || this._playbackRate;
  67327. this._updateSpatialParameters();
  67328. if (this.isPlaying) {
  67329. if (this._streaming && this._htmlAudioElement) {
  67330. this._htmlAudioElement.playbackRate = this._playbackRate;
  67331. }
  67332. else {
  67333. if (this._soundSource) {
  67334. this._soundSource.playbackRate.value = this._playbackRate;
  67335. }
  67336. }
  67337. }
  67338. }
  67339. };
  67340. Sound.prototype._createSpatialParameters = function () {
  67341. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67342. if (this._scene.headphone) {
  67343. this._panningModel = "HRTF";
  67344. }
  67345. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  67346. this._updateSpatialParameters();
  67347. this._soundPanner.connect(this._outputAudioNode);
  67348. this._inputAudioNode = this._soundPanner;
  67349. }
  67350. };
  67351. Sound.prototype._updateSpatialParameters = function () {
  67352. if (this.spatialSound && this._soundPanner) {
  67353. if (this.useCustomAttenuation) {
  67354. // Tricks to disable in a way embedded Web Audio attenuation
  67355. this._soundPanner.distanceModel = "linear";
  67356. this._soundPanner.maxDistance = Number.MAX_VALUE;
  67357. this._soundPanner.refDistance = 1;
  67358. this._soundPanner.rolloffFactor = 1;
  67359. this._soundPanner.panningModel = this._panningModel;
  67360. }
  67361. else {
  67362. this._soundPanner.distanceModel = this.distanceModel;
  67363. this._soundPanner.maxDistance = this.maxDistance;
  67364. this._soundPanner.refDistance = this.refDistance;
  67365. this._soundPanner.rolloffFactor = this.rolloffFactor;
  67366. this._soundPanner.panningModel = this._panningModel;
  67367. }
  67368. }
  67369. };
  67370. Sound.prototype.switchPanningModelToHRTF = function () {
  67371. this._panningModel = "HRTF";
  67372. this._switchPanningModel();
  67373. };
  67374. Sound.prototype.switchPanningModelToEqualPower = function () {
  67375. this._panningModel = "equalpower";
  67376. this._switchPanningModel();
  67377. };
  67378. Sound.prototype._switchPanningModel = function () {
  67379. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67380. this._soundPanner.panningModel = this._panningModel;
  67381. }
  67382. };
  67383. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  67384. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67385. if (this._isOutputConnected) {
  67386. this._outputAudioNode.disconnect();
  67387. }
  67388. this._outputAudioNode.connect(soundTrackAudioNode);
  67389. this._isOutputConnected = true;
  67390. }
  67391. };
  67392. /**
  67393. * Transform this sound into a directional source
  67394. * @param coneInnerAngle Size of the inner cone in degree
  67395. * @param coneOuterAngle Size of the outer cone in degree
  67396. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  67397. */
  67398. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  67399. if (coneOuterAngle < coneInnerAngle) {
  67400. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  67401. return;
  67402. }
  67403. this._coneInnerAngle = coneInnerAngle;
  67404. this._coneOuterAngle = coneOuterAngle;
  67405. this._coneOuterGain = coneOuterGain;
  67406. this._isDirectional = true;
  67407. if (this.isPlaying && this.loop) {
  67408. this.stop();
  67409. this.play();
  67410. }
  67411. };
  67412. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  67413. /**
  67414. * Gets or sets the inner angle for the directional cone.
  67415. */
  67416. get: function () {
  67417. return this._coneInnerAngle;
  67418. },
  67419. /**
  67420. * Gets or sets the inner angle for the directional cone.
  67421. */
  67422. set: function (value) {
  67423. if (value != this._coneInnerAngle) {
  67424. if (this._coneOuterAngle < value) {
  67425. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67426. return;
  67427. }
  67428. this._coneInnerAngle = value;
  67429. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67430. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67431. }
  67432. }
  67433. },
  67434. enumerable: true,
  67435. configurable: true
  67436. });
  67437. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  67438. /**
  67439. * Gets or sets the outer angle for the directional cone.
  67440. */
  67441. get: function () {
  67442. return this._coneOuterAngle;
  67443. },
  67444. /**
  67445. * Gets or sets the outer angle for the directional cone.
  67446. */
  67447. set: function (value) {
  67448. if (value != this._coneOuterAngle) {
  67449. if (value < this._coneInnerAngle) {
  67450. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67451. return;
  67452. }
  67453. this._coneOuterAngle = value;
  67454. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67455. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67456. }
  67457. }
  67458. },
  67459. enumerable: true,
  67460. configurable: true
  67461. });
  67462. Sound.prototype.setPosition = function (newPosition) {
  67463. this._position = newPosition;
  67464. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  67465. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  67466. }
  67467. };
  67468. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  67469. this._localDirection = newLocalDirection;
  67470. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  67471. this._updateDirection();
  67472. }
  67473. };
  67474. Sound.prototype._updateDirection = function () {
  67475. if (!this._connectedMesh || !this._soundPanner) {
  67476. return;
  67477. }
  67478. var mat = this._connectedMesh.getWorldMatrix();
  67479. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  67480. direction.normalize();
  67481. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  67482. };
  67483. Sound.prototype.updateDistanceFromListener = function () {
  67484. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  67485. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  67486. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  67487. }
  67488. };
  67489. Sound.prototype.setAttenuationFunction = function (callback) {
  67490. this._customAttenuationFunction = callback;
  67491. };
  67492. /**
  67493. * Play the sound
  67494. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  67495. * @param offset (optional) Start the sound setting it at a specific time
  67496. */
  67497. Sound.prototype.play = function (time, offset) {
  67498. var _this = this;
  67499. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  67500. try {
  67501. if (this._startOffset < 0) {
  67502. time = -this._startOffset;
  67503. this._startOffset = 0;
  67504. }
  67505. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  67506. if (!this._soundSource || !this._streamingSource) {
  67507. if (this.spatialSound && this._soundPanner) {
  67508. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  67509. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  67510. }
  67511. if (this._isDirectional) {
  67512. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67513. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67514. this._soundPanner.coneOuterGain = this._coneOuterGain;
  67515. if (this._connectedMesh) {
  67516. this._updateDirection();
  67517. }
  67518. else {
  67519. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  67520. }
  67521. }
  67522. }
  67523. }
  67524. if (this._streaming) {
  67525. if (!this._streamingSource) {
  67526. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  67527. this._htmlAudioElement.onended = function () { _this._onended(); };
  67528. this._htmlAudioElement.playbackRate = this._playbackRate;
  67529. }
  67530. this._streamingSource.disconnect();
  67531. this._streamingSource.connect(this._inputAudioNode);
  67532. if (this._htmlAudioElement) {
  67533. // required to manage properly the new suspended default state of Chrome
  67534. // When the option 'streaming: true' is used, we need first to wait for
  67535. // the audio engine to be unlocked by a user gesture before trying to play
  67536. // an HTML Audio elememt
  67537. var tryToPlay = function () {
  67538. if (BABYLON.Engine.audioEngine.unlocked) {
  67539. var playPromise = _this._htmlAudioElement.play();
  67540. // In browsers that don’t yet support this functionality,
  67541. // playPromise won’t be defined.
  67542. if (playPromise !== undefined) {
  67543. playPromise.catch(function (error) {
  67544. // Automatic playback failed.
  67545. // Waiting for the audio engine to be unlocked by user click on unmute
  67546. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { return tryToPlay; });
  67547. });
  67548. }
  67549. }
  67550. else {
  67551. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { return tryToPlay; });
  67552. }
  67553. };
  67554. tryToPlay();
  67555. }
  67556. }
  67557. else {
  67558. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  67559. this._soundSource.buffer = this._audioBuffer;
  67560. this._soundSource.connect(this._inputAudioNode);
  67561. this._soundSource.loop = this.loop;
  67562. this._soundSource.playbackRate.value = this._playbackRate;
  67563. this._soundSource.onended = function () { _this._onended(); };
  67564. if (this._soundSource.buffer) {
  67565. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  67566. }
  67567. }
  67568. this._startTime = startTime;
  67569. this.isPlaying = true;
  67570. this.isPaused = false;
  67571. }
  67572. catch (ex) {
  67573. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  67574. }
  67575. }
  67576. };
  67577. Sound.prototype._onended = function () {
  67578. this.isPlaying = false;
  67579. if (this.onended) {
  67580. this.onended();
  67581. }
  67582. this.onEndedObservable.notifyObservers(this);
  67583. };
  67584. /**
  67585. * Stop the sound
  67586. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  67587. */
  67588. Sound.prototype.stop = function (time) {
  67589. if (this.isPlaying) {
  67590. if (this._streaming) {
  67591. if (this._htmlAudioElement) {
  67592. this._htmlAudioElement.pause();
  67593. // Test needed for Firefox or it will generate an Invalid State Error
  67594. if (this._htmlAudioElement.currentTime > 0) {
  67595. this._htmlAudioElement.currentTime = 0;
  67596. }
  67597. }
  67598. else {
  67599. this._streamingSource.disconnect();
  67600. }
  67601. }
  67602. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  67603. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  67604. this._soundSource.stop(stopTime);
  67605. this._soundSource.onended = function () { };
  67606. if (!this.isPaused) {
  67607. this._startOffset = 0;
  67608. }
  67609. }
  67610. this.isPlaying = false;
  67611. }
  67612. };
  67613. Sound.prototype.pause = function () {
  67614. if (this.isPlaying) {
  67615. this.isPaused = true;
  67616. if (this._streaming) {
  67617. if (this._htmlAudioElement) {
  67618. this._htmlAudioElement.pause();
  67619. }
  67620. else {
  67621. this._streamingSource.disconnect();
  67622. }
  67623. }
  67624. else if (BABYLON.Engine.audioEngine.audioContext) {
  67625. this.stop(0);
  67626. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  67627. }
  67628. }
  67629. };
  67630. Sound.prototype.setVolume = function (newVolume, time) {
  67631. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  67632. if (time && BABYLON.Engine.audioEngine.audioContext) {
  67633. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  67634. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  67635. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  67636. }
  67637. else {
  67638. this._soundGain.gain.value = newVolume;
  67639. }
  67640. }
  67641. this._volume = newVolume;
  67642. };
  67643. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  67644. this._playbackRate = newPlaybackRate;
  67645. if (this.isPlaying) {
  67646. if (this._streaming && this._htmlAudioElement) {
  67647. this._htmlAudioElement.playbackRate = this._playbackRate;
  67648. }
  67649. else if (this._soundSource) {
  67650. this._soundSource.playbackRate.value = this._playbackRate;
  67651. }
  67652. }
  67653. };
  67654. Sound.prototype.getVolume = function () {
  67655. return this._volume;
  67656. };
  67657. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  67658. var _this = this;
  67659. if (this._connectedMesh && this._registerFunc) {
  67660. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67661. this._registerFunc = null;
  67662. }
  67663. this._connectedMesh = meshToConnectTo;
  67664. if (!this.spatialSound) {
  67665. this.spatialSound = true;
  67666. this._createSpatialParameters();
  67667. if (this.isPlaying && this.loop) {
  67668. this.stop();
  67669. this.play();
  67670. }
  67671. }
  67672. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  67673. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  67674. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  67675. };
  67676. Sound.prototype.detachFromMesh = function () {
  67677. if (this._connectedMesh && this._registerFunc) {
  67678. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67679. this._registerFunc = null;
  67680. this._connectedMesh = null;
  67681. }
  67682. };
  67683. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  67684. if (!node.getBoundingInfo) {
  67685. return;
  67686. }
  67687. var mesh = node;
  67688. if (this._positionInEmitterSpace) {
  67689. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  67690. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  67691. }
  67692. else {
  67693. var boundingInfo = mesh.getBoundingInfo();
  67694. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  67695. }
  67696. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  67697. this._updateDirection();
  67698. }
  67699. };
  67700. Sound.prototype.clone = function () {
  67701. var _this = this;
  67702. if (!this._streaming) {
  67703. var setBufferAndRun = function () {
  67704. if (_this._isReadyToPlay) {
  67705. clonedSound._audioBuffer = _this.getAudioBuffer();
  67706. clonedSound._isReadyToPlay = true;
  67707. if (clonedSound.autoplay) {
  67708. clonedSound.play();
  67709. }
  67710. }
  67711. else {
  67712. window.setTimeout(setBufferAndRun, 300);
  67713. }
  67714. };
  67715. var currentOptions = {
  67716. autoplay: this.autoplay, loop: this.loop,
  67717. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  67718. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  67719. refDistance: this.refDistance, distanceModel: this.distanceModel
  67720. };
  67721. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  67722. if (this.useCustomAttenuation) {
  67723. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  67724. }
  67725. clonedSound.setPosition(this._position);
  67726. clonedSound.setPlaybackRate(this._playbackRate);
  67727. setBufferAndRun();
  67728. return clonedSound;
  67729. }
  67730. // Can't clone a streaming sound
  67731. else {
  67732. return null;
  67733. }
  67734. };
  67735. Sound.prototype.getAudioBuffer = function () {
  67736. return this._audioBuffer;
  67737. };
  67738. Sound.prototype.serialize = function () {
  67739. var serializationObject = {
  67740. name: this.name,
  67741. url: this.name,
  67742. autoplay: this.autoplay,
  67743. loop: this.loop,
  67744. volume: this._volume,
  67745. spatialSound: this.spatialSound,
  67746. maxDistance: this.maxDistance,
  67747. rolloffFactor: this.rolloffFactor,
  67748. refDistance: this.refDistance,
  67749. distanceModel: this.distanceModel,
  67750. playbackRate: this._playbackRate,
  67751. panningModel: this._panningModel,
  67752. soundTrackId: this.soundTrackId
  67753. };
  67754. if (this.spatialSound) {
  67755. if (this._connectedMesh)
  67756. serializationObject.connectedMeshId = this._connectedMesh.id;
  67757. serializationObject.position = this._position.asArray();
  67758. serializationObject.refDistance = this.refDistance;
  67759. serializationObject.distanceModel = this.distanceModel;
  67760. serializationObject.isDirectional = this._isDirectional;
  67761. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  67762. serializationObject.coneInnerAngle = this._coneInnerAngle;
  67763. serializationObject.coneOuterAngle = this._coneOuterAngle;
  67764. serializationObject.coneOuterGain = this._coneOuterGain;
  67765. }
  67766. return serializationObject;
  67767. };
  67768. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  67769. var soundName = parsedSound.name;
  67770. var soundUrl;
  67771. if (parsedSound.url) {
  67772. soundUrl = rootUrl + parsedSound.url;
  67773. }
  67774. else {
  67775. soundUrl = rootUrl + soundName;
  67776. }
  67777. var options = {
  67778. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  67779. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  67780. rolloffFactor: parsedSound.rolloffFactor,
  67781. refDistance: parsedSound.refDistance,
  67782. distanceModel: parsedSound.distanceModel,
  67783. playbackRate: parsedSound.playbackRate
  67784. };
  67785. var newSound;
  67786. if (!sourceSound) {
  67787. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  67788. scene._addPendingData(newSound);
  67789. }
  67790. else {
  67791. var setBufferAndRun = function () {
  67792. if (sourceSound._isReadyToPlay) {
  67793. newSound._audioBuffer = sourceSound.getAudioBuffer();
  67794. newSound._isReadyToPlay = true;
  67795. if (newSound.autoplay) {
  67796. newSound.play();
  67797. }
  67798. }
  67799. else {
  67800. window.setTimeout(setBufferAndRun, 300);
  67801. }
  67802. };
  67803. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  67804. setBufferAndRun();
  67805. }
  67806. if (parsedSound.position) {
  67807. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  67808. newSound.setPosition(soundPosition);
  67809. }
  67810. if (parsedSound.isDirectional) {
  67811. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  67812. if (parsedSound.localDirectionToMesh) {
  67813. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  67814. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  67815. }
  67816. }
  67817. if (parsedSound.connectedMeshId) {
  67818. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  67819. if (connectedMesh) {
  67820. newSound.attachToMesh(connectedMesh);
  67821. }
  67822. }
  67823. return newSound;
  67824. };
  67825. return Sound;
  67826. }());
  67827. BABYLON.Sound = Sound;
  67828. })(BABYLON || (BABYLON = {}));
  67829. //# sourceMappingURL=babylon.sound.js.map
  67830. var BABYLON;
  67831. (function (BABYLON) {
  67832. var SoundTrack = /** @class */ (function () {
  67833. function SoundTrack(scene, options) {
  67834. this.id = -1;
  67835. this._isMainTrack = false;
  67836. this._isInitialized = false;
  67837. this._scene = scene;
  67838. this.soundCollection = new Array();
  67839. this._options = options;
  67840. if (!this._isMainTrack && this._scene.soundTracks) {
  67841. this._scene.soundTracks.push(this);
  67842. this.id = this._scene.soundTracks.length - 1;
  67843. }
  67844. }
  67845. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  67846. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67847. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  67848. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  67849. if (this._options) {
  67850. if (this._options.volume) {
  67851. this._outputAudioNode.gain.value = this._options.volume;
  67852. }
  67853. if (this._options.mainTrack) {
  67854. this._isMainTrack = this._options.mainTrack;
  67855. }
  67856. }
  67857. this._isInitialized = true;
  67858. }
  67859. };
  67860. SoundTrack.prototype.dispose = function () {
  67861. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  67862. if (this._connectedAnalyser) {
  67863. this._connectedAnalyser.stopDebugCanvas();
  67864. }
  67865. while (this.soundCollection.length) {
  67866. this.soundCollection[0].dispose();
  67867. }
  67868. if (this._outputAudioNode) {
  67869. this._outputAudioNode.disconnect();
  67870. }
  67871. this._outputAudioNode = null;
  67872. }
  67873. };
  67874. SoundTrack.prototype.AddSound = function (sound) {
  67875. if (!this._isInitialized) {
  67876. this._initializeSoundTrackAudioGraph();
  67877. }
  67878. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  67879. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  67880. }
  67881. if (sound.soundTrackId) {
  67882. if (sound.soundTrackId === -1) {
  67883. this._scene.mainSoundTrack.RemoveSound(sound);
  67884. }
  67885. else if (this._scene.soundTracks) {
  67886. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  67887. }
  67888. }
  67889. this.soundCollection.push(sound);
  67890. sound.soundTrackId = this.id;
  67891. };
  67892. SoundTrack.prototype.RemoveSound = function (sound) {
  67893. var index = this.soundCollection.indexOf(sound);
  67894. if (index !== -1) {
  67895. this.soundCollection.splice(index, 1);
  67896. }
  67897. };
  67898. SoundTrack.prototype.setVolume = function (newVolume) {
  67899. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  67900. this._outputAudioNode.gain.value = newVolume;
  67901. }
  67902. };
  67903. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  67904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67905. for (var i = 0; i < this.soundCollection.length; i++) {
  67906. this.soundCollection[i].switchPanningModelToHRTF();
  67907. }
  67908. }
  67909. };
  67910. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  67911. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67912. for (var i = 0; i < this.soundCollection.length; i++) {
  67913. this.soundCollection[i].switchPanningModelToEqualPower();
  67914. }
  67915. }
  67916. };
  67917. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  67918. if (this._connectedAnalyser) {
  67919. this._connectedAnalyser.stopDebugCanvas();
  67920. }
  67921. this._connectedAnalyser = analyser;
  67922. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  67923. this._outputAudioNode.disconnect();
  67924. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  67925. }
  67926. };
  67927. return SoundTrack;
  67928. }());
  67929. BABYLON.SoundTrack = SoundTrack;
  67930. })(BABYLON || (BABYLON = {}));
  67931. //# sourceMappingURL=babylon.soundtrack.js.map
  67932. var BABYLON;
  67933. (function (BABYLON) {
  67934. /**
  67935. * Class used to work with sound analyzer using fast fourier transform (FFT)
  67936. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67937. */
  67938. var Analyser = /** @class */ (function () {
  67939. /**
  67940. * Creates a new analyser
  67941. * @param scene defines hosting scene
  67942. */
  67943. function Analyser(scene) {
  67944. /**
  67945. * Gets or sets the smoothing
  67946. * @ignorenaming
  67947. */
  67948. this.SMOOTHING = 0.75;
  67949. /**
  67950. * Gets or sets the FFT table size
  67951. * @ignorenaming
  67952. */
  67953. this.FFT_SIZE = 512;
  67954. /**
  67955. * Gets or sets the bar graph amplitude
  67956. * @ignorenaming
  67957. */
  67958. this.BARGRAPHAMPLITUDE = 256;
  67959. /**
  67960. * Gets or sets the position of the debug canvas
  67961. * @ignorenaming
  67962. */
  67963. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  67964. /**
  67965. * Gets or sets the debug canvas size
  67966. * @ignorenaming
  67967. */
  67968. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  67969. this._scene = scene;
  67970. this._audioEngine = BABYLON.Engine.audioEngine;
  67971. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  67972. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  67973. this._webAudioAnalyser.minDecibels = -140;
  67974. this._webAudioAnalyser.maxDecibels = 0;
  67975. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  67976. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  67977. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  67978. }
  67979. }
  67980. /**
  67981. * Get the number of data values you will have to play with for the visualization
  67982. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  67983. * @returns a number
  67984. */
  67985. Analyser.prototype.getFrequencyBinCount = function () {
  67986. if (this._audioEngine.canUseWebAudio) {
  67987. return this._webAudioAnalyser.frequencyBinCount;
  67988. }
  67989. else {
  67990. return 0;
  67991. }
  67992. };
  67993. /**
  67994. * Gets the current frequency data as a byte array
  67995. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  67996. * @returns a Uint8Array
  67997. */
  67998. Analyser.prototype.getByteFrequencyData = function () {
  67999. if (this._audioEngine.canUseWebAudio) {
  68000. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68001. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68002. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68003. }
  68004. return this._byteFreqs;
  68005. };
  68006. /**
  68007. * Gets the current waveform as a byte array
  68008. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68009. * @returns a Uint8Array
  68010. */
  68011. Analyser.prototype.getByteTimeDomainData = function () {
  68012. if (this._audioEngine.canUseWebAudio) {
  68013. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68014. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68015. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68016. }
  68017. return this._byteTime;
  68018. };
  68019. /**
  68020. * Gets the current frequency data as a float array
  68021. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68022. * @returns a Float32Array
  68023. */
  68024. Analyser.prototype.getFloatFrequencyData = function () {
  68025. if (this._audioEngine.canUseWebAudio) {
  68026. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68027. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68028. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68029. }
  68030. return this._floatFreqs;
  68031. };
  68032. /**
  68033. * Renders the debug canvas
  68034. */
  68035. Analyser.prototype.drawDebugCanvas = function () {
  68036. var _this = this;
  68037. if (this._audioEngine.canUseWebAudio) {
  68038. if (!this._debugCanvas) {
  68039. this._debugCanvas = document.createElement("canvas");
  68040. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68041. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68042. this._debugCanvas.style.position = "absolute";
  68043. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68044. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68045. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68046. document.body.appendChild(this._debugCanvas);
  68047. this._registerFunc = function () {
  68048. _this.drawDebugCanvas();
  68049. };
  68050. this._scene.registerBeforeRender(this._registerFunc);
  68051. }
  68052. if (this._registerFunc && this._debugCanvasContext) {
  68053. var workingArray = this.getByteFrequencyData();
  68054. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68055. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68056. // Draw the frequency domain chart.
  68057. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68058. var value = workingArray[i];
  68059. var percent = value / this.BARGRAPHAMPLITUDE;
  68060. var height = this.DEBUGCANVASSIZE.height * percent;
  68061. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68062. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68063. var hue = i / this.getFrequencyBinCount() * 360;
  68064. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68065. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68066. }
  68067. }
  68068. }
  68069. };
  68070. /**
  68071. * Stops rendering the debug canvas and removes it
  68072. */
  68073. Analyser.prototype.stopDebugCanvas = function () {
  68074. if (this._debugCanvas) {
  68075. if (this._registerFunc) {
  68076. this._scene.unregisterBeforeRender(this._registerFunc);
  68077. this._registerFunc = null;
  68078. }
  68079. document.body.removeChild(this._debugCanvas);
  68080. this._debugCanvas = null;
  68081. this._debugCanvasContext = null;
  68082. }
  68083. };
  68084. /**
  68085. * Connects two audio nodes
  68086. * @param inputAudioNode defines first node to connect
  68087. * @param outputAudioNode defines second node to connect
  68088. */
  68089. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68090. if (this._audioEngine.canUseWebAudio) {
  68091. inputAudioNode.connect(this._webAudioAnalyser);
  68092. this._webAudioAnalyser.connect(outputAudioNode);
  68093. }
  68094. };
  68095. /**
  68096. * Releases all associated resources
  68097. */
  68098. Analyser.prototype.dispose = function () {
  68099. if (this._audioEngine.canUseWebAudio) {
  68100. this._webAudioAnalyser.disconnect();
  68101. }
  68102. };
  68103. return Analyser;
  68104. }());
  68105. BABYLON.Analyser = Analyser;
  68106. })(BABYLON || (BABYLON = {}));
  68107. //# sourceMappingURL=babylon.analyser.js.map
  68108. var BABYLON;
  68109. (function (BABYLON) {
  68110. /**
  68111. * Wraps one or more Sound objects and selects one with random weight for playback.
  68112. */
  68113. var WeightedSound = /** @class */ (function () {
  68114. /**
  68115. * Creates a new WeightedSound from the list of sounds given.
  68116. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  68117. * @param sounds Array of Sounds that will be selected from.
  68118. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  68119. */
  68120. function WeightedSound(loop, sounds, weights) {
  68121. var _this = this;
  68122. /** When true a Sound will be selected and played when the current playing Sound completes. */
  68123. this.loop = false;
  68124. this._coneInnerAngle = 360;
  68125. this._coneOuterAngle = 360;
  68126. this._volume = 1;
  68127. /** A Sound is currently playing. */
  68128. this.isPlaying = false;
  68129. /** A Sound is currently paused. */
  68130. this.isPaused = false;
  68131. this._sounds = [];
  68132. this._weights = [];
  68133. if (sounds.length !== weights.length) {
  68134. throw new Error('Sounds length does not equal weights length');
  68135. }
  68136. this.loop = loop;
  68137. this._weights = weights;
  68138. // Normalize the weights
  68139. var weightSum = 0;
  68140. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  68141. var weight = weights_1[_i];
  68142. weightSum += weight;
  68143. }
  68144. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  68145. for (var i = 0; i < this._weights.length; i++) {
  68146. this._weights[i] *= invWeightSum;
  68147. }
  68148. this._sounds = sounds;
  68149. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  68150. var sound = _b[_a];
  68151. sound.onEndedObservable.add(function () { _this._onended(); });
  68152. }
  68153. }
  68154. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  68155. /**
  68156. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  68157. */
  68158. get: function () {
  68159. return this._coneInnerAngle;
  68160. },
  68161. /**
  68162. * The size of cone in degress for a directional sound in which there will be no attenuation.
  68163. */
  68164. set: function (value) {
  68165. if (value !== this._coneInnerAngle) {
  68166. if (this._coneOuterAngle < value) {
  68167. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68168. return;
  68169. }
  68170. this._coneInnerAngle = value;
  68171. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68172. var sound = _a[_i];
  68173. sound.directionalConeInnerAngle = value;
  68174. }
  68175. }
  68176. },
  68177. enumerable: true,
  68178. configurable: true
  68179. });
  68180. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  68181. /**
  68182. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68183. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68184. */
  68185. get: function () {
  68186. return this._coneOuterAngle;
  68187. },
  68188. /**
  68189. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68190. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68191. */
  68192. set: function (value) {
  68193. if (value !== this._coneOuterAngle) {
  68194. if (value < this._coneInnerAngle) {
  68195. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68196. return;
  68197. }
  68198. this._coneOuterAngle = value;
  68199. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68200. var sound = _a[_i];
  68201. sound.directionalConeOuterAngle = value;
  68202. }
  68203. }
  68204. },
  68205. enumerable: true,
  68206. configurable: true
  68207. });
  68208. Object.defineProperty(WeightedSound.prototype, "volume", {
  68209. /**
  68210. * Playback volume.
  68211. */
  68212. get: function () {
  68213. return this._volume;
  68214. },
  68215. /**
  68216. * Playback volume.
  68217. */
  68218. set: function (value) {
  68219. if (value !== this._volume) {
  68220. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68221. var sound = _a[_i];
  68222. sound.setVolume(value);
  68223. }
  68224. }
  68225. },
  68226. enumerable: true,
  68227. configurable: true
  68228. });
  68229. WeightedSound.prototype._onended = function () {
  68230. if (this._currentIndex !== undefined) {
  68231. this._sounds[this._currentIndex].autoplay = false;
  68232. }
  68233. if (this.loop && this.isPlaying) {
  68234. this.play();
  68235. }
  68236. else {
  68237. this.isPlaying = false;
  68238. }
  68239. };
  68240. /**
  68241. * Suspend playback
  68242. */
  68243. WeightedSound.prototype.pause = function () {
  68244. this.isPaused = true;
  68245. if (this._currentIndex !== undefined) {
  68246. this._sounds[this._currentIndex].pause();
  68247. }
  68248. };
  68249. /**
  68250. * Stop playback
  68251. */
  68252. WeightedSound.prototype.stop = function () {
  68253. this.isPlaying = false;
  68254. if (this._currentIndex !== undefined) {
  68255. this._sounds[this._currentIndex].stop();
  68256. }
  68257. };
  68258. /**
  68259. * Start playback.
  68260. * @param startOffset Position the clip head at a specific time in seconds.
  68261. */
  68262. WeightedSound.prototype.play = function (startOffset) {
  68263. if (!this.isPaused) {
  68264. this.stop();
  68265. var randomValue = Math.random();
  68266. var total = 0;
  68267. for (var i = 0; i < this._weights.length; i++) {
  68268. total += this._weights[i];
  68269. if (randomValue <= total) {
  68270. this._currentIndex = i;
  68271. break;
  68272. }
  68273. }
  68274. }
  68275. var sound = this._sounds[this._currentIndex];
  68276. if (sound.isReady()) {
  68277. sound.play(0, this.isPaused ? undefined : startOffset);
  68278. }
  68279. else {
  68280. sound.autoplay = true;
  68281. }
  68282. this.isPlaying = true;
  68283. this.isPaused = false;
  68284. };
  68285. return WeightedSound;
  68286. }());
  68287. BABYLON.WeightedSound = WeightedSound;
  68288. })(BABYLON || (BABYLON = {}));
  68289. //# sourceMappingURL=babylon.weightedsound.js.map
  68290. var BABYLON;
  68291. (function (BABYLON) {
  68292. // Adds the parser to the scene parsers.
  68293. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  68294. // TODO: add sound
  68295. var loadedSounds = [];
  68296. var loadedSound;
  68297. container.sounds = container.sounds || [];
  68298. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68299. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68300. var parsedSound = parsedData.sounds[index];
  68301. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68302. if (!parsedSound.url)
  68303. parsedSound.url = parsedSound.name;
  68304. if (!loadedSounds[parsedSound.url]) {
  68305. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68306. loadedSounds[parsedSound.url] = loadedSound;
  68307. container.sounds.push(loadedSound);
  68308. }
  68309. else {
  68310. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68311. }
  68312. }
  68313. else {
  68314. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68315. }
  68316. }
  68317. }
  68318. loadedSounds = [];
  68319. });
  68320. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  68321. get: function () {
  68322. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68323. if (!compo) {
  68324. compo = new AudioSceneComponent(this);
  68325. this._addComponent(compo);
  68326. }
  68327. if (!this._mainSoundTrack) {
  68328. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  68329. }
  68330. return this._mainSoundTrack;
  68331. },
  68332. enumerable: true,
  68333. configurable: true
  68334. });
  68335. BABYLON.Scene.prototype.getSoundByName = function (name) {
  68336. var index;
  68337. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  68338. if (this.mainSoundTrack.soundCollection[index].name === name) {
  68339. return this.mainSoundTrack.soundCollection[index];
  68340. }
  68341. }
  68342. if (this.soundTracks) {
  68343. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  68344. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  68345. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  68346. return this.soundTracks[sdIndex].soundCollection[index];
  68347. }
  68348. }
  68349. }
  68350. }
  68351. return null;
  68352. };
  68353. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  68354. get: function () {
  68355. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68356. if (!compo) {
  68357. compo = new AudioSceneComponent(this);
  68358. this._addComponent(compo);
  68359. }
  68360. return compo.audioEnabled;
  68361. },
  68362. set: function (value) {
  68363. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68364. if (!compo) {
  68365. compo = new AudioSceneComponent(this);
  68366. this._addComponent(compo);
  68367. }
  68368. if (value) {
  68369. compo.enableAudio();
  68370. }
  68371. else {
  68372. compo.disableAudio();
  68373. }
  68374. },
  68375. enumerable: true,
  68376. configurable: true
  68377. });
  68378. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  68379. get: function () {
  68380. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68381. if (!compo) {
  68382. compo = new AudioSceneComponent(this);
  68383. this._addComponent(compo);
  68384. }
  68385. return compo.headphone;
  68386. },
  68387. set: function (value) {
  68388. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68389. if (!compo) {
  68390. compo = new AudioSceneComponent(this);
  68391. this._addComponent(compo);
  68392. }
  68393. if (value) {
  68394. compo.switchAudioModeForHeadphones();
  68395. }
  68396. else {
  68397. compo.switchAudioModeForNormalSpeakers();
  68398. }
  68399. },
  68400. enumerable: true,
  68401. configurable: true
  68402. });
  68403. /**
  68404. * Defines the sound scene component responsible to manage any sounds
  68405. * in a given scene.
  68406. */
  68407. var AudioSceneComponent = /** @class */ (function () {
  68408. /**
  68409. * Creates a new instance of the component for the given scene
  68410. * @param scene Defines the scene to register the component in
  68411. */
  68412. function AudioSceneComponent(scene) {
  68413. /**
  68414. * The component name helpfull to identify the component in the list of scene components.
  68415. */
  68416. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  68417. this._audioEnabled = true;
  68418. this._headphone = false;
  68419. this.scene = scene;
  68420. scene.soundTracks = new Array();
  68421. scene.sounds = new Array();
  68422. }
  68423. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  68424. /**
  68425. * Gets whether audio is enabled or not.
  68426. * Please use related enable/disable method to switch state.
  68427. */
  68428. get: function () {
  68429. return this._audioEnabled;
  68430. },
  68431. enumerable: true,
  68432. configurable: true
  68433. });
  68434. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  68435. /**
  68436. * Gets whether audio is outputing to headphone or not.
  68437. * Please use the according Switch methods to change output.
  68438. */
  68439. get: function () {
  68440. return this._headphone;
  68441. },
  68442. enumerable: true,
  68443. configurable: true
  68444. });
  68445. /**
  68446. * Registers the component in a given scene
  68447. */
  68448. AudioSceneComponent.prototype.register = function () {
  68449. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  68450. };
  68451. /**
  68452. * Rebuilds the elements related to this component in case of
  68453. * context lost for instance.
  68454. */
  68455. AudioSceneComponent.prototype.rebuild = function () {
  68456. // Nothing to do here. (Not rendering related)
  68457. };
  68458. /**
  68459. * Serializes the component data to the specified json object
  68460. * @param serializationObject The object to serialize to
  68461. */
  68462. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  68463. serializationObject.sounds = [];
  68464. if (this.scene.soundTracks) {
  68465. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  68466. var soundtrack = this.scene.soundTracks[index];
  68467. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  68468. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  68469. }
  68470. }
  68471. }
  68472. };
  68473. /**
  68474. * Adds all the element from the container to the scene
  68475. * @param container the container holding the elements
  68476. */
  68477. AudioSceneComponent.prototype.addFromContainer = function (container) {
  68478. var _this = this;
  68479. if (!container.sounds) {
  68480. return;
  68481. }
  68482. container.sounds.forEach(function (sound) {
  68483. sound.play();
  68484. sound.autoplay = true;
  68485. _this.scene.mainSoundTrack.AddSound(sound);
  68486. });
  68487. };
  68488. /**
  68489. * Removes all the elements in the container from the scene
  68490. * @param container contains the elements to remove
  68491. */
  68492. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  68493. var _this = this;
  68494. if (!container.sounds) {
  68495. return;
  68496. }
  68497. container.sounds.forEach(function (sound) {
  68498. sound.stop();
  68499. sound.autoplay = false;
  68500. _this.scene.mainSoundTrack.RemoveSound(sound);
  68501. });
  68502. };
  68503. /**
  68504. * Disposes the component and the associated ressources.
  68505. */
  68506. AudioSceneComponent.prototype.dispose = function () {
  68507. var scene = this.scene;
  68508. if (scene._mainSoundTrack) {
  68509. scene.mainSoundTrack.dispose();
  68510. }
  68511. if (scene.soundTracks) {
  68512. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  68513. scene.soundTracks[scIndex].dispose();
  68514. }
  68515. }
  68516. };
  68517. /**
  68518. * Disables audio in the associated scene.
  68519. */
  68520. AudioSceneComponent.prototype.disableAudio = function () {
  68521. var scene = this.scene;
  68522. this._audioEnabled = false;
  68523. var i;
  68524. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68525. scene.mainSoundTrack.soundCollection[i].pause();
  68526. }
  68527. if (scene.soundTracks) {
  68528. for (i = 0; i < scene.soundTracks.length; i++) {
  68529. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68530. scene.soundTracks[i].soundCollection[j].pause();
  68531. }
  68532. }
  68533. }
  68534. };
  68535. /**
  68536. * Enables audio in the associated scene.
  68537. */
  68538. AudioSceneComponent.prototype.enableAudio = function () {
  68539. var scene = this.scene;
  68540. this._audioEnabled = true;
  68541. var i;
  68542. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68543. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  68544. scene.mainSoundTrack.soundCollection[i].play();
  68545. }
  68546. }
  68547. if (scene.soundTracks) {
  68548. for (i = 0; i < scene.soundTracks.length; i++) {
  68549. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68550. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  68551. scene.soundTracks[i].soundCollection[j].play();
  68552. }
  68553. }
  68554. }
  68555. }
  68556. };
  68557. /**
  68558. * Switch audio to headphone output.
  68559. */
  68560. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  68561. var scene = this.scene;
  68562. this._headphone = true;
  68563. scene.mainSoundTrack.switchPanningModelToHRTF();
  68564. if (scene.soundTracks) {
  68565. for (var i = 0; i < scene.soundTracks.length; i++) {
  68566. scene.soundTracks[i].switchPanningModelToHRTF();
  68567. }
  68568. }
  68569. };
  68570. /**
  68571. * Switch audio to normal speakers.
  68572. */
  68573. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  68574. var scene = this.scene;
  68575. this._headphone = false;
  68576. scene.mainSoundTrack.switchPanningModelToEqualPower();
  68577. if (scene.soundTracks) {
  68578. for (var i = 0; i < scene.soundTracks.length; i++) {
  68579. scene.soundTracks[i].switchPanningModelToEqualPower();
  68580. }
  68581. }
  68582. };
  68583. AudioSceneComponent.prototype._afterRender = function () {
  68584. var scene = this.scene;
  68585. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  68586. return;
  68587. }
  68588. var listeningCamera;
  68589. var audioEngine = BABYLON.Engine.audioEngine;
  68590. if (scene.activeCameras.length > 0) {
  68591. listeningCamera = scene.activeCameras[0];
  68592. }
  68593. else {
  68594. listeningCamera = scene.activeCamera;
  68595. }
  68596. if (listeningCamera && audioEngine.audioContext) {
  68597. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  68598. // for VR cameras
  68599. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  68600. listeningCamera = listeningCamera.rigCameras[0];
  68601. }
  68602. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  68603. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  68604. cameraDirection.normalize();
  68605. // To avoid some errors on GearVR
  68606. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  68607. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  68608. }
  68609. var i;
  68610. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68611. var sound = scene.mainSoundTrack.soundCollection[i];
  68612. if (sound.useCustomAttenuation) {
  68613. sound.updateDistanceFromListener();
  68614. }
  68615. }
  68616. if (scene.soundTracks) {
  68617. for (i = 0; i < scene.soundTracks.length; i++) {
  68618. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68619. sound = scene.soundTracks[i].soundCollection[j];
  68620. if (sound.useCustomAttenuation) {
  68621. sound.updateDistanceFromListener();
  68622. }
  68623. }
  68624. }
  68625. }
  68626. }
  68627. };
  68628. return AudioSceneComponent;
  68629. }());
  68630. BABYLON.AudioSceneComponent = AudioSceneComponent;
  68631. })(BABYLON || (BABYLON = {}));
  68632. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  68633. var BABYLON;
  68634. (function (BABYLON) {
  68635. /**
  68636. * This defines an action helpful to play a defined sound on a triggered action.
  68637. */
  68638. var PlaySoundAction = /** @class */ (function (_super) {
  68639. __extends(PlaySoundAction, _super);
  68640. /**
  68641. * Instantiate the action
  68642. * @param triggerOptions defines the trigger options
  68643. * @param sound defines the sound to play
  68644. * @param condition defines the trigger related conditions
  68645. */
  68646. function PlaySoundAction(triggerOptions, sound, condition) {
  68647. var _this = _super.call(this, triggerOptions, condition) || this;
  68648. _this._sound = sound;
  68649. return _this;
  68650. }
  68651. /** @hidden */
  68652. PlaySoundAction.prototype._prepare = function () {
  68653. };
  68654. /**
  68655. * Execute the action and play the sound.
  68656. */
  68657. PlaySoundAction.prototype.execute = function () {
  68658. if (this._sound !== undefined)
  68659. this._sound.play();
  68660. };
  68661. /**
  68662. * Serializes the actions and its related information.
  68663. * @param parent defines the object to serialize in
  68664. * @returns the serialized object
  68665. */
  68666. PlaySoundAction.prototype.serialize = function (parent) {
  68667. return _super.prototype._serialize.call(this, {
  68668. name: "PlaySoundAction",
  68669. properties: [{ name: "sound", value: this._sound.name }]
  68670. }, parent);
  68671. };
  68672. return PlaySoundAction;
  68673. }(BABYLON.Action));
  68674. BABYLON.PlaySoundAction = PlaySoundAction;
  68675. /**
  68676. * This defines an action helpful to stop a defined sound on a triggered action.
  68677. */
  68678. var StopSoundAction = /** @class */ (function (_super) {
  68679. __extends(StopSoundAction, _super);
  68680. /**
  68681. * Instantiate the action
  68682. * @param triggerOptions defines the trigger options
  68683. * @param sound defines the sound to stop
  68684. * @param condition defines the trigger related conditions
  68685. */
  68686. function StopSoundAction(triggerOptions, sound, condition) {
  68687. var _this = _super.call(this, triggerOptions, condition) || this;
  68688. _this._sound = sound;
  68689. return _this;
  68690. }
  68691. /** @hidden */
  68692. StopSoundAction.prototype._prepare = function () {
  68693. };
  68694. /**
  68695. * Execute the action and stop the sound.
  68696. */
  68697. StopSoundAction.prototype.execute = function () {
  68698. if (this._sound !== undefined)
  68699. this._sound.stop();
  68700. };
  68701. /**
  68702. * Serializes the actions and its related information.
  68703. * @param parent defines the object to serialize in
  68704. * @returns the serialized object
  68705. */
  68706. StopSoundAction.prototype.serialize = function (parent) {
  68707. return _super.prototype._serialize.call(this, {
  68708. name: "StopSoundAction",
  68709. properties: [{ name: "sound", value: this._sound.name }]
  68710. }, parent);
  68711. };
  68712. return StopSoundAction;
  68713. }(BABYLON.Action));
  68714. BABYLON.StopSoundAction = StopSoundAction;
  68715. })(BABYLON || (BABYLON = {}));
  68716. //# sourceMappingURL=babylon.directAudioActions.js.map
  68717. var BABYLON;
  68718. (function (BABYLON) {
  68719. var CubeTexture = /** @class */ (function (_super) {
  68720. __extends(CubeTexture, _super);
  68721. /**
  68722. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  68723. * as prefiltered data.
  68724. * @param rootUrl defines the url of the texture or the root name of the six images
  68725. * @param scene defines the scene the texture is attached to
  68726. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  68727. * @param noMipmap defines if mipmaps should be created or not
  68728. * @param files defines the six files to load for the different faces
  68729. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  68730. * @param onError defines a callback triggered in case of error during load
  68731. * @param format defines the internal format to use for the texture once loaded
  68732. * @param prefiltered defines whether or not the texture is created from prefiltered data
  68733. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  68734. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  68735. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  68736. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  68737. * @return the cube texture
  68738. */
  68739. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  68740. if (extensions === void 0) { extensions = null; }
  68741. if (noMipmap === void 0) { noMipmap = false; }
  68742. if (files === void 0) { files = null; }
  68743. if (onLoad === void 0) { onLoad = null; }
  68744. if (onError === void 0) { onError = null; }
  68745. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68746. if (prefiltered === void 0) { prefiltered = false; }
  68747. if (forcedExtension === void 0) { forcedExtension = null; }
  68748. if (createPolynomials === void 0) { createPolynomials = false; }
  68749. if (lodScale === void 0) { lodScale = 0.8; }
  68750. if (lodOffset === void 0) { lodOffset = 0; }
  68751. var _this = _super.call(this, scene) || this;
  68752. /**
  68753. * Gets or sets the center of the bounding box associated with the cube texture
  68754. * It must define where the camera used to render the texture was set
  68755. */
  68756. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  68757. _this._rotationY = 0;
  68758. /** @hidden */
  68759. _this._prefiltered = false;
  68760. _this.name = rootUrl;
  68761. _this.url = rootUrl;
  68762. _this._noMipmap = noMipmap;
  68763. _this.hasAlpha = false;
  68764. _this._format = format;
  68765. _this.isCube = true;
  68766. _this._textureMatrix = BABYLON.Matrix.Identity();
  68767. _this._createPolynomials = createPolynomials;
  68768. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  68769. if (!rootUrl && !files) {
  68770. return _this;
  68771. }
  68772. var lastDot = rootUrl.lastIndexOf(".");
  68773. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  68774. var isDDS = (extension === ".dds");
  68775. var isEnv = (extension === ".env");
  68776. if (isEnv) {
  68777. _this.gammaSpace = false;
  68778. _this._prefiltered = false;
  68779. }
  68780. else {
  68781. _this._prefiltered = prefiltered;
  68782. if (prefiltered) {
  68783. _this.gammaSpace = false;
  68784. }
  68785. }
  68786. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  68787. if (!files) {
  68788. if (!isEnv && !isDDS && !extensions) {
  68789. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  68790. }
  68791. files = [];
  68792. if (extensions) {
  68793. for (var index = 0; index < extensions.length; index++) {
  68794. files.push(rootUrl + extensions[index]);
  68795. }
  68796. }
  68797. }
  68798. _this._files = files;
  68799. if (!_this._texture) {
  68800. if (!scene.useDelayedTextureLoading) {
  68801. if (prefiltered) {
  68802. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  68803. }
  68804. else {
  68805. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  68806. }
  68807. }
  68808. else {
  68809. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  68810. }
  68811. }
  68812. else if (onLoad) {
  68813. if (_this._texture.isReady) {
  68814. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  68815. }
  68816. else {
  68817. _this._texture.onLoadedObservable.add(onLoad);
  68818. }
  68819. }
  68820. return _this;
  68821. }
  68822. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  68823. get: function () {
  68824. return this._boundingBoxSize;
  68825. },
  68826. /**
  68827. * Gets or sets the size of the bounding box associated with the cube texture
  68828. * When defined, the cubemap will switch to local mode
  68829. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  68830. * @example https://www.babylonjs-playground.com/#RNASML
  68831. */
  68832. set: function (value) {
  68833. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  68834. return;
  68835. }
  68836. this._boundingBoxSize = value;
  68837. var scene = this.getScene();
  68838. if (scene) {
  68839. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  68840. }
  68841. },
  68842. enumerable: true,
  68843. configurable: true
  68844. });
  68845. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  68846. /**
  68847. * Gets texture matrix rotation angle around Y axis radians.
  68848. */
  68849. get: function () {
  68850. return this._rotationY;
  68851. },
  68852. /**
  68853. * Sets texture matrix rotation angle around Y axis in radians.
  68854. */
  68855. set: function (value) {
  68856. this._rotationY = value;
  68857. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  68858. },
  68859. enumerable: true,
  68860. configurable: true
  68861. });
  68862. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  68863. var rootUrlKey = "";
  68864. files.forEach(function (url) { return rootUrlKey += url; });
  68865. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  68866. };
  68867. /**
  68868. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  68869. * @param url defines the url of the prefiltered texture
  68870. * @param scene defines the scene the texture is attached to
  68871. * @param forcedExtension defines the extension of the file if different from the url
  68872. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  68873. * @return the prefiltered texture
  68874. */
  68875. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  68876. if (forcedExtension === void 0) { forcedExtension = null; }
  68877. if (createPolynomials === void 0) { createPolynomials = true; }
  68878. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  68879. };
  68880. // Methods
  68881. CubeTexture.prototype.delayLoad = function () {
  68882. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  68883. return;
  68884. }
  68885. var scene = this.getScene();
  68886. if (!scene) {
  68887. return;
  68888. }
  68889. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  68890. this._texture = this._getFromCache(this.url, this._noMipmap);
  68891. if (!this._texture) {
  68892. if (this._prefiltered) {
  68893. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  68894. }
  68895. else {
  68896. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  68897. }
  68898. }
  68899. };
  68900. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  68901. return this._textureMatrix;
  68902. };
  68903. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  68904. this._textureMatrix = value;
  68905. };
  68906. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  68907. var texture = BABYLON.SerializationHelper.Parse(function () {
  68908. var prefiltered = false;
  68909. if (parsedTexture.prefiltered) {
  68910. prefiltered = parsedTexture.prefiltered;
  68911. }
  68912. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  68913. }, parsedTexture, scene);
  68914. // Local Cubemaps
  68915. if (parsedTexture.boundingBoxPosition) {
  68916. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  68917. }
  68918. if (parsedTexture.boundingBoxSize) {
  68919. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  68920. }
  68921. // Animations
  68922. if (parsedTexture.animations) {
  68923. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  68924. var parsedAnimation = parsedTexture.animations[animationIndex];
  68925. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68926. }
  68927. }
  68928. return texture;
  68929. };
  68930. CubeTexture.prototype.clone = function () {
  68931. var _this = this;
  68932. return BABYLON.SerializationHelper.Clone(function () {
  68933. var scene = _this.getScene();
  68934. if (!scene) {
  68935. return _this;
  68936. }
  68937. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  68938. }, this);
  68939. };
  68940. __decorate([
  68941. BABYLON.serialize("rotationY")
  68942. ], CubeTexture.prototype, "rotationY", null);
  68943. return CubeTexture;
  68944. }(BABYLON.BaseTexture));
  68945. BABYLON.CubeTexture = CubeTexture;
  68946. })(BABYLON || (BABYLON = {}));
  68947. //# sourceMappingURL=babylon.cubeTexture.js.map
  68948. var BABYLON;
  68949. (function (BABYLON) {
  68950. /**
  68951. * Raw cube texture where the raw buffers are passed in
  68952. */
  68953. var RawCubeTexture = /** @class */ (function (_super) {
  68954. __extends(RawCubeTexture, _super);
  68955. /**
  68956. * Creates a cube texture where the raw buffers are passed in.
  68957. * @param scene defines the scene the texture is attached to
  68958. * @param data defines the array of data to use to create each face
  68959. * @param size defines the size of the textures
  68960. * @param format defines the format of the data
  68961. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  68962. * @param generateMipMaps defines if the engine should generate the mip levels
  68963. * @param invertY defines if data must be stored with Y axis inverted
  68964. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  68965. * @param compression defines the compression used (null by default)
  68966. */
  68967. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  68968. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68969. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68970. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68971. if (invertY === void 0) { invertY = false; }
  68972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68973. if (compression === void 0) { compression = null; }
  68974. var _this = _super.call(this, "", scene) || this;
  68975. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  68976. return _this;
  68977. }
  68978. /**
  68979. * Updates the raw cube texture.
  68980. * @param data defines the data to store
  68981. * @param format defines the data format
  68982. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  68983. * @param invertY defines if data must be stored with Y axis inverted
  68984. * @param compression defines the compression used (null by default)
  68985. * @param level defines which level of the texture to update
  68986. */
  68987. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  68988. if (compression === void 0) { compression = null; }
  68989. if (level === void 0) { level = 0; }
  68990. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  68991. };
  68992. /**
  68993. * Updates a raw cube texture with RGBD encoded data.
  68994. * @param data defines the array of data [mipmap][face] to use to create each face
  68995. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  68996. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  68997. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  68998. * @returns a promsie that resolves when the operation is complete
  68999. */
  69000. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69001. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69002. if (lodScale === void 0) { lodScale = 0.8; }
  69003. if (lodOffset === void 0) { lodOffset = 0; }
  69004. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69005. };
  69006. /**
  69007. * Clones the raw cube texture.
  69008. * @return a new cube texture
  69009. */
  69010. RawCubeTexture.prototype.clone = function () {
  69011. var _this = this;
  69012. return BABYLON.SerializationHelper.Clone(function () {
  69013. var scene = _this.getScene();
  69014. var internalTexture = _this._texture;
  69015. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69016. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69017. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69018. }
  69019. return texture;
  69020. }, this);
  69021. };
  69022. /** @hidden */
  69023. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69024. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69025. internalTexture._bufferViewArrayArray = data;
  69026. internalTexture._lodGenerationScale = lodScale;
  69027. internalTexture._lodGenerationOffset = lodOffset;
  69028. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69029. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69030. internalTexture.isReady = true;
  69031. });
  69032. };
  69033. return RawCubeTexture;
  69034. }(BABYLON.CubeTexture));
  69035. BABYLON.RawCubeTexture = RawCubeTexture;
  69036. })(BABYLON || (BABYLON = {}));
  69037. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69038. var BABYLON;
  69039. (function (BABYLON) {
  69040. var RenderTargetTexture = /** @class */ (function (_super) {
  69041. __extends(RenderTargetTexture, _super);
  69042. /**
  69043. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69044. * or used a shadow, depth texture...
  69045. * @param name The friendly name of the texture
  69046. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  69047. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69048. * @param generateMipMaps True if mip maps need to be generated after render.
  69049. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69050. * @param type The type of the buffer in the RTT (int, half float, float...)
  69051. * @param isCube True if a cube texture needs to be created
  69052. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69053. * @param generateDepthBuffer True to generate a depth buffer
  69054. * @param generateStencilBuffer True to generate a stencil buffer
  69055. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69056. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69057. */
  69058. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69059. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69060. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69061. if (isCube === void 0) { isCube = false; }
  69062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69063. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69064. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69065. if (isMulti === void 0) { isMulti = false; }
  69066. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69067. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69068. _this.isCube = isCube;
  69069. _this.renderParticles = true;
  69070. _this.renderSprites = false;
  69071. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69072. _this.ignoreCameraViewport = false;
  69073. // Events
  69074. /**
  69075. * An event triggered when the texture is unbind.
  69076. */
  69077. _this.onBeforeBindObservable = new BABYLON.Observable();
  69078. /**
  69079. * An event triggered when the texture is unbind.
  69080. */
  69081. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69082. /**
  69083. * An event triggered before rendering the texture
  69084. */
  69085. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69086. /**
  69087. * An event triggered after rendering the texture
  69088. */
  69089. _this.onAfterRenderObservable = new BABYLON.Observable();
  69090. /**
  69091. * An event triggered after the texture clear
  69092. */
  69093. _this.onClearObservable = new BABYLON.Observable();
  69094. _this._currentRefreshId = -1;
  69095. _this._refreshRate = 1;
  69096. _this._samples = 1;
  69097. /**
  69098. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  69099. * It must define where the camera used to render the texture is set
  69100. */
  69101. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69102. scene = _this.getScene();
  69103. if (!scene) {
  69104. return _this;
  69105. }
  69106. _this.renderList = new Array();
  69107. _this._engine = scene.getEngine();
  69108. _this.name = name;
  69109. _this.isRenderTarget = true;
  69110. _this._initialSizeParameter = size;
  69111. _this._processSizeParameter(size);
  69112. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  69113. });
  69114. _this._generateMipMaps = generateMipMaps ? true : false;
  69115. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  69116. // Rendering groups
  69117. _this._renderingManager = new BABYLON.RenderingManager(scene);
  69118. _this._renderingManager._useSceneAutoClearSetup = true;
  69119. if (isMulti) {
  69120. return _this;
  69121. }
  69122. _this._renderTargetOptions = {
  69123. generateMipMaps: generateMipMaps,
  69124. type: type,
  69125. format: format,
  69126. samplingMode: samplingMode,
  69127. generateDepthBuffer: generateDepthBuffer,
  69128. generateStencilBuffer: generateStencilBuffer
  69129. };
  69130. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  69131. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69132. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69133. }
  69134. if (isCube) {
  69135. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  69136. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  69137. _this._textureMatrix = BABYLON.Matrix.Identity();
  69138. }
  69139. else {
  69140. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  69141. }
  69142. return _this;
  69143. }
  69144. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  69145. get: function () {
  69146. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  69147. },
  69148. enumerable: true,
  69149. configurable: true
  69150. });
  69151. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  69152. get: function () {
  69153. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  69154. },
  69155. enumerable: true,
  69156. configurable: true
  69157. });
  69158. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  69159. get: function () {
  69160. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  69161. },
  69162. enumerable: true,
  69163. configurable: true
  69164. });
  69165. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  69166. /**
  69167. * Use this list to define the list of mesh you want to render.
  69168. */
  69169. get: function () {
  69170. return this._renderList;
  69171. },
  69172. set: function (value) {
  69173. this._renderList = value;
  69174. if (this._renderList) {
  69175. this._hookArray(this._renderList);
  69176. }
  69177. },
  69178. enumerable: true,
  69179. configurable: true
  69180. });
  69181. RenderTargetTexture.prototype._hookArray = function (array) {
  69182. var _this = this;
  69183. var oldPush = array.push;
  69184. array.push = function () {
  69185. var items = [];
  69186. for (var _i = 0; _i < arguments.length; _i++) {
  69187. items[_i] = arguments[_i];
  69188. }
  69189. var result = oldPush.apply(array, items);
  69190. _this.getScene().meshes.forEach(function (mesh) {
  69191. mesh._markSubMeshesAsLightDirty();
  69192. });
  69193. return result;
  69194. };
  69195. var oldSplice = array.splice;
  69196. array.splice = function (index, deleteCount) {
  69197. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69198. _this.getScene().meshes.forEach(function (mesh) {
  69199. mesh._markSubMeshesAsLightDirty();
  69200. });
  69201. return deleted;
  69202. };
  69203. };
  69204. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  69205. set: function (callback) {
  69206. if (this._onAfterUnbindObserver) {
  69207. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  69208. }
  69209. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  69210. },
  69211. enumerable: true,
  69212. configurable: true
  69213. });
  69214. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  69215. set: function (callback) {
  69216. if (this._onBeforeRenderObserver) {
  69217. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69218. }
  69219. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69220. },
  69221. enumerable: true,
  69222. configurable: true
  69223. });
  69224. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  69225. set: function (callback) {
  69226. if (this._onAfterRenderObserver) {
  69227. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69228. }
  69229. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69230. },
  69231. enumerable: true,
  69232. configurable: true
  69233. });
  69234. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  69235. set: function (callback) {
  69236. if (this._onClearObserver) {
  69237. this.onClearObservable.remove(this._onClearObserver);
  69238. }
  69239. this._onClearObserver = this.onClearObservable.add(callback);
  69240. },
  69241. enumerable: true,
  69242. configurable: true
  69243. });
  69244. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  69245. get: function () {
  69246. return this._renderTargetOptions;
  69247. },
  69248. enumerable: true,
  69249. configurable: true
  69250. });
  69251. RenderTargetTexture.prototype._onRatioRescale = function () {
  69252. if (this._sizeRatio) {
  69253. this.resize(this._initialSizeParameter);
  69254. }
  69255. };
  69256. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  69257. get: function () {
  69258. return this._boundingBoxSize;
  69259. },
  69260. /**
  69261. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  69262. * When defined, the cubemap will switch to local mode
  69263. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69264. * @example https://www.babylonjs-playground.com/#RNASML
  69265. */
  69266. set: function (value) {
  69267. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69268. return;
  69269. }
  69270. this._boundingBoxSize = value;
  69271. var scene = this.getScene();
  69272. if (scene) {
  69273. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69274. }
  69275. },
  69276. enumerable: true,
  69277. configurable: true
  69278. });
  69279. /**
  69280. * Creates a depth stencil texture.
  69281. * This is only available in WebGL 2 or with the depth texture extension available.
  69282. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  69283. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  69284. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  69285. */
  69286. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  69287. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  69288. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  69289. if (generateStencil === void 0) { generateStencil = false; }
  69290. if (!this.getScene()) {
  69291. return;
  69292. }
  69293. var engine = this.getScene().getEngine();
  69294. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  69295. bilinearFiltering: bilinearFiltering,
  69296. comparisonFunction: comparisonFunction,
  69297. generateStencil: generateStencil,
  69298. isCube: this.isCube
  69299. });
  69300. engine.setFrameBufferDepthStencilTexture(this);
  69301. };
  69302. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  69303. if (size.ratio) {
  69304. this._sizeRatio = size.ratio;
  69305. this._size = {
  69306. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  69307. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  69308. };
  69309. }
  69310. else {
  69311. this._size = size;
  69312. }
  69313. };
  69314. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  69315. get: function () {
  69316. return this._samples;
  69317. },
  69318. set: function (value) {
  69319. if (this._samples === value) {
  69320. return;
  69321. }
  69322. var scene = this.getScene();
  69323. if (!scene) {
  69324. return;
  69325. }
  69326. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  69327. },
  69328. enumerable: true,
  69329. configurable: true
  69330. });
  69331. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  69332. this._currentRefreshId = -1;
  69333. };
  69334. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  69335. get: function () {
  69336. return this._refreshRate;
  69337. },
  69338. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69339. set: function (value) {
  69340. this._refreshRate = value;
  69341. this.resetRefreshCounter();
  69342. },
  69343. enumerable: true,
  69344. configurable: true
  69345. });
  69346. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  69347. if (!this._postProcessManager) {
  69348. var scene = this.getScene();
  69349. if (!scene) {
  69350. return;
  69351. }
  69352. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  69353. this._postProcesses = new Array();
  69354. }
  69355. this._postProcesses.push(postProcess);
  69356. this._postProcesses[0].autoClear = false;
  69357. };
  69358. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  69359. if (!this._postProcesses) {
  69360. return;
  69361. }
  69362. if (dispose) {
  69363. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  69364. var postProcess = _a[_i];
  69365. postProcess.dispose();
  69366. }
  69367. }
  69368. this._postProcesses = [];
  69369. };
  69370. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  69371. if (!this._postProcesses) {
  69372. return;
  69373. }
  69374. var index = this._postProcesses.indexOf(postProcess);
  69375. if (index === -1) {
  69376. return;
  69377. }
  69378. this._postProcesses.splice(index, 1);
  69379. if (this._postProcesses.length > 0) {
  69380. this._postProcesses[0].autoClear = false;
  69381. }
  69382. };
  69383. /** @hidden */
  69384. RenderTargetTexture.prototype._shouldRender = function () {
  69385. if (this._currentRefreshId === -1) { // At least render once
  69386. this._currentRefreshId = 1;
  69387. return true;
  69388. }
  69389. if (this.refreshRate === this._currentRefreshId) {
  69390. this._currentRefreshId = 1;
  69391. return true;
  69392. }
  69393. this._currentRefreshId++;
  69394. return false;
  69395. };
  69396. RenderTargetTexture.prototype.getRenderSize = function () {
  69397. if (this._size.width) {
  69398. return this._size.width;
  69399. }
  69400. return this._size;
  69401. };
  69402. RenderTargetTexture.prototype.getRenderWidth = function () {
  69403. if (this._size.width) {
  69404. return this._size.width;
  69405. }
  69406. return this._size;
  69407. };
  69408. RenderTargetTexture.prototype.getRenderHeight = function () {
  69409. if (this._size.width) {
  69410. return this._size.height;
  69411. }
  69412. return this._size;
  69413. };
  69414. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  69415. get: function () {
  69416. return true;
  69417. },
  69418. enumerable: true,
  69419. configurable: true
  69420. });
  69421. RenderTargetTexture.prototype.scale = function (ratio) {
  69422. var newSize = this.getRenderSize() * ratio;
  69423. this.resize(newSize);
  69424. };
  69425. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  69426. if (this.isCube) {
  69427. return this._textureMatrix;
  69428. }
  69429. return _super.prototype.getReflectionTextureMatrix.call(this);
  69430. };
  69431. RenderTargetTexture.prototype.resize = function (size) {
  69432. this.releaseInternalTexture();
  69433. var scene = this.getScene();
  69434. if (!scene) {
  69435. return;
  69436. }
  69437. this._processSizeParameter(size);
  69438. if (this.isCube) {
  69439. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  69440. }
  69441. else {
  69442. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  69443. }
  69444. };
  69445. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  69446. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  69447. if (dumpForDebug === void 0) { dumpForDebug = false; }
  69448. var scene = this.getScene();
  69449. if (!scene) {
  69450. return;
  69451. }
  69452. var engine = scene.getEngine();
  69453. if (this.useCameraPostProcesses !== undefined) {
  69454. useCameraPostProcess = this.useCameraPostProcesses;
  69455. }
  69456. if (this._waitingRenderList) {
  69457. this.renderList = [];
  69458. for (var index = 0; index < this._waitingRenderList.length; index++) {
  69459. var id = this._waitingRenderList[index];
  69460. var mesh_1 = scene.getMeshByID(id);
  69461. if (mesh_1) {
  69462. this.renderList.push(mesh_1);
  69463. }
  69464. }
  69465. delete this._waitingRenderList;
  69466. }
  69467. // Is predicate defined?
  69468. if (this.renderListPredicate) {
  69469. if (this.renderList) {
  69470. this.renderList.splice(0); // Clear previous renderList
  69471. }
  69472. else {
  69473. this.renderList = [];
  69474. }
  69475. var scene = this.getScene();
  69476. if (!scene) {
  69477. return;
  69478. }
  69479. var sceneMeshes = scene.meshes;
  69480. for (var index = 0; index < sceneMeshes.length; index++) {
  69481. var mesh = sceneMeshes[index];
  69482. if (this.renderListPredicate(mesh)) {
  69483. this.renderList.push(mesh);
  69484. }
  69485. }
  69486. }
  69487. this.onBeforeBindObservable.notifyObservers(this);
  69488. // Set custom projection.
  69489. // Needs to be before binding to prevent changing the aspect ratio.
  69490. var camera;
  69491. if (this.activeCamera) {
  69492. camera = this.activeCamera;
  69493. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  69494. if (this.activeCamera !== scene.activeCamera) {
  69495. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  69496. }
  69497. }
  69498. else {
  69499. camera = scene.activeCamera;
  69500. if (camera) {
  69501. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  69502. }
  69503. }
  69504. // Prepare renderingManager
  69505. this._renderingManager.reset();
  69506. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  69507. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  69508. var sceneRenderId = scene.getRenderId();
  69509. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  69510. var mesh = currentRenderList[meshIndex];
  69511. if (mesh) {
  69512. if (!mesh.isReady(this.refreshRate === 0)) {
  69513. this.resetRefreshCounter();
  69514. continue;
  69515. }
  69516. mesh._preActivateForIntermediateRendering(sceneRenderId);
  69517. var isMasked = void 0;
  69518. if (!this.renderList && camera) {
  69519. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  69520. }
  69521. else {
  69522. isMasked = false;
  69523. }
  69524. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  69525. mesh._activate(sceneRenderId);
  69526. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  69527. var subMesh = mesh.subMeshes[subIndex];
  69528. scene._activeIndices.addCount(subMesh.indexCount, false);
  69529. this._renderingManager.dispatch(subMesh, mesh);
  69530. }
  69531. }
  69532. }
  69533. }
  69534. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  69535. var particleSystem = scene.particleSystems[particleIndex];
  69536. var emitter = particleSystem.emitter;
  69537. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  69538. continue;
  69539. }
  69540. if (currentRenderList.indexOf(emitter) >= 0) {
  69541. this._renderingManager.dispatchParticles(particleSystem);
  69542. }
  69543. }
  69544. if (this.isCube) {
  69545. for (var face = 0; face < 6; face++) {
  69546. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  69547. scene.incrementRenderId();
  69548. scene.resetCachedMaterial();
  69549. }
  69550. }
  69551. else {
  69552. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  69553. }
  69554. this.onAfterUnbindObservable.notifyObservers(this);
  69555. if (scene.activeCamera) {
  69556. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  69557. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  69558. }
  69559. engine.setViewport(scene.activeCamera.viewport);
  69560. }
  69561. scene.resetCachedMaterial();
  69562. };
  69563. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  69564. var minimum = 128;
  69565. var x = renderDimension * scale;
  69566. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  69567. // Ensure we don't exceed the render dimension (while staying POT)
  69568. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  69569. };
  69570. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  69571. var _this = this;
  69572. if (!this._texture) {
  69573. return;
  69574. }
  69575. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  69576. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  69577. });
  69578. };
  69579. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  69580. var scene = this.getScene();
  69581. if (!scene) {
  69582. return;
  69583. }
  69584. var engine = scene.getEngine();
  69585. if (!this._texture) {
  69586. return;
  69587. }
  69588. // Bind
  69589. if (this._postProcessManager) {
  69590. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  69591. }
  69592. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  69593. if (this._texture) {
  69594. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  69595. }
  69596. }
  69597. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  69598. // Clear
  69599. if (this.onClearObservable.hasObservers()) {
  69600. this.onClearObservable.notifyObservers(engine);
  69601. }
  69602. else {
  69603. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  69604. }
  69605. if (!this._doNotChangeAspectRatio) {
  69606. scene.updateTransformMatrix(true);
  69607. }
  69608. // Render
  69609. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  69610. if (this._postProcessManager) {
  69611. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  69612. }
  69613. else if (useCameraPostProcess) {
  69614. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  69615. }
  69616. if (!this._doNotChangeAspectRatio) {
  69617. scene.updateTransformMatrix(true);
  69618. }
  69619. // Dump ?
  69620. if (dumpForDebug) {
  69621. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  69622. }
  69623. // Unbind
  69624. if (!this.isCube || faceIndex === 5) {
  69625. if (this.isCube) {
  69626. if (faceIndex === 5) {
  69627. engine.generateMipMapsForCubemap(this._texture);
  69628. }
  69629. }
  69630. this.unbindFrameBuffer(engine, faceIndex);
  69631. }
  69632. else {
  69633. this.onAfterRenderObservable.notifyObservers(faceIndex);
  69634. }
  69635. };
  69636. /**
  69637. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  69638. * This allowed control for front to back rendering or reversly depending of the special needs.
  69639. *
  69640. * @param renderingGroupId The rendering group id corresponding to its index
  69641. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  69642. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  69643. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  69644. */
  69645. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  69646. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  69647. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  69648. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  69649. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  69650. };
  69651. /**
  69652. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  69653. *
  69654. * @param renderingGroupId The rendering group id corresponding to its index
  69655. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  69656. */
  69657. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  69658. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  69659. this._renderingManager._useSceneAutoClearSetup = false;
  69660. };
  69661. RenderTargetTexture.prototype.clone = function () {
  69662. var textureSize = this.getSize();
  69663. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  69664. // Base texture
  69665. newTexture.hasAlpha = this.hasAlpha;
  69666. newTexture.level = this.level;
  69667. // RenderTarget Texture
  69668. newTexture.coordinatesMode = this.coordinatesMode;
  69669. if (this.renderList) {
  69670. newTexture.renderList = this.renderList.slice(0);
  69671. }
  69672. return newTexture;
  69673. };
  69674. RenderTargetTexture.prototype.serialize = function () {
  69675. if (!this.name) {
  69676. return null;
  69677. }
  69678. var serializationObject = _super.prototype.serialize.call(this);
  69679. serializationObject.renderTargetSize = this.getRenderSize();
  69680. serializationObject.renderList = [];
  69681. if (this.renderList) {
  69682. for (var index = 0; index < this.renderList.length; index++) {
  69683. serializationObject.renderList.push(this.renderList[index].id);
  69684. }
  69685. }
  69686. return serializationObject;
  69687. };
  69688. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  69689. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  69690. var objBuffer = this.getInternalTexture();
  69691. var scene = this.getScene();
  69692. if (objBuffer && scene) {
  69693. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  69694. }
  69695. };
  69696. RenderTargetTexture.prototype.dispose = function () {
  69697. if (this._postProcessManager) {
  69698. this._postProcessManager.dispose();
  69699. this._postProcessManager = null;
  69700. }
  69701. this.clearPostProcesses(true);
  69702. if (this._resizeObserver) {
  69703. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  69704. this._resizeObserver = null;
  69705. }
  69706. this.renderList = null;
  69707. // Remove from custom render targets
  69708. var scene = this.getScene();
  69709. if (!scene) {
  69710. return;
  69711. }
  69712. var index = scene.customRenderTargets.indexOf(this);
  69713. if (index >= 0) {
  69714. scene.customRenderTargets.splice(index, 1);
  69715. }
  69716. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  69717. var camera = _a[_i];
  69718. index = camera.customRenderTargets.indexOf(this);
  69719. if (index >= 0) {
  69720. camera.customRenderTargets.splice(index, 1);
  69721. }
  69722. }
  69723. _super.prototype.dispose.call(this);
  69724. };
  69725. /** @hidden */
  69726. RenderTargetTexture.prototype._rebuild = function () {
  69727. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69728. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69729. }
  69730. if (this._postProcessManager) {
  69731. this._postProcessManager._rebuild();
  69732. }
  69733. };
  69734. /**
  69735. * Clear the info related to rendering groups preventing retention point in material dispose.
  69736. */
  69737. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  69738. if (this._renderingManager) {
  69739. this._renderingManager.freeRenderingGroups();
  69740. }
  69741. };
  69742. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  69743. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  69744. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  69745. return RenderTargetTexture;
  69746. }(BABYLON.Texture));
  69747. BABYLON.RenderTargetTexture = RenderTargetTexture;
  69748. })(BABYLON || (BABYLON = {}));
  69749. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  69750. var BABYLON;
  69751. (function (BABYLON) {
  69752. ;
  69753. var MultiRenderTarget = /** @class */ (function (_super) {
  69754. __extends(MultiRenderTarget, _super);
  69755. function MultiRenderTarget(name, size, count, scene, options) {
  69756. var _this = this;
  69757. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  69758. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  69759. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  69760. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  69761. _this._engine = scene.getEngine();
  69762. if (!_this.isSupported) {
  69763. _this.dispose();
  69764. return;
  69765. }
  69766. var types = [];
  69767. var samplingModes = [];
  69768. for (var i = 0; i < count; i++) {
  69769. if (options && options.types && options.types[i] !== undefined) {
  69770. types.push(options.types[i]);
  69771. }
  69772. else {
  69773. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69774. }
  69775. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  69776. samplingModes.push(options.samplingModes[i]);
  69777. }
  69778. else {
  69779. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69780. }
  69781. }
  69782. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  69783. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  69784. _this._size = size;
  69785. _this._multiRenderTargetOptions = {
  69786. samplingModes: samplingModes,
  69787. generateMipMaps: generateMipMaps,
  69788. generateDepthBuffer: generateDepthBuffer,
  69789. generateStencilBuffer: generateStencilBuffer,
  69790. generateDepthTexture: generateDepthTexture,
  69791. types: types,
  69792. textureCount: count
  69793. };
  69794. _this._createInternalTextures();
  69795. _this._createTextures();
  69796. return _this;
  69797. }
  69798. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  69799. get: function () {
  69800. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  69801. },
  69802. enumerable: true,
  69803. configurable: true
  69804. });
  69805. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  69806. get: function () {
  69807. return this._textures;
  69808. },
  69809. enumerable: true,
  69810. configurable: true
  69811. });
  69812. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  69813. get: function () {
  69814. return this._textures[this._textures.length - 1];
  69815. },
  69816. enumerable: true,
  69817. configurable: true
  69818. });
  69819. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  69820. set: function (wrap) {
  69821. if (this._textures) {
  69822. for (var i = 0; i < this._textures.length; i++) {
  69823. this._textures[i].wrapU = wrap;
  69824. }
  69825. }
  69826. },
  69827. enumerable: true,
  69828. configurable: true
  69829. });
  69830. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  69831. set: function (wrap) {
  69832. if (this._textures) {
  69833. for (var i = 0; i < this._textures.length; i++) {
  69834. this._textures[i].wrapV = wrap;
  69835. }
  69836. }
  69837. },
  69838. enumerable: true,
  69839. configurable: true
  69840. });
  69841. /** @hidden */
  69842. MultiRenderTarget.prototype._rebuild = function () {
  69843. this.releaseInternalTextures();
  69844. this._createInternalTextures();
  69845. for (var i = 0; i < this._internalTextures.length; i++) {
  69846. var texture = this._textures[i];
  69847. texture._texture = this._internalTextures[i];
  69848. }
  69849. // Keeps references to frame buffer and stencil/depth buffer
  69850. this._texture = this._internalTextures[0];
  69851. };
  69852. MultiRenderTarget.prototype._createInternalTextures = function () {
  69853. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  69854. };
  69855. MultiRenderTarget.prototype._createTextures = function () {
  69856. this._textures = [];
  69857. for (var i = 0; i < this._internalTextures.length; i++) {
  69858. var texture = new BABYLON.Texture(null, this.getScene());
  69859. texture._texture = this._internalTextures[i];
  69860. this._textures.push(texture);
  69861. }
  69862. // Keeps references to frame buffer and stencil/depth buffer
  69863. this._texture = this._internalTextures[0];
  69864. };
  69865. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  69866. get: function () {
  69867. return this._samples;
  69868. },
  69869. set: function (value) {
  69870. if (this._samples === value) {
  69871. return;
  69872. }
  69873. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  69874. },
  69875. enumerable: true,
  69876. configurable: true
  69877. });
  69878. MultiRenderTarget.prototype.resize = function (size) {
  69879. this.releaseInternalTextures();
  69880. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  69881. this._createInternalTextures();
  69882. };
  69883. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  69884. var _this = this;
  69885. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  69886. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  69887. });
  69888. };
  69889. MultiRenderTarget.prototype.dispose = function () {
  69890. this.releaseInternalTextures();
  69891. _super.prototype.dispose.call(this);
  69892. };
  69893. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  69894. if (!this._internalTextures) {
  69895. return;
  69896. }
  69897. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  69898. if (this._internalTextures[i] !== undefined) {
  69899. this._internalTextures[i].dispose();
  69900. this._internalTextures.splice(i, 1);
  69901. }
  69902. }
  69903. };
  69904. return MultiRenderTarget;
  69905. }(BABYLON.RenderTargetTexture));
  69906. BABYLON.MultiRenderTarget = MultiRenderTarget;
  69907. })(BABYLON || (BABYLON = {}));
  69908. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  69909. var BABYLON;
  69910. (function (BABYLON) {
  69911. var MirrorTexture = /** @class */ (function (_super) {
  69912. __extends(MirrorTexture, _super);
  69913. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  69914. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69916. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69917. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  69918. _this.scene = scene;
  69919. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  69920. _this._transformMatrix = BABYLON.Matrix.Zero();
  69921. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  69922. _this._adaptiveBlurKernel = 0;
  69923. _this._blurKernelX = 0;
  69924. _this._blurKernelY = 0;
  69925. _this._blurRatio = 1.0;
  69926. _this.ignoreCameraViewport = true;
  69927. _this._updateGammaSpace();
  69928. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  69929. _this._updateGammaSpace;
  69930. });
  69931. _this.onBeforeRenderObservable.add(function () {
  69932. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  69933. _this._savedViewMatrix = scene.getViewMatrix();
  69934. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  69935. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  69936. scene.clipPlane = _this.mirrorPlane;
  69937. scene.getEngine().cullBackFaces = false;
  69938. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  69939. });
  69940. _this.onAfterRenderObservable.add(function () {
  69941. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  69942. scene.getEngine().cullBackFaces = true;
  69943. scene._mirroredCameraPosition = null;
  69944. delete scene.clipPlane;
  69945. });
  69946. return _this;
  69947. }
  69948. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  69949. get: function () {
  69950. return this._blurRatio;
  69951. },
  69952. set: function (value) {
  69953. if (this._blurRatio === value) {
  69954. return;
  69955. }
  69956. this._blurRatio = value;
  69957. this._preparePostProcesses();
  69958. },
  69959. enumerable: true,
  69960. configurable: true
  69961. });
  69962. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  69963. set: function (value) {
  69964. this._adaptiveBlurKernel = value;
  69965. this._autoComputeBlurKernel();
  69966. },
  69967. enumerable: true,
  69968. configurable: true
  69969. });
  69970. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  69971. set: function (value) {
  69972. this.blurKernelX = value;
  69973. this.blurKernelY = value;
  69974. },
  69975. enumerable: true,
  69976. configurable: true
  69977. });
  69978. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  69979. get: function () {
  69980. return this._blurKernelX;
  69981. },
  69982. set: function (value) {
  69983. if (this._blurKernelX === value) {
  69984. return;
  69985. }
  69986. this._blurKernelX = value;
  69987. this._preparePostProcesses();
  69988. },
  69989. enumerable: true,
  69990. configurable: true
  69991. });
  69992. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  69993. get: function () {
  69994. return this._blurKernelY;
  69995. },
  69996. set: function (value) {
  69997. if (this._blurKernelY === value) {
  69998. return;
  69999. }
  70000. this._blurKernelY = value;
  70001. this._preparePostProcesses();
  70002. },
  70003. enumerable: true,
  70004. configurable: true
  70005. });
  70006. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70007. var engine = this.getScene().getEngine();
  70008. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70009. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70010. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70011. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70012. };
  70013. MirrorTexture.prototype._onRatioRescale = function () {
  70014. if (this._sizeRatio) {
  70015. this.resize(this._initialSizeParameter);
  70016. if (!this._adaptiveBlurKernel) {
  70017. this._preparePostProcesses();
  70018. }
  70019. }
  70020. if (this._adaptiveBlurKernel) {
  70021. this._autoComputeBlurKernel();
  70022. }
  70023. };
  70024. MirrorTexture.prototype._updateGammaSpace = function () {
  70025. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70026. };
  70027. MirrorTexture.prototype._preparePostProcesses = function () {
  70028. this.clearPostProcesses(true);
  70029. if (this._blurKernelX && this._blurKernelY) {
  70030. var engine = this.getScene().getEngine();
  70031. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70032. 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);
  70033. this._blurX.autoClear = false;
  70034. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70035. this._blurX.inputTexture = this._texture;
  70036. }
  70037. else {
  70038. this._blurX.alwaysForcePOT = true;
  70039. }
  70040. 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);
  70041. this._blurY.autoClear = false;
  70042. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70043. this.addPostProcess(this._blurX);
  70044. this.addPostProcess(this._blurY);
  70045. }
  70046. else {
  70047. if (this._blurY) {
  70048. this.removePostProcess(this._blurY);
  70049. this._blurY.dispose();
  70050. this._blurY = null;
  70051. }
  70052. if (this._blurX) {
  70053. this.removePostProcess(this._blurX);
  70054. this._blurX.dispose();
  70055. this._blurX = null;
  70056. }
  70057. }
  70058. };
  70059. MirrorTexture.prototype.clone = function () {
  70060. var scene = this.getScene();
  70061. if (!scene) {
  70062. return this;
  70063. }
  70064. var textureSize = this.getSize();
  70065. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70066. // Base texture
  70067. newTexture.hasAlpha = this.hasAlpha;
  70068. newTexture.level = this.level;
  70069. // Mirror Texture
  70070. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70071. if (this.renderList) {
  70072. newTexture.renderList = this.renderList.slice(0);
  70073. }
  70074. return newTexture;
  70075. };
  70076. MirrorTexture.prototype.serialize = function () {
  70077. if (!this.name) {
  70078. return null;
  70079. }
  70080. var serializationObject = _super.prototype.serialize.call(this);
  70081. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70082. return serializationObject;
  70083. };
  70084. MirrorTexture.prototype.dispose = function () {
  70085. _super.prototype.dispose.call(this);
  70086. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70087. };
  70088. return MirrorTexture;
  70089. }(BABYLON.RenderTargetTexture));
  70090. BABYLON.MirrorTexture = MirrorTexture;
  70091. })(BABYLON || (BABYLON = {}));
  70092. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70093. var BABYLON;
  70094. (function (BABYLON) {
  70095. /**
  70096. * Creates a refraction texture used by refraction channel of the standard material.
  70097. * @param name the texture name
  70098. * @param size size of the underlying texture
  70099. * @param scene root scene
  70100. */
  70101. var RefractionTexture = /** @class */ (function (_super) {
  70102. __extends(RefractionTexture, _super);
  70103. function RefractionTexture(name, size, scene, generateMipMaps) {
  70104. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  70105. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  70106. _this.depth = 2.0;
  70107. _this.onBeforeRenderObservable.add(function () {
  70108. scene.clipPlane = _this.refractionPlane;
  70109. });
  70110. _this.onAfterRenderObservable.add(function () {
  70111. delete scene.clipPlane;
  70112. });
  70113. return _this;
  70114. }
  70115. RefractionTexture.prototype.clone = function () {
  70116. var scene = this.getScene();
  70117. if (!scene) {
  70118. return this;
  70119. }
  70120. var textureSize = this.getSize();
  70121. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  70122. // Base texture
  70123. newTexture.hasAlpha = this.hasAlpha;
  70124. newTexture.level = this.level;
  70125. // Refraction Texture
  70126. newTexture.refractionPlane = this.refractionPlane.clone();
  70127. if (this.renderList) {
  70128. newTexture.renderList = this.renderList.slice(0);
  70129. }
  70130. newTexture.depth = this.depth;
  70131. return newTexture;
  70132. };
  70133. RefractionTexture.prototype.serialize = function () {
  70134. if (!this.name) {
  70135. return null;
  70136. }
  70137. var serializationObject = _super.prototype.serialize.call(this);
  70138. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  70139. serializationObject.depth = this.depth;
  70140. return serializationObject;
  70141. };
  70142. return RefractionTexture;
  70143. }(BABYLON.RenderTargetTexture));
  70144. BABYLON.RefractionTexture = RefractionTexture;
  70145. })(BABYLON || (BABYLON = {}));
  70146. //# sourceMappingURL=babylon.refractionTexture.js.map
  70147. var BABYLON;
  70148. (function (BABYLON) {
  70149. /**
  70150. * A class extending {BABYLON.Texture} allowing drawing on a texture
  70151. * @see http://doc.babylonjs.com/how_to/dynamictexture
  70152. */
  70153. var DynamicTexture = /** @class */ (function (_super) {
  70154. __extends(DynamicTexture, _super);
  70155. /**
  70156. * Creates a {BABYLON.DynamicTexture}
  70157. * @param name defines the name of the texture
  70158. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  70159. * @param scene defines the scene where you want the texture
  70160. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  70161. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  70162. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  70163. */
  70164. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  70165. if (scene === void 0) { scene = null; }
  70166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70167. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70168. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  70169. _this.name = name;
  70170. _this._engine = _this.getScene().getEngine();
  70171. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70172. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70173. _this._generateMipMaps = generateMipMaps;
  70174. if (options.getContext) {
  70175. _this._canvas = options;
  70176. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70177. }
  70178. else {
  70179. _this._canvas = document.createElement("canvas");
  70180. if (options.width || options.width === 0) {
  70181. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70182. }
  70183. else {
  70184. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  70185. }
  70186. }
  70187. var textureSize = _this.getSize();
  70188. _this._canvas.width = textureSize.width;
  70189. _this._canvas.height = textureSize.height;
  70190. _this._context = _this._canvas.getContext("2d");
  70191. return _this;
  70192. }
  70193. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  70194. /**
  70195. * Gets the current state of canRescale
  70196. */
  70197. get: function () {
  70198. return true;
  70199. },
  70200. enumerable: true,
  70201. configurable: true
  70202. });
  70203. DynamicTexture.prototype._recreate = function (textureSize) {
  70204. this._canvas.width = textureSize.width;
  70205. this._canvas.height = textureSize.height;
  70206. this.releaseInternalTexture();
  70207. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  70208. };
  70209. /**
  70210. * Scales the texture
  70211. * @param ratio the scale factor to apply to both width and height
  70212. */
  70213. DynamicTexture.prototype.scale = function (ratio) {
  70214. var textureSize = this.getSize();
  70215. textureSize.width *= ratio;
  70216. textureSize.height *= ratio;
  70217. this._recreate(textureSize);
  70218. };
  70219. /**
  70220. * Resizes the texture
  70221. * @param width the new width
  70222. * @param height the new height
  70223. */
  70224. DynamicTexture.prototype.scaleTo = function (width, height) {
  70225. var textureSize = this.getSize();
  70226. textureSize.width = width;
  70227. textureSize.height = height;
  70228. this._recreate(textureSize);
  70229. };
  70230. /**
  70231. * Gets the context of the canvas used by the texture
  70232. * @returns the canvas context of the dynamic texture
  70233. */
  70234. DynamicTexture.prototype.getContext = function () {
  70235. return this._context;
  70236. };
  70237. /**
  70238. * Clears the texture
  70239. */
  70240. DynamicTexture.prototype.clear = function () {
  70241. var size = this.getSize();
  70242. this._context.fillRect(0, 0, size.width, size.height);
  70243. };
  70244. /**
  70245. * Updates the texture
  70246. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70247. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  70248. */
  70249. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  70250. if (premulAlpha === void 0) { premulAlpha = false; }
  70251. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  70252. };
  70253. /**
  70254. * Draws text onto the texture
  70255. * @param text defines the text to be drawn
  70256. * @param x defines the placement of the text from the left
  70257. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  70258. * @param font defines the font to be used with font-style, font-size, font-name
  70259. * @param color defines the color used for the text
  70260. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  70261. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70262. * @param update defines whether texture is immediately update (default is true)
  70263. */
  70264. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  70265. if (update === void 0) { update = true; }
  70266. var size = this.getSize();
  70267. if (clearColor) {
  70268. this._context.fillStyle = clearColor;
  70269. this._context.fillRect(0, 0, size.width, size.height);
  70270. }
  70271. this._context.font = font;
  70272. if (x === null || x === undefined) {
  70273. var textSize = this._context.measureText(text);
  70274. x = (size.width - textSize.width) / 2;
  70275. }
  70276. if (y === null || y === undefined) {
  70277. var fontSize = parseInt((font.replace(/\D/g, '')));
  70278. y = (size.height / 2) + (fontSize / 3.65);
  70279. }
  70280. this._context.fillStyle = color;
  70281. this._context.fillText(text, x, y);
  70282. if (update) {
  70283. this.update(invertY);
  70284. }
  70285. };
  70286. /**
  70287. * Clones the texture
  70288. * @returns the clone of the texture.
  70289. */
  70290. DynamicTexture.prototype.clone = function () {
  70291. var scene = this.getScene();
  70292. if (!scene) {
  70293. return this;
  70294. }
  70295. var textureSize = this.getSize();
  70296. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  70297. // Base texture
  70298. newTexture.hasAlpha = this.hasAlpha;
  70299. newTexture.level = this.level;
  70300. // Dynamic Texture
  70301. newTexture.wrapU = this.wrapU;
  70302. newTexture.wrapV = this.wrapV;
  70303. return newTexture;
  70304. };
  70305. /**
  70306. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  70307. * @returns a serialized dynamic texture object
  70308. */
  70309. DynamicTexture.prototype.serialize = function () {
  70310. var scene = this.getScene();
  70311. if (scene && !scene.isReady()) {
  70312. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  70313. }
  70314. var serializationObject = _super.prototype.serialize.call(this);
  70315. serializationObject.base64String = this._canvas.toDataURL();
  70316. serializationObject.invertY = this._invertY;
  70317. serializationObject.samplingMode = this.samplingMode;
  70318. return serializationObject;
  70319. };
  70320. /** @hidden */
  70321. DynamicTexture.prototype._rebuild = function () {
  70322. this.update();
  70323. };
  70324. return DynamicTexture;
  70325. }(BABYLON.Texture));
  70326. BABYLON.DynamicTexture = DynamicTexture;
  70327. })(BABYLON || (BABYLON = {}));
  70328. //# sourceMappingURL=babylon.dynamicTexture.js.map
  70329. var BABYLON;
  70330. (function (BABYLON) {
  70331. var VideoTexture = /** @class */ (function (_super) {
  70332. __extends(VideoTexture, _super);
  70333. /**
  70334. * Creates a video texture.
  70335. * Sample : https://doc.babylonjs.com/how_to/video_texture
  70336. * @param {string | null} name optional name, will detect from video source, if not defined
  70337. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  70338. * @param {BABYLON.Scene} scene is obviously the current scene.
  70339. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  70340. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  70341. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  70342. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  70343. */
  70344. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  70345. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70346. if (invertY === void 0) { invertY = false; }
  70347. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70348. if (settings === void 0) { settings = {
  70349. autoPlay: true,
  70350. loop: true,
  70351. autoUpdateTexture: true,
  70352. }; }
  70353. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70354. _this._onUserActionRequestedObservable = null;
  70355. _this._stillImageCaptured = false;
  70356. _this._poster = false;
  70357. _this._createInternalTexture = function () {
  70358. if (_this._texture != null) {
  70359. if (_this._poster) {
  70360. _this._texture.dispose();
  70361. _this._poster = false;
  70362. }
  70363. else {
  70364. return;
  70365. }
  70366. }
  70367. if (!_this._engine.needPOTTextures ||
  70368. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  70369. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  70370. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  70371. }
  70372. else {
  70373. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70374. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70375. _this._generateMipMaps = false;
  70376. }
  70377. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  70378. if (!_this.video.autoplay) {
  70379. var oldHandler_1 = _this.video.onplaying;
  70380. var error_1 = false;
  70381. _this.video.onplaying = function () {
  70382. _this.video.onplaying = oldHandler_1;
  70383. _this._texture.isReady = true;
  70384. _this._updateInternalTexture();
  70385. if (!error_1) {
  70386. _this.video.pause();
  70387. }
  70388. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70389. _this.onLoadObservable.notifyObservers(_this);
  70390. }
  70391. };
  70392. var playing = _this.video.play();
  70393. if (playing) {
  70394. playing.then(function () {
  70395. // Everything is good.
  70396. })
  70397. .catch(function () {
  70398. error_1 = true;
  70399. // On Chrome for instance, new policies might prevent playing without user interaction.
  70400. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  70401. _this._onUserActionRequestedObservable.notifyObservers(_this);
  70402. }
  70403. });
  70404. }
  70405. else {
  70406. _this.video.onplaying = oldHandler_1;
  70407. _this._texture.isReady = true;
  70408. _this._updateInternalTexture();
  70409. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70410. _this.onLoadObservable.notifyObservers(_this);
  70411. }
  70412. }
  70413. }
  70414. else {
  70415. _this._texture.isReady = true;
  70416. _this._updateInternalTexture();
  70417. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70418. _this.onLoadObservable.notifyObservers(_this);
  70419. }
  70420. }
  70421. };
  70422. _this.reset = function () {
  70423. if (_this._texture == null) {
  70424. return;
  70425. }
  70426. if (!_this._poster) {
  70427. _this._texture.dispose();
  70428. _this._texture = null;
  70429. }
  70430. };
  70431. _this._updateInternalTexture = function (e) {
  70432. if (_this._texture == null || !_this._texture.isReady) {
  70433. return;
  70434. }
  70435. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  70436. return;
  70437. }
  70438. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  70439. };
  70440. _this._engine = _this.getScene().getEngine();
  70441. _this._generateMipMaps = generateMipMaps;
  70442. _this._samplingMode = samplingMode;
  70443. _this.autoUpdateTexture = settings.autoUpdateTexture;
  70444. _this.name = name || _this._getName(src);
  70445. _this.video = _this._getVideo(src);
  70446. if (settings.poster) {
  70447. _this.video.poster = settings.poster;
  70448. }
  70449. if (settings.autoPlay !== undefined) {
  70450. _this.video.autoplay = settings.autoPlay;
  70451. }
  70452. if (settings.loop !== undefined) {
  70453. _this.video.loop = settings.loop;
  70454. }
  70455. _this.video.setAttribute("playsinline", "");
  70456. _this.video.addEventListener("canplay", _this._createInternalTexture);
  70457. _this.video.addEventListener("paused", _this._updateInternalTexture);
  70458. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  70459. _this.video.addEventListener("emptied", _this.reset);
  70460. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  70461. _this._createInternalTexture();
  70462. }
  70463. if (settings.poster) {
  70464. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  70465. _this._poster = true;
  70466. }
  70467. return _this;
  70468. }
  70469. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  70470. get: function () {
  70471. if (!this._onUserActionRequestedObservable) {
  70472. this._onUserActionRequestedObservable = new BABYLON.Observable();
  70473. }
  70474. return this._onUserActionRequestedObservable;
  70475. },
  70476. enumerable: true,
  70477. configurable: true
  70478. });
  70479. VideoTexture.prototype._getName = function (src) {
  70480. if (src instanceof HTMLVideoElement) {
  70481. return src.currentSrc;
  70482. }
  70483. if (typeof src === "object") {
  70484. return src.toString();
  70485. }
  70486. return src;
  70487. };
  70488. ;
  70489. VideoTexture.prototype._getVideo = function (src) {
  70490. if (src instanceof HTMLVideoElement) {
  70491. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  70492. return src;
  70493. }
  70494. var video = document.createElement("video");
  70495. if (typeof src === "string") {
  70496. BABYLON.Tools.SetCorsBehavior(src, video);
  70497. video.src = src;
  70498. }
  70499. else {
  70500. BABYLON.Tools.SetCorsBehavior(src[0], video);
  70501. src.forEach(function (url) {
  70502. var source = document.createElement("source");
  70503. source.src = url;
  70504. video.appendChild(source);
  70505. });
  70506. }
  70507. return video;
  70508. };
  70509. ;
  70510. /**
  70511. * @hidden Internal method to initiate `update`.
  70512. */
  70513. VideoTexture.prototype._rebuild = function () {
  70514. this.update();
  70515. };
  70516. /**
  70517. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  70518. */
  70519. VideoTexture.prototype.update = function () {
  70520. if (!this.autoUpdateTexture) {
  70521. // Expecting user to call `updateTexture` manually
  70522. return;
  70523. }
  70524. this.updateTexture(true);
  70525. };
  70526. /**
  70527. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  70528. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  70529. */
  70530. VideoTexture.prototype.updateTexture = function (isVisible) {
  70531. if (!isVisible) {
  70532. return;
  70533. }
  70534. if (this.video.paused && this._stillImageCaptured) {
  70535. return;
  70536. }
  70537. this._stillImageCaptured = true;
  70538. this._updateInternalTexture();
  70539. };
  70540. /**
  70541. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  70542. * @param url New url.
  70543. */
  70544. VideoTexture.prototype.updateURL = function (url) {
  70545. this.video.src = url;
  70546. };
  70547. VideoTexture.prototype.dispose = function () {
  70548. _super.prototype.dispose.call(this);
  70549. if (this._onUserActionRequestedObservable) {
  70550. this._onUserActionRequestedObservable.clear();
  70551. this._onUserActionRequestedObservable = null;
  70552. }
  70553. this.video.removeEventListener("canplay", this._createInternalTexture);
  70554. this.video.removeEventListener("paused", this._updateInternalTexture);
  70555. this.video.removeEventListener("seeked", this._updateInternalTexture);
  70556. this.video.removeEventListener("emptied", this.reset);
  70557. this.video.pause();
  70558. };
  70559. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  70560. var video = document.createElement("video");
  70561. video.setAttribute('autoplay', '');
  70562. video.setAttribute('muted', '');
  70563. video.setAttribute('playsinline', '');
  70564. var constraintsDeviceId;
  70565. if (constraints && constraints.deviceId) {
  70566. constraintsDeviceId = {
  70567. exact: constraints.deviceId,
  70568. };
  70569. }
  70570. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  70571. if (navigator.mediaDevices) {
  70572. navigator.mediaDevices.getUserMedia({ video: constraints })
  70573. .then(function (stream) {
  70574. if (video.mozSrcObject !== undefined) {
  70575. // hack for Firefox < 19
  70576. video.mozSrcObject = stream;
  70577. }
  70578. else {
  70579. video.srcObject = stream;
  70580. }
  70581. var onPlaying = function () {
  70582. if (onReady) {
  70583. onReady(new VideoTexture("video", video, scene, true, true));
  70584. }
  70585. video.removeEventListener("playing", onPlaying);
  70586. };
  70587. video.addEventListener("playing", onPlaying);
  70588. video.play();
  70589. })
  70590. .catch(function (err) {
  70591. BABYLON.Tools.Error(err.name);
  70592. });
  70593. }
  70594. else {
  70595. navigator.getUserMedia =
  70596. navigator.getUserMedia ||
  70597. navigator.webkitGetUserMedia ||
  70598. navigator.mozGetUserMedia ||
  70599. navigator.msGetUserMedia;
  70600. if (navigator.getUserMedia) {
  70601. navigator.getUserMedia({
  70602. video: {
  70603. deviceId: constraintsDeviceId,
  70604. width: {
  70605. min: (constraints && constraints.minWidth) || 256,
  70606. max: (constraints && constraints.maxWidth) || 640,
  70607. },
  70608. height: {
  70609. min: (constraints && constraints.minHeight) || 256,
  70610. max: (constraints && constraints.maxHeight) || 480,
  70611. },
  70612. },
  70613. }, function (stream) {
  70614. if (video.mozSrcObject !== undefined) {
  70615. // hack for Firefox < 19
  70616. video.mozSrcObject = stream;
  70617. }
  70618. else {
  70619. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  70620. }
  70621. video.play();
  70622. if (onReady) {
  70623. onReady(new VideoTexture("video", video, scene, true, true));
  70624. }
  70625. }, function (e) {
  70626. BABYLON.Tools.Error(e.name);
  70627. });
  70628. }
  70629. }
  70630. };
  70631. return VideoTexture;
  70632. }(BABYLON.Texture));
  70633. BABYLON.VideoTexture = VideoTexture;
  70634. })(BABYLON || (BABYLON = {}));
  70635. //# sourceMappingURL=babylon.videoTexture.js.map
  70636. var BABYLON;
  70637. (function (BABYLON) {
  70638. var RawTexture = /** @class */ (function (_super) {
  70639. __extends(RawTexture, _super);
  70640. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  70641. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70642. if (invertY === void 0) { invertY = false; }
  70643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70644. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70645. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70646. _this.format = format;
  70647. _this._engine = scene.getEngine();
  70648. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  70649. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70650. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70651. return _this;
  70652. }
  70653. RawTexture.prototype.update = function (data) {
  70654. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  70655. };
  70656. // Statics
  70657. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70658. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70659. if (invertY === void 0) { invertY = false; }
  70660. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70661. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  70662. };
  70663. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70664. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70665. if (invertY === void 0) { invertY = false; }
  70666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70667. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  70668. };
  70669. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70670. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70671. if (invertY === void 0) { invertY = false; }
  70672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70673. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  70674. };
  70675. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70676. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70677. if (invertY === void 0) { invertY = false; }
  70678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70679. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70680. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  70681. };
  70682. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70683. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70684. if (invertY === void 0) { invertY = false; }
  70685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70686. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70687. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  70688. };
  70689. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70690. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70691. if (invertY === void 0) { invertY = false; }
  70692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70693. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  70694. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  70695. };
  70696. return RawTexture;
  70697. }(BABYLON.Texture));
  70698. BABYLON.RawTexture = RawTexture;
  70699. })(BABYLON || (BABYLON = {}));
  70700. //# sourceMappingURL=babylon.rawTexture.js.map
  70701. var BABYLON;
  70702. (function (BABYLON) {
  70703. /**
  70704. * Class used to store 3D textures containing user data
  70705. */
  70706. var RawTexture3D = /** @class */ (function (_super) {
  70707. __extends(RawTexture3D, _super);
  70708. /**
  70709. * Create a new RawTexture3D
  70710. * @param data defines the data of the texture
  70711. * @param width defines the width of the texture
  70712. * @param height defines the height of the texture
  70713. * @param depth defines the depth of the texture
  70714. * @param format defines the texture format to use
  70715. * @param scene defines the hosting scene
  70716. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  70717. * @param invertY defines if texture must be stored with Y axis inverted
  70718. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  70719. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  70720. */
  70721. function RawTexture3D(data, width, height, depth,
  70722. /** Gets or sets the texture format to use */
  70723. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  70724. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70725. if (invertY === void 0) { invertY = false; }
  70726. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70727. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70728. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70729. _this.format = format;
  70730. _this._engine = scene.getEngine();
  70731. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  70732. _this.is3D = true;
  70733. return _this;
  70734. }
  70735. /**
  70736. * Update the texture with new data
  70737. * @param data defines the data to store in the texture
  70738. */
  70739. RawTexture3D.prototype.update = function (data) {
  70740. if (!this._texture) {
  70741. return;
  70742. }
  70743. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  70744. };
  70745. return RawTexture3D;
  70746. }(BABYLON.Texture));
  70747. BABYLON.RawTexture3D = RawTexture3D;
  70748. })(BABYLON || (BABYLON = {}));
  70749. //# sourceMappingURL=babylon.rawTexture3D.js.map
  70750. var BABYLON;
  70751. (function (BABYLON) {
  70752. /**
  70753. * PostProcessManager is used to manage one or more post processes or post process pipelines
  70754. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  70755. */
  70756. var PostProcessManager = /** @class */ (function () {
  70757. /**
  70758. * Creates a new instance PostProcess
  70759. * @param scene The scene that the post process is associated with.
  70760. */
  70761. function PostProcessManager(scene) {
  70762. this._vertexBuffers = {};
  70763. this._scene = scene;
  70764. }
  70765. PostProcessManager.prototype._prepareBuffers = function () {
  70766. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  70767. return;
  70768. }
  70769. // VBO
  70770. var vertices = [];
  70771. vertices.push(1, 1);
  70772. vertices.push(-1, 1);
  70773. vertices.push(-1, -1);
  70774. vertices.push(1, -1);
  70775. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70776. this._buildIndexBuffer();
  70777. };
  70778. PostProcessManager.prototype._buildIndexBuffer = function () {
  70779. // Indices
  70780. var indices = [];
  70781. indices.push(0);
  70782. indices.push(1);
  70783. indices.push(2);
  70784. indices.push(0);
  70785. indices.push(2);
  70786. indices.push(3);
  70787. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  70788. };
  70789. /**
  70790. * Rebuilds the vertex buffers of the manager.
  70791. * @hidden
  70792. */
  70793. PostProcessManager.prototype._rebuild = function () {
  70794. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70795. if (!vb) {
  70796. return;
  70797. }
  70798. vb._rebuild();
  70799. this._buildIndexBuffer();
  70800. };
  70801. // Methods
  70802. /**
  70803. * Prepares a frame to be run through a post process.
  70804. * @param sourceTexture The input texture to the post procesess. (default: null)
  70805. * @param postProcesses An array of post processes to be run. (default: null)
  70806. * @returns True if the post processes were able to be run.
  70807. * @hidden
  70808. */
  70809. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  70810. if (sourceTexture === void 0) { sourceTexture = null; }
  70811. if (postProcesses === void 0) { postProcesses = null; }
  70812. var camera = this._scene.activeCamera;
  70813. if (!camera) {
  70814. return false;
  70815. }
  70816. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  70817. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  70818. return false;
  70819. }
  70820. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  70821. return true;
  70822. };
  70823. /**
  70824. * Manually render a set of post processes to a texture.
  70825. * @param postProcesses An array of post processes to be run.
  70826. * @param targetTexture The target texture to render to.
  70827. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  70828. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  70829. * @param lodLevel defines which lod of the texture to render to
  70830. */
  70831. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  70832. if (targetTexture === void 0) { targetTexture = null; }
  70833. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  70834. if (faceIndex === void 0) { faceIndex = 0; }
  70835. if (lodLevel === void 0) { lodLevel = 0; }
  70836. var engine = this._scene.getEngine();
  70837. for (var index = 0; index < postProcesses.length; index++) {
  70838. if (index < postProcesses.length - 1) {
  70839. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  70840. }
  70841. else {
  70842. if (targetTexture) {
  70843. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  70844. }
  70845. else {
  70846. engine.restoreDefaultFramebuffer();
  70847. }
  70848. }
  70849. var pp = postProcesses[index];
  70850. var effect = pp.apply();
  70851. if (effect) {
  70852. pp.onBeforeRenderObservable.notifyObservers(effect);
  70853. // VBOs
  70854. this._prepareBuffers();
  70855. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  70856. // Draw order
  70857. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70858. pp.onAfterRenderObservable.notifyObservers(effect);
  70859. }
  70860. }
  70861. // Restore depth buffer
  70862. engine.setDepthBuffer(true);
  70863. engine.setDepthWrite(true);
  70864. };
  70865. /**
  70866. * Finalize the result of the output of the postprocesses.
  70867. * @param doNotPresent If true the result will not be displayed to the screen.
  70868. * @param targetTexture The target texture to render to.
  70869. * @param faceIndex The index of the face to bind the target texture to.
  70870. * @param postProcesses The array of post processes to render.
  70871. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  70872. * @hidden
  70873. */
  70874. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  70875. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  70876. var camera = this._scene.activeCamera;
  70877. if (!camera) {
  70878. return;
  70879. }
  70880. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  70881. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  70882. return;
  70883. }
  70884. var engine = this._scene.getEngine();
  70885. for (var index = 0, len = postProcesses.length; index < len; index++) {
  70886. var pp = postProcesses[index];
  70887. if (index < len - 1) {
  70888. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  70889. }
  70890. else {
  70891. if (targetTexture) {
  70892. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  70893. pp._outputTexture = targetTexture;
  70894. }
  70895. else {
  70896. engine.restoreDefaultFramebuffer();
  70897. pp._outputTexture = null;
  70898. }
  70899. }
  70900. if (doNotPresent) {
  70901. break;
  70902. }
  70903. var effect = pp.apply();
  70904. if (effect) {
  70905. pp.onBeforeRenderObservable.notifyObservers(effect);
  70906. // VBOs
  70907. this._prepareBuffers();
  70908. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  70909. // Draw order
  70910. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70911. pp.onAfterRenderObservable.notifyObservers(effect);
  70912. }
  70913. }
  70914. // Restore states
  70915. engine.setDepthBuffer(true);
  70916. engine.setDepthWrite(true);
  70917. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70918. };
  70919. /**
  70920. * Disposes of the post process manager.
  70921. */
  70922. PostProcessManager.prototype.dispose = function () {
  70923. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70924. if (buffer) {
  70925. buffer.dispose();
  70926. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70927. }
  70928. if (this._indexBuffer) {
  70929. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70930. this._indexBuffer = null;
  70931. }
  70932. };
  70933. return PostProcessManager;
  70934. }());
  70935. BABYLON.PostProcessManager = PostProcessManager;
  70936. })(BABYLON || (BABYLON = {}));
  70937. //# sourceMappingURL=babylon.postProcessManager.js.map
  70938. var BABYLON;
  70939. (function (BABYLON) {
  70940. /**
  70941. * PostProcess can be used to apply a shader to a texture after it has been rendered
  70942. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  70943. */
  70944. var PostProcess = /** @class */ (function () {
  70945. /**
  70946. * Creates a new instance PostProcess
  70947. * @param name The name of the PostProcess.
  70948. * @param fragmentUrl The url of the fragment shader to be used.
  70949. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  70950. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  70951. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70952. * @param camera The camera to apply the render pass to.
  70953. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70954. * @param engine The engine which the post process will be applied. (default: current engine)
  70955. * @param reusable If the post process can be reused on the same frame. (default: false)
  70956. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  70957. * @param textureType Type of textures used when performing the post process. (default: 0)
  70958. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  70959. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  70960. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  70961. */
  70962. function PostProcess(
  70963. /** Name of the PostProcess. */
  70964. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  70965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  70966. if (defines === void 0) { defines = null; }
  70967. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70968. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  70969. if (blockCompilation === void 0) { blockCompilation = false; }
  70970. this.name = name;
  70971. /**
  70972. * Width of the texture to apply the post process on
  70973. */
  70974. this.width = -1;
  70975. /**
  70976. * Height of the texture to apply the post process on
  70977. */
  70978. this.height = -1;
  70979. /**
  70980. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  70981. * @hidden
  70982. */
  70983. this._outputTexture = null;
  70984. /**
  70985. * If the buffer needs to be cleared before applying the post process. (default: true)
  70986. * Should be set to false if shader will overwrite all previous pixels.
  70987. */
  70988. this.autoClear = true;
  70989. /**
  70990. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  70991. */
  70992. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  70993. /**
  70994. * Animations to be used for the post processing
  70995. */
  70996. this.animations = new Array();
  70997. /**
  70998. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  70999. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71000. */
  71001. this.enablePixelPerfectMode = false;
  71002. /**
  71003. * Force the postprocess to be applied without taking in account viewport
  71004. */
  71005. this.forceFullscreenViewport = true;
  71006. /**
  71007. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71008. *
  71009. * | Value | Type | Description |
  71010. * | ----- | ----------------------------------- | ----------- |
  71011. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71012. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71013. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71014. *
  71015. */
  71016. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71017. /**
  71018. * Force textures to be a power of two (default: false)
  71019. */
  71020. this.alwaysForcePOT = false;
  71021. this._samples = 1;
  71022. /**
  71023. * Modify the scale of the post process to be the same as the viewport (default: false)
  71024. */
  71025. this.adaptScaleToCurrentViewport = false;
  71026. this._reusable = false;
  71027. /**
  71028. * Smart array of input and output textures for the post process.
  71029. * @hidden
  71030. */
  71031. this._textures = new BABYLON.SmartArray(2);
  71032. /**
  71033. * The index in _textures that corresponds to the output texture.
  71034. * @hidden
  71035. */
  71036. this._currentRenderTextureInd = 0;
  71037. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71038. this._texelSize = BABYLON.Vector2.Zero();
  71039. // Events
  71040. /**
  71041. * An event triggered when the postprocess is activated.
  71042. */
  71043. this.onActivateObservable = new BABYLON.Observable();
  71044. /**
  71045. * An event triggered when the postprocess changes its size.
  71046. */
  71047. this.onSizeChangedObservable = new BABYLON.Observable();
  71048. /**
  71049. * An event triggered when the postprocess applies its effect.
  71050. */
  71051. this.onApplyObservable = new BABYLON.Observable();
  71052. /**
  71053. * An event triggered before rendering the postprocess
  71054. */
  71055. this.onBeforeRenderObservable = new BABYLON.Observable();
  71056. /**
  71057. * An event triggered after rendering the postprocess
  71058. */
  71059. this.onAfterRenderObservable = new BABYLON.Observable();
  71060. if (camera != null) {
  71061. this._camera = camera;
  71062. this._scene = camera.getScene();
  71063. camera.attachPostProcess(this);
  71064. this._engine = this._scene.getEngine();
  71065. this._scene.postProcesses.push(this);
  71066. }
  71067. else if (engine) {
  71068. this._engine = engine;
  71069. this._engine.postProcesses.push(this);
  71070. }
  71071. this._options = options;
  71072. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71073. this._reusable = reusable || false;
  71074. this._textureType = textureType;
  71075. this._samplers = samplers || [];
  71076. this._samplers.push("textureSampler");
  71077. this._fragmentUrl = fragmentUrl;
  71078. this._vertexUrl = vertexUrl;
  71079. this._parameters = parameters || [];
  71080. this._parameters.push("scale");
  71081. this._indexParameters = indexParameters;
  71082. if (!blockCompilation) {
  71083. this.updateEffect(defines);
  71084. }
  71085. }
  71086. Object.defineProperty(PostProcess.prototype, "samples", {
  71087. /**
  71088. * Number of sample textures (default: 1)
  71089. */
  71090. get: function () {
  71091. return this._samples;
  71092. },
  71093. set: function (n) {
  71094. var _this = this;
  71095. this._samples = n;
  71096. this._textures.forEach(function (texture) {
  71097. if (texture.samples !== _this._samples) {
  71098. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  71099. }
  71100. });
  71101. },
  71102. enumerable: true,
  71103. configurable: true
  71104. });
  71105. Object.defineProperty(PostProcess.prototype, "onActivate", {
  71106. /**
  71107. * A function that is added to the onActivateObservable
  71108. */
  71109. set: function (callback) {
  71110. if (this._onActivateObserver) {
  71111. this.onActivateObservable.remove(this._onActivateObserver);
  71112. }
  71113. if (callback) {
  71114. this._onActivateObserver = this.onActivateObservable.add(callback);
  71115. }
  71116. },
  71117. enumerable: true,
  71118. configurable: true
  71119. });
  71120. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  71121. /**
  71122. * A function that is added to the onSizeChangedObservable
  71123. */
  71124. set: function (callback) {
  71125. if (this._onSizeChangedObserver) {
  71126. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  71127. }
  71128. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  71129. },
  71130. enumerable: true,
  71131. configurable: true
  71132. });
  71133. Object.defineProperty(PostProcess.prototype, "onApply", {
  71134. /**
  71135. * A function that is added to the onApplyObservable
  71136. */
  71137. set: function (callback) {
  71138. if (this._onApplyObserver) {
  71139. this.onApplyObservable.remove(this._onApplyObserver);
  71140. }
  71141. this._onApplyObserver = this.onApplyObservable.add(callback);
  71142. },
  71143. enumerable: true,
  71144. configurable: true
  71145. });
  71146. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  71147. /**
  71148. * A function that is added to the onBeforeRenderObservable
  71149. */
  71150. set: function (callback) {
  71151. if (this._onBeforeRenderObserver) {
  71152. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71153. }
  71154. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71155. },
  71156. enumerable: true,
  71157. configurable: true
  71158. });
  71159. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  71160. /**
  71161. * A function that is added to the onAfterRenderObservable
  71162. */
  71163. set: function (callback) {
  71164. if (this._onAfterRenderObserver) {
  71165. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71166. }
  71167. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71168. },
  71169. enumerable: true,
  71170. configurable: true
  71171. });
  71172. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  71173. /**
  71174. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  71175. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  71176. */
  71177. get: function () {
  71178. return this._textures.data[this._currentRenderTextureInd];
  71179. },
  71180. set: function (value) {
  71181. this._forcedOutputTexture = value;
  71182. },
  71183. enumerable: true,
  71184. configurable: true
  71185. });
  71186. /**
  71187. * Gets the camera which post process is applied to.
  71188. * @returns The camera the post process is applied to.
  71189. */
  71190. PostProcess.prototype.getCamera = function () {
  71191. return this._camera;
  71192. };
  71193. Object.defineProperty(PostProcess.prototype, "texelSize", {
  71194. /**
  71195. * Gets the texel size of the postprocess.
  71196. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  71197. */
  71198. get: function () {
  71199. if (this._shareOutputWithPostProcess) {
  71200. return this._shareOutputWithPostProcess.texelSize;
  71201. }
  71202. if (this._forcedOutputTexture) {
  71203. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  71204. }
  71205. return this._texelSize;
  71206. },
  71207. enumerable: true,
  71208. configurable: true
  71209. });
  71210. /**
  71211. * Gets the engine which this post process belongs to.
  71212. * @returns The engine the post process was enabled with.
  71213. */
  71214. PostProcess.prototype.getEngine = function () {
  71215. return this._engine;
  71216. };
  71217. /**
  71218. * The effect that is created when initializing the post process.
  71219. * @returns The created effect corrisponding the the postprocess.
  71220. */
  71221. PostProcess.prototype.getEffect = function () {
  71222. return this._effect;
  71223. };
  71224. /**
  71225. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  71226. * @param postProcess The post process to share the output with.
  71227. * @returns This post process.
  71228. */
  71229. PostProcess.prototype.shareOutputWith = function (postProcess) {
  71230. this._disposeTextures();
  71231. this._shareOutputWithPostProcess = postProcess;
  71232. return this;
  71233. };
  71234. /**
  71235. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  71236. * This should be called if the post process that shares output with this post process is disabled/disposed.
  71237. */
  71238. PostProcess.prototype.useOwnOutput = function () {
  71239. if (this._textures.length == 0) {
  71240. this._textures = new BABYLON.SmartArray(2);
  71241. }
  71242. this._shareOutputWithPostProcess = null;
  71243. };
  71244. /**
  71245. * Updates the effect with the current post process compile time values and recompiles the shader.
  71246. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71247. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71248. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71249. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  71250. * @param onCompiled Called when the shader has been compiled.
  71251. * @param onError Called if there is an error when compiling a shader.
  71252. */
  71253. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71254. if (defines === void 0) { defines = null; }
  71255. if (uniforms === void 0) { uniforms = null; }
  71256. if (samplers === void 0) { samplers = null; }
  71257. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", undefined, onCompiled, onError, indexParameters || this._indexParameters);
  71258. };
  71259. /**
  71260. * The post process is reusable if it can be used multiple times within one frame.
  71261. * @returns If the post process is reusable
  71262. */
  71263. PostProcess.prototype.isReusable = function () {
  71264. return this._reusable;
  71265. };
  71266. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  71267. PostProcess.prototype.markTextureDirty = function () {
  71268. this.width = -1;
  71269. };
  71270. /**
  71271. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  71272. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  71273. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  71274. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  71275. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  71276. * @returns The target texture that was bound to be written to.
  71277. */
  71278. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  71279. var _this = this;
  71280. if (sourceTexture === void 0) { sourceTexture = null; }
  71281. camera = camera || this._camera;
  71282. var scene = camera.getScene();
  71283. var engine = scene.getEngine();
  71284. var maxSize = engine.getCaps().maxTextureSize;
  71285. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  71286. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  71287. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  71288. var webVRCamera = camera.parent;
  71289. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  71290. requiredWidth /= 2;
  71291. }
  71292. var desiredWidth = (this._options.width || requiredWidth);
  71293. var desiredHeight = this._options.height || requiredHeight;
  71294. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  71295. if (this.adaptScaleToCurrentViewport) {
  71296. var currentViewport = engine.currentViewport;
  71297. if (currentViewport) {
  71298. desiredWidth *= currentViewport.width;
  71299. desiredHeight *= currentViewport.height;
  71300. }
  71301. }
  71302. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  71303. if (!this._options.width) {
  71304. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  71305. }
  71306. if (!this._options.height) {
  71307. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  71308. }
  71309. }
  71310. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  71311. if (this._textures.length > 0) {
  71312. for (var i = 0; i < this._textures.length; i++) {
  71313. this._engine._releaseTexture(this._textures.data[i]);
  71314. }
  71315. this._textures.reset();
  71316. }
  71317. this.width = desiredWidth;
  71318. this.height = desiredHeight;
  71319. var textureSize = { width: this.width, height: this.height };
  71320. var textureOptions = {
  71321. generateMipMaps: false,
  71322. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  71323. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  71324. samplingMode: this.renderTargetSamplingMode,
  71325. type: this._textureType
  71326. };
  71327. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71328. if (this._reusable) {
  71329. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71330. }
  71331. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  71332. this.onSizeChangedObservable.notifyObservers(this);
  71333. }
  71334. this._textures.forEach(function (texture) {
  71335. if (texture.samples !== _this.samples) {
  71336. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  71337. }
  71338. });
  71339. }
  71340. var target;
  71341. if (this._shareOutputWithPostProcess) {
  71342. target = this._shareOutputWithPostProcess.inputTexture;
  71343. }
  71344. else if (this._forcedOutputTexture) {
  71345. target = this._forcedOutputTexture;
  71346. this.width = this._forcedOutputTexture.width;
  71347. this.height = this._forcedOutputTexture.height;
  71348. }
  71349. else {
  71350. target = this.inputTexture;
  71351. }
  71352. // Bind the input of this post process to be used as the output of the previous post process.
  71353. if (this.enablePixelPerfectMode) {
  71354. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  71355. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  71356. }
  71357. else {
  71358. this._scaleRatio.copyFromFloats(1, 1);
  71359. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  71360. }
  71361. this.onActivateObservable.notifyObservers(camera);
  71362. // Clear
  71363. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  71364. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  71365. }
  71366. if (this._reusable) {
  71367. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  71368. }
  71369. return target;
  71370. };
  71371. Object.defineProperty(PostProcess.prototype, "isSupported", {
  71372. /**
  71373. * If the post process is supported.
  71374. */
  71375. get: function () {
  71376. return this._effect.isSupported;
  71377. },
  71378. enumerable: true,
  71379. configurable: true
  71380. });
  71381. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  71382. /**
  71383. * The aspect ratio of the output texture.
  71384. */
  71385. get: function () {
  71386. if (this._shareOutputWithPostProcess) {
  71387. return this._shareOutputWithPostProcess.aspectRatio;
  71388. }
  71389. if (this._forcedOutputTexture) {
  71390. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  71391. }
  71392. return this.width / this.height;
  71393. },
  71394. enumerable: true,
  71395. configurable: true
  71396. });
  71397. /**
  71398. * Get a value indicating if the post-process is ready to be used
  71399. * @returns true if the post-process is ready (shader is compiled)
  71400. */
  71401. PostProcess.prototype.isReady = function () {
  71402. return this._effect && this._effect.isReady();
  71403. };
  71404. /**
  71405. * Binds all textures and uniforms to the shader, this will be run on every pass.
  71406. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  71407. */
  71408. PostProcess.prototype.apply = function () {
  71409. // Check
  71410. if (!this._effect || !this._effect.isReady())
  71411. return null;
  71412. // States
  71413. this._engine.enableEffect(this._effect);
  71414. this._engine.setState(false);
  71415. this._engine.setDepthBuffer(false);
  71416. this._engine.setDepthWrite(false);
  71417. // Alpha
  71418. this._engine.setAlphaMode(this.alphaMode);
  71419. if (this.alphaConstants) {
  71420. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  71421. }
  71422. // Bind the output texture of the preivous post process as the input to this post process.
  71423. var source;
  71424. if (this._shareOutputWithPostProcess) {
  71425. source = this._shareOutputWithPostProcess.inputTexture;
  71426. }
  71427. else if (this._forcedOutputTexture) {
  71428. source = this._forcedOutputTexture;
  71429. }
  71430. else {
  71431. source = this.inputTexture;
  71432. }
  71433. this._effect._bindTexture("textureSampler", source);
  71434. // Parameters
  71435. this._effect.setVector2("scale", this._scaleRatio);
  71436. this.onApplyObservable.notifyObservers(this._effect);
  71437. return this._effect;
  71438. };
  71439. PostProcess.prototype._disposeTextures = function () {
  71440. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  71441. return;
  71442. }
  71443. if (this._textures.length > 0) {
  71444. for (var i = 0; i < this._textures.length; i++) {
  71445. this._engine._releaseTexture(this._textures.data[i]);
  71446. }
  71447. }
  71448. this._textures.dispose();
  71449. };
  71450. /**
  71451. * Disposes the post process.
  71452. * @param camera The camera to dispose the post process on.
  71453. */
  71454. PostProcess.prototype.dispose = function (camera) {
  71455. camera = camera || this._camera;
  71456. this._disposeTextures();
  71457. if (this._scene) {
  71458. var index_1 = this._scene.postProcesses.indexOf(this);
  71459. if (index_1 !== -1) {
  71460. this._scene.postProcesses.splice(index_1, 1);
  71461. }
  71462. }
  71463. else {
  71464. var index_2 = this._engine.postProcesses.indexOf(this);
  71465. if (index_2 !== -1) {
  71466. this._engine.postProcesses.splice(index_2, 1);
  71467. }
  71468. }
  71469. if (!camera) {
  71470. return;
  71471. }
  71472. camera.detachPostProcess(this);
  71473. var index = camera._postProcesses.indexOf(this);
  71474. if (index === 0 && camera._postProcesses.length > 0) {
  71475. var firstPostProcess = this._camera._getFirstPostProcess();
  71476. if (firstPostProcess) {
  71477. firstPostProcess.markTextureDirty();
  71478. }
  71479. }
  71480. this.onActivateObservable.clear();
  71481. this.onAfterRenderObservable.clear();
  71482. this.onApplyObservable.clear();
  71483. this.onBeforeRenderObservable.clear();
  71484. this.onSizeChangedObservable.clear();
  71485. };
  71486. return PostProcess;
  71487. }());
  71488. BABYLON.PostProcess = PostProcess;
  71489. })(BABYLON || (BABYLON = {}));
  71490. //# sourceMappingURL=babylon.postProcess.js.map
  71491. var BABYLON;
  71492. (function (BABYLON) {
  71493. var PassPostProcess = /** @class */ (function (_super) {
  71494. __extends(PassPostProcess, _super);
  71495. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71496. if (camera === void 0) { camera = null; }
  71497. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71498. if (blockCompilation === void 0) { blockCompilation = false; }
  71499. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  71500. }
  71501. return PassPostProcess;
  71502. }(BABYLON.PostProcess));
  71503. BABYLON.PassPostProcess = PassPostProcess;
  71504. })(BABYLON || (BABYLON = {}));
  71505. //# sourceMappingURL=babylon.passPostProcess.js.map
  71506. var __assign = (this && this.__assign) || function () {
  71507. __assign = Object.assign || function(t) {
  71508. for (var s, i = 1, n = arguments.length; i < n; i++) {
  71509. s = arguments[i];
  71510. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  71511. t[p] = s[p];
  71512. }
  71513. return t;
  71514. };
  71515. return __assign.apply(this, arguments);
  71516. };
  71517. var BABYLON;
  71518. (function (BABYLON) {
  71519. /**
  71520. * Default implementation IShadowGenerator.
  71521. * This is the main object responsible of generating shadows in the framework.
  71522. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  71523. */
  71524. var ShadowGenerator = /** @class */ (function () {
  71525. /**
  71526. * Creates a ShadowGenerator object.
  71527. * A ShadowGenerator is the required tool to use the shadows.
  71528. * Each light casting shadows needs to use its own ShadowGenerator.
  71529. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  71530. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  71531. * @param light The light object generating the shadows.
  71532. * @param 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.
  71533. */
  71534. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  71535. this._bias = 0.00005;
  71536. this._normalBias = 0;
  71537. this._blurBoxOffset = 1;
  71538. this._blurScale = 2;
  71539. this._blurKernel = 1;
  71540. this._useKernelBlur = false;
  71541. this._filter = ShadowGenerator.FILTER_NONE;
  71542. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  71543. this._contactHardeningLightSizeUVRatio = 0.1;
  71544. this._darkness = 0;
  71545. this._transparencyShadow = false;
  71546. /**
  71547. * Controls the extent to which the shadows fade out at the edge of the frustum
  71548. * Used only by directionals and spots
  71549. */
  71550. this.frustumEdgeFalloff = 0;
  71551. /**
  71552. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  71553. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  71554. * It might on the other hand introduce peter panning.
  71555. */
  71556. this.forceBackFacesOnly = false;
  71557. this._lightDirection = BABYLON.Vector3.Zero();
  71558. this._viewMatrix = BABYLON.Matrix.Zero();
  71559. this._projectionMatrix = BABYLON.Matrix.Zero();
  71560. this._transformMatrix = BABYLON.Matrix.Zero();
  71561. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  71562. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  71563. this._currentFaceIndex = 0;
  71564. this._currentFaceIndexCache = 0;
  71565. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  71566. this._mapSize = mapSize;
  71567. this._light = light;
  71568. this._scene = light.getScene();
  71569. light._shadowGenerator = this;
  71570. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  71571. if (!component) {
  71572. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  71573. this._scene._addComponent(component);
  71574. }
  71575. // Texture type fallback from float to int if not supported.
  71576. var caps = this._scene.getEngine().getCaps();
  71577. if (!useFullFloatFirst) {
  71578. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  71579. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71580. }
  71581. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  71582. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71583. }
  71584. else {
  71585. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71586. }
  71587. }
  71588. else {
  71589. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  71590. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71591. }
  71592. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  71593. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71594. }
  71595. else {
  71596. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71597. }
  71598. }
  71599. this._initializeGenerator();
  71600. this._applyFilterValues();
  71601. }
  71602. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  71603. /**
  71604. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  71605. */
  71606. get: function () {
  71607. return this._bias;
  71608. },
  71609. /**
  71610. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  71611. */
  71612. set: function (bias) {
  71613. this._bias = bias;
  71614. },
  71615. enumerable: true,
  71616. configurable: true
  71617. });
  71618. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  71619. /**
  71620. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  71621. */
  71622. get: function () {
  71623. return this._normalBias;
  71624. },
  71625. /**
  71626. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  71627. */
  71628. set: function (normalBias) {
  71629. this._normalBias = normalBias;
  71630. },
  71631. enumerable: true,
  71632. configurable: true
  71633. });
  71634. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  71635. /**
  71636. * Gets the blur box offset: offset applied during the blur pass.
  71637. * Only usefull if useKernelBlur = false
  71638. */
  71639. get: function () {
  71640. return this._blurBoxOffset;
  71641. },
  71642. /**
  71643. * Sets the blur box offset: offset applied during the blur pass.
  71644. * Only usefull if useKernelBlur = false
  71645. */
  71646. set: function (value) {
  71647. if (this._blurBoxOffset === value) {
  71648. return;
  71649. }
  71650. this._blurBoxOffset = value;
  71651. this._disposeBlurPostProcesses();
  71652. },
  71653. enumerable: true,
  71654. configurable: true
  71655. });
  71656. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  71657. /**
  71658. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  71659. * 2 means half of the size.
  71660. */
  71661. get: function () {
  71662. return this._blurScale;
  71663. },
  71664. /**
  71665. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  71666. * 2 means half of the size.
  71667. */
  71668. set: function (value) {
  71669. if (this._blurScale === value) {
  71670. return;
  71671. }
  71672. this._blurScale = value;
  71673. this._disposeBlurPostProcesses();
  71674. },
  71675. enumerable: true,
  71676. configurable: true
  71677. });
  71678. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  71679. /**
  71680. * Gets the blur kernel: kernel size of the blur pass.
  71681. * Only usefull if useKernelBlur = true
  71682. */
  71683. get: function () {
  71684. return this._blurKernel;
  71685. },
  71686. /**
  71687. * Sets the blur kernel: kernel size of the blur pass.
  71688. * Only usefull if useKernelBlur = true
  71689. */
  71690. set: function (value) {
  71691. if (this._blurKernel === value) {
  71692. return;
  71693. }
  71694. this._blurKernel = value;
  71695. this._disposeBlurPostProcesses();
  71696. },
  71697. enumerable: true,
  71698. configurable: true
  71699. });
  71700. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  71701. /**
  71702. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  71703. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  71704. */
  71705. get: function () {
  71706. return this._useKernelBlur;
  71707. },
  71708. /**
  71709. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  71710. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  71711. */
  71712. set: function (value) {
  71713. if (this._useKernelBlur === value) {
  71714. return;
  71715. }
  71716. this._useKernelBlur = value;
  71717. this._disposeBlurPostProcesses();
  71718. },
  71719. enumerable: true,
  71720. configurable: true
  71721. });
  71722. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  71723. /**
  71724. * Gets the depth scale used in ESM mode.
  71725. */
  71726. get: function () {
  71727. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  71728. },
  71729. /**
  71730. * Sets the depth scale used in ESM mode.
  71731. * This can override the scale stored on the light.
  71732. */
  71733. set: function (value) {
  71734. this._depthScale = value;
  71735. },
  71736. enumerable: true,
  71737. configurable: true
  71738. });
  71739. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  71740. /**
  71741. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  71742. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  71743. */
  71744. get: function () {
  71745. return this._filter;
  71746. },
  71747. /**
  71748. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  71749. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  71750. */
  71751. set: function (value) {
  71752. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  71753. if (this._light.needCube()) {
  71754. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  71755. this.useExponentialShadowMap = true;
  71756. return;
  71757. }
  71758. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  71759. this.useCloseExponentialShadowMap = true;
  71760. return;
  71761. }
  71762. // PCF on cubemap would also be expensive
  71763. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  71764. this.usePoissonSampling = true;
  71765. return;
  71766. }
  71767. }
  71768. // Weblg1 fallback for PCF.
  71769. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  71770. if (this._scene.getEngine().webGLVersion === 1) {
  71771. this.usePoissonSampling = true;
  71772. return;
  71773. }
  71774. }
  71775. if (this._filter === value) {
  71776. return;
  71777. }
  71778. this._filter = value;
  71779. this._disposeBlurPostProcesses();
  71780. this._applyFilterValues();
  71781. this._light._markMeshesAsLightDirty();
  71782. },
  71783. enumerable: true,
  71784. configurable: true
  71785. });
  71786. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  71787. /**
  71788. * Gets if the current filter is set to Poisson Sampling.
  71789. */
  71790. get: function () {
  71791. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  71792. },
  71793. /**
  71794. * Sets the current filter to Poisson Sampling.
  71795. */
  71796. set: function (value) {
  71797. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  71798. return;
  71799. }
  71800. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  71801. },
  71802. enumerable: true,
  71803. configurable: true
  71804. });
  71805. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  71806. /**
  71807. * Gets if the current filter is set to VSM.
  71808. * DEPRECATED. Should use useExponentialShadowMap instead.
  71809. */
  71810. get: function () {
  71811. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  71812. return this.useExponentialShadowMap;
  71813. },
  71814. /**
  71815. * Sets the current filter is to VSM.
  71816. * DEPRECATED. Should use useExponentialShadowMap instead.
  71817. */
  71818. set: function (value) {
  71819. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  71820. this.useExponentialShadowMap = value;
  71821. },
  71822. enumerable: true,
  71823. configurable: true
  71824. });
  71825. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  71826. /**
  71827. * Gets if the current filter is set to blurred VSM.
  71828. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  71829. */
  71830. get: function () {
  71831. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  71832. return this.useBlurExponentialShadowMap;
  71833. },
  71834. /**
  71835. * Sets the current filter is to blurred VSM.
  71836. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  71837. */
  71838. set: function (value) {
  71839. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  71840. this.useBlurExponentialShadowMap = value;
  71841. },
  71842. enumerable: true,
  71843. configurable: true
  71844. });
  71845. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  71846. /**
  71847. * Gets if the current filter is set to ESM.
  71848. */
  71849. get: function () {
  71850. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  71851. },
  71852. /**
  71853. * Sets the current filter is to ESM.
  71854. */
  71855. set: function (value) {
  71856. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  71857. return;
  71858. }
  71859. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  71860. },
  71861. enumerable: true,
  71862. configurable: true
  71863. });
  71864. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  71865. /**
  71866. * Gets if the current filter is set to filtered ESM.
  71867. */
  71868. get: function () {
  71869. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  71870. },
  71871. /**
  71872. * Gets if the current filter is set to filtered ESM.
  71873. */
  71874. set: function (value) {
  71875. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  71876. return;
  71877. }
  71878. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  71879. },
  71880. enumerable: true,
  71881. configurable: true
  71882. });
  71883. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  71884. /**
  71885. * Gets if the current filter is set to "close ESM" (using the inverse of the
  71886. * exponential to prevent steep falloff artifacts).
  71887. */
  71888. get: function () {
  71889. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  71890. },
  71891. /**
  71892. * Sets the current filter to "close ESM" (using the inverse of the
  71893. * exponential to prevent steep falloff artifacts).
  71894. */
  71895. set: function (value) {
  71896. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  71897. return;
  71898. }
  71899. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  71900. },
  71901. enumerable: true,
  71902. configurable: true
  71903. });
  71904. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  71905. /**
  71906. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  71907. * exponential to prevent steep falloff artifacts).
  71908. */
  71909. get: function () {
  71910. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  71911. },
  71912. /**
  71913. * Sets the current filter to filtered "close ESM" (using the inverse of the
  71914. * exponential to prevent steep falloff artifacts).
  71915. */
  71916. set: function (value) {
  71917. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  71918. return;
  71919. }
  71920. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  71921. },
  71922. enumerable: true,
  71923. configurable: true
  71924. });
  71925. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  71926. /**
  71927. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  71928. */
  71929. get: function () {
  71930. return this.filter === ShadowGenerator.FILTER_PCF;
  71931. },
  71932. /**
  71933. * Sets the current filter to "PCF" (percentage closer filtering).
  71934. */
  71935. set: function (value) {
  71936. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  71937. return;
  71938. }
  71939. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  71940. },
  71941. enumerable: true,
  71942. configurable: true
  71943. });
  71944. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  71945. /**
  71946. * Gets the PCF or PCSS Quality.
  71947. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  71948. */
  71949. get: function () {
  71950. return this._filteringQuality;
  71951. },
  71952. /**
  71953. * Sets the PCF or PCSS Quality.
  71954. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  71955. */
  71956. set: function (filteringQuality) {
  71957. this._filteringQuality = filteringQuality;
  71958. },
  71959. enumerable: true,
  71960. configurable: true
  71961. });
  71962. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  71963. /**
  71964. * Gets if the current filter is set to "PCSS" (contact hardening).
  71965. */
  71966. get: function () {
  71967. return this.filter === ShadowGenerator.FILTER_PCSS;
  71968. },
  71969. /**
  71970. * Sets the current filter to "PCSS" (contact hardening).
  71971. */
  71972. set: function (value) {
  71973. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  71974. return;
  71975. }
  71976. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  71977. },
  71978. enumerable: true,
  71979. configurable: true
  71980. });
  71981. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  71982. /**
  71983. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  71984. * Using a ratio helps keeping shape stability independently of the map size.
  71985. *
  71986. * It does not account for the light projection as it was having too much
  71987. * instability during the light setup or during light position changes.
  71988. *
  71989. * Only valid if useContactHardeningShadow is true.
  71990. */
  71991. get: function () {
  71992. return this._contactHardeningLightSizeUVRatio;
  71993. },
  71994. /**
  71995. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  71996. * Using a ratio helps keeping shape stability independently of the map size.
  71997. *
  71998. * It does not account for the light projection as it was having too much
  71999. * instability during the light setup or during light position changes.
  72000. *
  72001. * Only valid if useContactHardeningShadow is true.
  72002. */
  72003. set: function (contactHardeningLightSizeUVRatio) {
  72004. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72005. },
  72006. enumerable: true,
  72007. configurable: true
  72008. });
  72009. /**
  72010. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72011. * 0 means strongest and 1 would means no shadow.
  72012. * @returns the darkness.
  72013. */
  72014. ShadowGenerator.prototype.getDarkness = function () {
  72015. return this._darkness;
  72016. };
  72017. /**
  72018. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72019. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72020. * @returns the shadow generator allowing fluent coding.
  72021. */
  72022. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72023. if (darkness >= 1.0)
  72024. this._darkness = 1.0;
  72025. else if (darkness <= 0.0)
  72026. this._darkness = 0.0;
  72027. else
  72028. this._darkness = darkness;
  72029. return this;
  72030. };
  72031. /**
  72032. * Sets the ability to have transparent shadow (boolean).
  72033. * @param transparent True if transparent else False
  72034. * @returns the shadow generator allowing fluent coding
  72035. */
  72036. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72037. this._transparencyShadow = transparent;
  72038. return this;
  72039. };
  72040. /**
  72041. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72042. * @returns The render target texture if present otherwise, null
  72043. */
  72044. ShadowGenerator.prototype.getShadowMap = function () {
  72045. return this._shadowMap;
  72046. };
  72047. /**
  72048. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72049. * @returns The render target texture if the shadow map is present otherwise, null
  72050. */
  72051. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72052. if (this._shadowMap2) {
  72053. return this._shadowMap2;
  72054. }
  72055. return this._shadowMap;
  72056. };
  72057. /**
  72058. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72059. * @param mesh Mesh to add
  72060. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72061. * @returns the Shadow Generator itself
  72062. */
  72063. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72064. if (includeDescendants === void 0) { includeDescendants = true; }
  72065. var _a;
  72066. if (!this._shadowMap) {
  72067. return this;
  72068. }
  72069. if (!this._shadowMap.renderList) {
  72070. this._shadowMap.renderList = [];
  72071. }
  72072. this._shadowMap.renderList.push(mesh);
  72073. if (includeDescendants) {
  72074. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72075. }
  72076. return this;
  72077. };
  72078. /**
  72079. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72080. * @param mesh Mesh to remove
  72081. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72082. * @returns the Shadow Generator itself
  72083. */
  72084. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72085. if (includeDescendants === void 0) { includeDescendants = true; }
  72086. if (!this._shadowMap || !this._shadowMap.renderList) {
  72087. return this;
  72088. }
  72089. var index = this._shadowMap.renderList.indexOf(mesh);
  72090. if (index !== -1) {
  72091. this._shadowMap.renderList.splice(index, 1);
  72092. }
  72093. if (includeDescendants) {
  72094. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72095. var child = _a[_i];
  72096. this.removeShadowCaster(child);
  72097. }
  72098. }
  72099. return this;
  72100. };
  72101. /**
  72102. * Returns the associated light object.
  72103. * @returns the light generating the shadow
  72104. */
  72105. ShadowGenerator.prototype.getLight = function () {
  72106. return this._light;
  72107. };
  72108. ShadowGenerator.prototype._initializeGenerator = function () {
  72109. this._light._markMeshesAsLightDirty();
  72110. this._initializeShadowMap();
  72111. };
  72112. ShadowGenerator.prototype._initializeShadowMap = function () {
  72113. var _this = this;
  72114. // Render target
  72115. var engine = this._scene.getEngine();
  72116. if (engine.webGLVersion > 1) {
  72117. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  72118. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  72119. }
  72120. else {
  72121. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  72122. }
  72123. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72124. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72125. this._shadowMap.anisotropicFilteringLevel = 1;
  72126. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72127. this._shadowMap.renderParticles = false;
  72128. this._shadowMap.ignoreCameraViewport = true;
  72129. // Record Face Index before render.
  72130. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  72131. _this._currentFaceIndex = faceIndex;
  72132. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72133. engine.setColorWrite(false);
  72134. }
  72135. });
  72136. // Custom render function.
  72137. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  72138. // Blur if required afer render.
  72139. this._shadowMap.onAfterUnbindObservable.add(function () {
  72140. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72141. engine.setColorWrite(true);
  72142. }
  72143. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  72144. return;
  72145. }
  72146. var shadowMap = _this.getShadowMapForRendering();
  72147. if (shadowMap) {
  72148. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  72149. }
  72150. });
  72151. // Clear according to the chosen filter.
  72152. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  72153. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  72154. this._shadowMap.onClearObservable.add(function (engine) {
  72155. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72156. engine.clear(clearOne, false, true, false);
  72157. }
  72158. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  72159. engine.clear(clearZero, true, true, false);
  72160. }
  72161. else {
  72162. engine.clear(clearOne, true, true, false);
  72163. }
  72164. });
  72165. };
  72166. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  72167. var _this = this;
  72168. var engine = this._scene.getEngine();
  72169. var targetSize = this._mapSize / this.blurScale;
  72170. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  72171. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  72172. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72173. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72174. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72175. }
  72176. if (this.useKernelBlur) {
  72177. 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);
  72178. this._kernelBlurXPostprocess.width = targetSize;
  72179. this._kernelBlurXPostprocess.height = targetSize;
  72180. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  72181. effect.setTexture("textureSampler", _this._shadowMap);
  72182. });
  72183. 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);
  72184. this._kernelBlurXPostprocess.autoClear = false;
  72185. this._kernelBlurYPostprocess.autoClear = false;
  72186. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72187. this._kernelBlurXPostprocess.packedFloat = true;
  72188. this._kernelBlurYPostprocess.packedFloat = true;
  72189. }
  72190. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  72191. }
  72192. else {
  72193. 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);
  72194. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  72195. effect.setFloat2("screenSize", targetSize, targetSize);
  72196. effect.setTexture("textureSampler", _this._shadowMap);
  72197. });
  72198. this._boxBlurPostprocess.autoClear = false;
  72199. this._blurPostProcesses = [this._boxBlurPostprocess];
  72200. }
  72201. };
  72202. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72203. var index;
  72204. var engine = this._scene.getEngine();
  72205. if (depthOnlySubMeshes.length) {
  72206. engine.setColorWrite(false);
  72207. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72208. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  72209. }
  72210. engine.setColorWrite(true);
  72211. }
  72212. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72213. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  72214. }
  72215. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72216. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  72217. }
  72218. if (this._transparencyShadow) {
  72219. for (index = 0; index < transparentSubMeshes.length; index++) {
  72220. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  72221. }
  72222. }
  72223. };
  72224. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  72225. var _this = this;
  72226. var mesh = subMesh.getRenderingMesh();
  72227. var scene = this._scene;
  72228. var engine = scene.getEngine();
  72229. var material = subMesh.getMaterial();
  72230. if (!material) {
  72231. return;
  72232. }
  72233. // Culling
  72234. engine.setState(material.backFaceCulling);
  72235. // Managing instances
  72236. var batch = mesh._getInstancesRenderList(subMesh._id);
  72237. if (batch.mustReturn) {
  72238. return;
  72239. }
  72240. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72241. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  72242. engine.enableEffect(this._effect);
  72243. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72244. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  72245. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  72246. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72247. this._effect.setVector3("lightData", this._cachedDirection);
  72248. }
  72249. else {
  72250. this._effect.setVector3("lightData", this._cachedPosition);
  72251. }
  72252. if (scene.activeCamera) {
  72253. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  72254. }
  72255. // Alpha test
  72256. if (material && material.needAlphaTesting()) {
  72257. var alphaTexture = material.getAlphaTestTexture();
  72258. if (alphaTexture) {
  72259. this._effect.setTexture("diffuseSampler", alphaTexture);
  72260. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  72261. }
  72262. }
  72263. // Bones
  72264. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72265. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  72266. }
  72267. // Morph targets
  72268. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  72269. if (this.forceBackFacesOnly) {
  72270. engine.setState(true, 0, false, true);
  72271. }
  72272. // Draw
  72273. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72274. if (this.forceBackFacesOnly) {
  72275. engine.setState(true, 0, false, false);
  72276. }
  72277. }
  72278. else {
  72279. // Need to reset refresh rate of the shadowMap
  72280. if (this._shadowMap) {
  72281. this._shadowMap.resetRefreshCounter();
  72282. }
  72283. }
  72284. };
  72285. ShadowGenerator.prototype._applyFilterValues = function () {
  72286. if (!this._shadowMap) {
  72287. return;
  72288. }
  72289. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  72290. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  72291. }
  72292. else {
  72293. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72294. }
  72295. };
  72296. /**
  72297. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72298. * @param onCompiled Callback triggered at the and of the effects compilation
  72299. * @param options Sets of optional options forcing the compilation with different modes
  72300. */
  72301. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  72302. var _this = this;
  72303. var localOptions = __assign({ useInstances: false }, options);
  72304. var shadowMap = this.getShadowMap();
  72305. if (!shadowMap) {
  72306. if (onCompiled) {
  72307. onCompiled(this);
  72308. }
  72309. return;
  72310. }
  72311. var renderList = shadowMap.renderList;
  72312. if (!renderList) {
  72313. if (onCompiled) {
  72314. onCompiled(this);
  72315. }
  72316. return;
  72317. }
  72318. var subMeshes = new Array();
  72319. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  72320. var mesh = renderList_1[_i];
  72321. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  72322. }
  72323. if (subMeshes.length === 0) {
  72324. if (onCompiled) {
  72325. onCompiled(this);
  72326. }
  72327. return;
  72328. }
  72329. var currentIndex = 0;
  72330. var checkReady = function () {
  72331. if (!_this._scene || !_this._scene.getEngine()) {
  72332. return;
  72333. }
  72334. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  72335. currentIndex++;
  72336. if (currentIndex >= subMeshes.length) {
  72337. if (onCompiled) {
  72338. onCompiled(_this);
  72339. }
  72340. return;
  72341. }
  72342. }
  72343. setTimeout(checkReady, 16);
  72344. };
  72345. checkReady();
  72346. };
  72347. /**
  72348. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72349. * @param options Sets of optional options forcing the compilation with different modes
  72350. * @returns A promise that resolves when the compilation completes
  72351. */
  72352. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  72353. var _this = this;
  72354. return new Promise(function (resolve) {
  72355. _this.forceCompilation(function () {
  72356. resolve();
  72357. }, options);
  72358. });
  72359. };
  72360. /**
  72361. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  72362. * @param subMesh The submesh we want to render in the shadow map
  72363. * @param useInstances Defines wether will draw in the map using instances
  72364. * @returns true if ready otherwise, false
  72365. */
  72366. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  72367. var defines = [];
  72368. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72369. defines.push("#define FLOAT");
  72370. }
  72371. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  72372. defines.push("#define ESM");
  72373. }
  72374. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  72375. defines.push("#define DEPTHTEXTURE");
  72376. }
  72377. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72378. var mesh = subMesh.getMesh();
  72379. var material = subMesh.getMaterial();
  72380. // Normal bias.
  72381. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  72382. attribs.push(BABYLON.VertexBuffer.NormalKind);
  72383. defines.push("#define NORMAL");
  72384. if (mesh.nonUniformScaling) {
  72385. defines.push("#define NONUNIFORMSCALING");
  72386. }
  72387. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72388. defines.push("#define DIRECTIONINLIGHTDATA");
  72389. }
  72390. }
  72391. // Alpha test
  72392. if (material && material.needAlphaTesting()) {
  72393. var alphaTexture = material.getAlphaTestTexture();
  72394. if (alphaTexture) {
  72395. defines.push("#define ALPHATEST");
  72396. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72397. attribs.push(BABYLON.VertexBuffer.UVKind);
  72398. defines.push("#define UV1");
  72399. }
  72400. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72401. if (alphaTexture.coordinatesIndex === 1) {
  72402. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72403. defines.push("#define UV2");
  72404. }
  72405. }
  72406. }
  72407. }
  72408. // Bones
  72409. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72410. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72411. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72412. if (mesh.numBoneInfluencers > 4) {
  72413. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72414. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72415. }
  72416. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72417. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  72418. }
  72419. else {
  72420. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72421. }
  72422. // Morph targets
  72423. var manager = mesh.morphTargetManager;
  72424. var morphInfluencers = 0;
  72425. if (manager) {
  72426. if (manager.numInfluencers > 0) {
  72427. defines.push("#define MORPHTARGETS");
  72428. morphInfluencers = manager.numInfluencers;
  72429. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  72430. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  72431. }
  72432. }
  72433. // Instances
  72434. if (useInstances) {
  72435. defines.push("#define INSTANCES");
  72436. attribs.push("world0");
  72437. attribs.push("world1");
  72438. attribs.push("world2");
  72439. attribs.push("world3");
  72440. }
  72441. // Get correct effect
  72442. var join = defines.join("\n");
  72443. if (this._cachedDefines !== join) {
  72444. this._cachedDefines = join;
  72445. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  72446. }
  72447. if (!this._effect.isReady()) {
  72448. return false;
  72449. }
  72450. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  72451. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  72452. this._initializeBlurRTTAndPostProcesses();
  72453. }
  72454. }
  72455. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  72456. return false;
  72457. }
  72458. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  72459. return false;
  72460. }
  72461. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  72462. return false;
  72463. }
  72464. return true;
  72465. };
  72466. /**
  72467. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  72468. * @param defines Defines of the material we want to update
  72469. * @param lightIndex Index of the light in the enabled light list of the material
  72470. */
  72471. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  72472. var scene = this._scene;
  72473. var light = this._light;
  72474. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  72475. return;
  72476. }
  72477. defines["SHADOW" + lightIndex] = true;
  72478. if (this.useContactHardeningShadow) {
  72479. defines["SHADOWPCSS" + lightIndex] = true;
  72480. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  72481. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  72482. }
  72483. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  72484. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  72485. }
  72486. // else default to high.
  72487. }
  72488. if (this.usePercentageCloserFiltering) {
  72489. defines["SHADOWPCF" + lightIndex] = true;
  72490. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  72491. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  72492. }
  72493. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  72494. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  72495. }
  72496. // else default to high.
  72497. }
  72498. else if (this.usePoissonSampling) {
  72499. defines["SHADOWPOISSON" + lightIndex] = true;
  72500. }
  72501. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  72502. defines["SHADOWESM" + lightIndex] = true;
  72503. }
  72504. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  72505. defines["SHADOWCLOSEESM" + lightIndex] = true;
  72506. }
  72507. if (light.needCube()) {
  72508. defines["SHADOWCUBE" + lightIndex] = true;
  72509. }
  72510. };
  72511. /**
  72512. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  72513. * defined in the generator but impacting the effect).
  72514. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  72515. * @param effect The effect we are binfing the information for
  72516. */
  72517. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  72518. var light = this._light;
  72519. var scene = this._scene;
  72520. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  72521. return;
  72522. }
  72523. var camera = scene.activeCamera;
  72524. if (!camera) {
  72525. return;
  72526. }
  72527. var shadowMap = this.getShadowMap();
  72528. if (!shadowMap) {
  72529. return;
  72530. }
  72531. if (!light.needCube()) {
  72532. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  72533. }
  72534. // Only PCF uses depth stencil texture.
  72535. if (this._filter === ShadowGenerator.FILTER_PCF) {
  72536. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72537. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  72538. }
  72539. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  72540. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72541. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  72542. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  72543. }
  72544. else {
  72545. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72546. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  72547. }
  72548. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  72549. };
  72550. /**
  72551. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  72552. * (eq to shadow prjection matrix * light transform matrix)
  72553. * @returns The transform matrix used to create the shadow map
  72554. */
  72555. ShadowGenerator.prototype.getTransformMatrix = function () {
  72556. var scene = this._scene;
  72557. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  72558. return this._transformMatrix;
  72559. }
  72560. this._currentRenderID = scene.getRenderId();
  72561. this._currentFaceIndexCache = this._currentFaceIndex;
  72562. var lightPosition = this._light.position;
  72563. if (this._light.computeTransformedInformation()) {
  72564. lightPosition = this._light.transformedPosition;
  72565. }
  72566. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  72567. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  72568. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  72569. }
  72570. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  72571. this._cachedPosition.copyFrom(lightPosition);
  72572. this._cachedDirection.copyFrom(this._lightDirection);
  72573. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  72574. var shadowMap = this.getShadowMap();
  72575. if (shadowMap) {
  72576. var renderList = shadowMap.renderList;
  72577. if (renderList) {
  72578. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  72579. }
  72580. }
  72581. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  72582. }
  72583. return this._transformMatrix;
  72584. };
  72585. /**
  72586. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  72587. * Cube and 2D textures for instance.
  72588. */
  72589. ShadowGenerator.prototype.recreateShadowMap = function () {
  72590. var shadowMap = this._shadowMap;
  72591. if (!shadowMap) {
  72592. return;
  72593. }
  72594. // Track render list.
  72595. var renderList = shadowMap.renderList;
  72596. // Clean up existing data.
  72597. this._disposeRTTandPostProcesses();
  72598. // Reinitializes.
  72599. this._initializeGenerator();
  72600. // Reaffect the filter to ensure a correct fallback if necessary.
  72601. this.filter = this.filter;
  72602. // Reaffect the filter.
  72603. this._applyFilterValues();
  72604. // Reaffect Render List.
  72605. this._shadowMap.renderList = renderList;
  72606. };
  72607. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  72608. if (this._shadowMap2) {
  72609. this._shadowMap2.dispose();
  72610. this._shadowMap2 = null;
  72611. }
  72612. if (this._boxBlurPostprocess) {
  72613. this._boxBlurPostprocess.dispose();
  72614. this._boxBlurPostprocess = null;
  72615. }
  72616. if (this._kernelBlurXPostprocess) {
  72617. this._kernelBlurXPostprocess.dispose();
  72618. this._kernelBlurXPostprocess = null;
  72619. }
  72620. if (this._kernelBlurYPostprocess) {
  72621. this._kernelBlurYPostprocess.dispose();
  72622. this._kernelBlurYPostprocess = null;
  72623. }
  72624. this._blurPostProcesses = [];
  72625. };
  72626. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  72627. if (this._shadowMap) {
  72628. this._shadowMap.dispose();
  72629. this._shadowMap = null;
  72630. }
  72631. this._disposeBlurPostProcesses();
  72632. };
  72633. /**
  72634. * Disposes the ShadowGenerator.
  72635. * Returns nothing.
  72636. */
  72637. ShadowGenerator.prototype.dispose = function () {
  72638. this._disposeRTTandPostProcesses();
  72639. if (this._light) {
  72640. this._light._shadowGenerator = null;
  72641. this._light._markMeshesAsLightDirty();
  72642. }
  72643. };
  72644. /**
  72645. * Serializes the shadow generator setup to a json object.
  72646. * @returns The serialized JSON object
  72647. */
  72648. ShadowGenerator.prototype.serialize = function () {
  72649. var serializationObject = {};
  72650. var shadowMap = this.getShadowMap();
  72651. if (!shadowMap) {
  72652. return serializationObject;
  72653. }
  72654. serializationObject.lightId = this._light.id;
  72655. serializationObject.mapSize = shadowMap.getRenderSize();
  72656. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  72657. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  72658. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  72659. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  72660. serializationObject.usePoissonSampling = this.usePoissonSampling;
  72661. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  72662. serializationObject.depthScale = this.depthScale;
  72663. serializationObject.darkness = this.getDarkness();
  72664. serializationObject.blurBoxOffset = this.blurBoxOffset;
  72665. serializationObject.blurKernel = this.blurKernel;
  72666. serializationObject.blurScale = this.blurScale;
  72667. serializationObject.useKernelBlur = this.useKernelBlur;
  72668. serializationObject.transparencyShadow = this._transparencyShadow;
  72669. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  72670. serializationObject.bias = this.bias;
  72671. serializationObject.normalBias = this.normalBias;
  72672. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  72673. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  72674. serializationObject.filteringQuality = this.filteringQuality;
  72675. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  72676. serializationObject.renderList = [];
  72677. if (shadowMap.renderList) {
  72678. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  72679. var mesh = shadowMap.renderList[meshIndex];
  72680. serializationObject.renderList.push(mesh.id);
  72681. }
  72682. }
  72683. return serializationObject;
  72684. };
  72685. /**
  72686. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  72687. * @param parsedShadowGenerator The JSON object to parse
  72688. * @param scene The scene to create the shadow map for
  72689. * @returns The parsed shadow generator
  72690. */
  72691. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  72692. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  72693. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  72694. var shadowMap = shadowGenerator.getShadowMap();
  72695. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  72696. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  72697. meshes.forEach(function (mesh) {
  72698. if (!shadowMap) {
  72699. return;
  72700. }
  72701. if (!shadowMap.renderList) {
  72702. shadowMap.renderList = [];
  72703. }
  72704. shadowMap.renderList.push(mesh);
  72705. });
  72706. }
  72707. if (parsedShadowGenerator.usePoissonSampling) {
  72708. shadowGenerator.usePoissonSampling = true;
  72709. }
  72710. else if (parsedShadowGenerator.useExponentialShadowMap) {
  72711. shadowGenerator.useExponentialShadowMap = true;
  72712. }
  72713. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  72714. shadowGenerator.useBlurExponentialShadowMap = true;
  72715. }
  72716. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  72717. shadowGenerator.useCloseExponentialShadowMap = true;
  72718. }
  72719. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  72720. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  72721. }
  72722. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  72723. shadowGenerator.usePercentageCloserFiltering = true;
  72724. }
  72725. else if (parsedShadowGenerator.useContactHardeningShadow) {
  72726. shadowGenerator.useContactHardeningShadow = true;
  72727. }
  72728. if (parsedShadowGenerator.filteringQuality) {
  72729. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  72730. }
  72731. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  72732. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  72733. }
  72734. // Backward compat
  72735. else if (parsedShadowGenerator.useVarianceShadowMap) {
  72736. shadowGenerator.useExponentialShadowMap = true;
  72737. }
  72738. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  72739. shadowGenerator.useBlurExponentialShadowMap = true;
  72740. }
  72741. if (parsedShadowGenerator.depthScale) {
  72742. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  72743. }
  72744. if (parsedShadowGenerator.blurScale) {
  72745. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  72746. }
  72747. if (parsedShadowGenerator.blurBoxOffset) {
  72748. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  72749. }
  72750. if (parsedShadowGenerator.useKernelBlur) {
  72751. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  72752. }
  72753. if (parsedShadowGenerator.blurKernel) {
  72754. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  72755. }
  72756. if (parsedShadowGenerator.bias !== undefined) {
  72757. shadowGenerator.bias = parsedShadowGenerator.bias;
  72758. }
  72759. if (parsedShadowGenerator.normalBias !== undefined) {
  72760. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  72761. }
  72762. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  72763. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  72764. }
  72765. if (parsedShadowGenerator.darkness) {
  72766. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  72767. }
  72768. if (parsedShadowGenerator.transparencyShadow) {
  72769. shadowGenerator.setTransparencyShadow(true);
  72770. }
  72771. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  72772. return shadowGenerator;
  72773. };
  72774. /**
  72775. * Shadow generator mode None: no filtering applied.
  72776. */
  72777. ShadowGenerator.FILTER_NONE = 0;
  72778. /**
  72779. * Shadow generator mode ESM: Exponential Shadow Mapping.
  72780. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72781. */
  72782. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  72783. /**
  72784. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  72785. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  72786. */
  72787. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  72788. /**
  72789. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  72790. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72791. */
  72792. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  72793. /**
  72794. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  72795. * edge artifacts on steep falloff.
  72796. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72797. */
  72798. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  72799. /**
  72800. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  72801. * edge artifacts on steep falloff.
  72802. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72803. */
  72804. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  72805. /**
  72806. * Shadow generator mode PCF: Percentage Closer Filtering
  72807. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  72808. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  72809. */
  72810. ShadowGenerator.FILTER_PCF = 6;
  72811. /**
  72812. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  72813. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  72814. * Contact Hardening
  72815. */
  72816. ShadowGenerator.FILTER_PCSS = 7;
  72817. /**
  72818. * Reserved for PCF and PCSS
  72819. * Highest Quality.
  72820. *
  72821. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  72822. *
  72823. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  72824. */
  72825. ShadowGenerator.QUALITY_HIGH = 0;
  72826. /**
  72827. * Reserved for PCF and PCSS
  72828. * Good tradeoff for quality/perf cross devices
  72829. *
  72830. * Execute PCF on a 3*3 kernel.
  72831. *
  72832. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  72833. */
  72834. ShadowGenerator.QUALITY_MEDIUM = 1;
  72835. /**
  72836. * Reserved for PCF and PCSS
  72837. * The lowest quality but the fastest.
  72838. *
  72839. * Execute PCF on a 1*1 kernel.
  72840. *
  72841. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  72842. */
  72843. ShadowGenerator.QUALITY_LOW = 2;
  72844. return ShadowGenerator;
  72845. }());
  72846. BABYLON.ShadowGenerator = ShadowGenerator;
  72847. })(BABYLON || (BABYLON = {}));
  72848. //# sourceMappingURL=babylon.shadowGenerator.js.map
  72849. var BABYLON;
  72850. (function (BABYLON) {
  72851. // Adds the parser to the scene parsers.
  72852. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  72853. // Shadows
  72854. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  72855. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  72856. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  72857. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  72858. // SG would be available on their associated lights
  72859. }
  72860. }
  72861. });
  72862. /**
  72863. * Defines the shadow generator component responsible to manage any shadow generators
  72864. * in a given scene.
  72865. */
  72866. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  72867. /**
  72868. * Creates a new instance of the component for the given scene
  72869. * @param scene Defines the scene to register the component in
  72870. */
  72871. function ShadowGeneratorSceneComponent(scene) {
  72872. /**
  72873. * The component name helpfull to identify the component in the list of scene components.
  72874. */
  72875. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  72876. this.scene = scene;
  72877. }
  72878. /**
  72879. * Registers the component in a given scene
  72880. */
  72881. ShadowGeneratorSceneComponent.prototype.register = function () {
  72882. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  72883. };
  72884. /**
  72885. * Rebuilds the elements related to this component in case of
  72886. * context lost for instance.
  72887. */
  72888. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  72889. // Nothing To Do Here.
  72890. };
  72891. /**
  72892. * Serializes the component data to the specified json object
  72893. * @param serializationObject The object to serialize to
  72894. */
  72895. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  72896. // Shadows
  72897. serializationObject.shadowGenerators = [];
  72898. var lights = this.scene.lights;
  72899. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  72900. var light = lights_1[_i];
  72901. var shadowGenerator = light.getShadowGenerator();
  72902. if (shadowGenerator) {
  72903. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  72904. }
  72905. }
  72906. };
  72907. /**
  72908. * Adds all the element from the container to the scene
  72909. * @param container the container holding the elements
  72910. */
  72911. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  72912. // Nothing To Do Here. (directly attached to a light)
  72913. };
  72914. /**
  72915. * Removes all the elements in the container from the scene
  72916. * @param container contains the elements to remove
  72917. */
  72918. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  72919. // Nothing To Do Here. (directly attached to a light)
  72920. };
  72921. /**
  72922. * Rebuilds the elements related to this component in case of
  72923. * context lost for instance.
  72924. */
  72925. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  72926. // Nothing To Do Here.
  72927. };
  72928. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  72929. // Shadows
  72930. var scene = this.scene;
  72931. if (this.scene.shadowsEnabled) {
  72932. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  72933. var light = scene.lights[lightIndex];
  72934. var shadowGenerator = light.getShadowGenerator();
  72935. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  72936. var shadowMap = (shadowGenerator.getShadowMap());
  72937. if (scene.textures.indexOf(shadowMap) !== -1) {
  72938. renderTargets.push(shadowMap);
  72939. }
  72940. }
  72941. }
  72942. }
  72943. };
  72944. return ShadowGeneratorSceneComponent;
  72945. }());
  72946. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  72947. })(BABYLON || (BABYLON = {}));
  72948. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  72949. var BABYLON;
  72950. (function (BABYLON) {
  72951. var DefaultLoadingScreen = /** @class */ (function () {
  72952. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  72953. if (_loadingText === void 0) { _loadingText = ""; }
  72954. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  72955. var _this = this;
  72956. this._renderingCanvas = _renderingCanvas;
  72957. this._loadingText = _loadingText;
  72958. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  72959. // Resize
  72960. this._resizeLoadingUI = function () {
  72961. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  72962. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  72963. if (!_this._loadingDiv) {
  72964. return;
  72965. }
  72966. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  72967. _this._loadingDiv.style.left = canvasRect.left + "px";
  72968. _this._loadingDiv.style.top = canvasRect.top + "px";
  72969. _this._loadingDiv.style.width = canvasRect.width + "px";
  72970. _this._loadingDiv.style.height = canvasRect.height + "px";
  72971. };
  72972. }
  72973. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  72974. if (this._loadingDiv) {
  72975. // Do not add a loading screen if there is already one
  72976. return;
  72977. }
  72978. this._loadingDiv = document.createElement("div");
  72979. this._loadingDiv.id = "babylonjsLoadingDiv";
  72980. this._loadingDiv.style.opacity = "0";
  72981. this._loadingDiv.style.transition = "opacity 1.5s ease";
  72982. this._loadingDiv.style.pointerEvents = "none";
  72983. // Loading text
  72984. this._loadingTextDiv = document.createElement("div");
  72985. this._loadingTextDiv.style.position = "absolute";
  72986. this._loadingTextDiv.style.left = "0";
  72987. this._loadingTextDiv.style.top = "50%";
  72988. this._loadingTextDiv.style.marginTop = "80px";
  72989. this._loadingTextDiv.style.width = "100%";
  72990. this._loadingTextDiv.style.height = "20px";
  72991. this._loadingTextDiv.style.fontFamily = "Arial";
  72992. this._loadingTextDiv.style.fontSize = "14px";
  72993. this._loadingTextDiv.style.color = "white";
  72994. this._loadingTextDiv.style.textAlign = "center";
  72995. this._loadingTextDiv.innerHTML = "Loading";
  72996. this._loadingDiv.appendChild(this._loadingTextDiv);
  72997. //set the predefined text
  72998. this._loadingTextDiv.innerHTML = this._loadingText;
  72999. // Generating keyframes
  73000. var style = document.createElement('style');
  73001. style.type = 'text/css';
  73002. 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 }";
  73003. style.innerHTML = keyFrames;
  73004. document.getElementsByTagName('head')[0].appendChild(style);
  73005. // Loading img
  73006. var imgBack = new Image();
  73007. 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";
  73008. imgBack.style.position = "absolute";
  73009. imgBack.style.left = "50%";
  73010. imgBack.style.top = "50%";
  73011. imgBack.style.marginLeft = "-60px";
  73012. imgBack.style.marginTop = "-60px";
  73013. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73014. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73015. imgBack.style.transformOrigin = "50% 50%";
  73016. imgBack.style.webkitTransformOrigin = "50% 50%";
  73017. this._loadingDiv.appendChild(imgBack);
  73018. this._resizeLoadingUI();
  73019. window.addEventListener("resize", this._resizeLoadingUI);
  73020. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73021. document.body.appendChild(this._loadingDiv);
  73022. this._loadingDiv.style.opacity = "1";
  73023. };
  73024. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73025. var _this = this;
  73026. if (!this._loadingDiv) {
  73027. return;
  73028. }
  73029. var onTransitionEnd = function () {
  73030. if (!_this._loadingDiv) {
  73031. return;
  73032. }
  73033. document.body.removeChild(_this._loadingDiv);
  73034. window.removeEventListener("resize", _this._resizeLoadingUI);
  73035. _this._loadingDiv = null;
  73036. };
  73037. this._loadingDiv.style.opacity = "0";
  73038. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73039. };
  73040. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73041. set: function (text) {
  73042. this._loadingText = text;
  73043. if (this._loadingTextDiv) {
  73044. this._loadingTextDiv.innerHTML = this._loadingText;
  73045. }
  73046. },
  73047. enumerable: true,
  73048. configurable: true
  73049. });
  73050. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73051. get: function () {
  73052. return this._loadingDivBackgroundColor;
  73053. },
  73054. set: function (color) {
  73055. this._loadingDivBackgroundColor = color;
  73056. if (!this._loadingDiv) {
  73057. return;
  73058. }
  73059. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73060. },
  73061. enumerable: true,
  73062. configurable: true
  73063. });
  73064. return DefaultLoadingScreen;
  73065. }());
  73066. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73067. })(BABYLON || (BABYLON = {}));
  73068. //# sourceMappingURL=babylon.loadingScreen.js.map
  73069. var BABYLON;
  73070. (function (BABYLON) {
  73071. var SceneLoaderProgressEvent = /** @class */ (function () {
  73072. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73073. this.lengthComputable = lengthComputable;
  73074. this.loaded = loaded;
  73075. this.total = total;
  73076. }
  73077. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73078. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73079. };
  73080. return SceneLoaderProgressEvent;
  73081. }());
  73082. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73083. var SceneLoader = /** @class */ (function () {
  73084. function SceneLoader() {
  73085. }
  73086. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73087. get: function () {
  73088. return 0;
  73089. },
  73090. enumerable: true,
  73091. configurable: true
  73092. });
  73093. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73094. get: function () {
  73095. return 1;
  73096. },
  73097. enumerable: true,
  73098. configurable: true
  73099. });
  73100. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  73101. get: function () {
  73102. return 2;
  73103. },
  73104. enumerable: true,
  73105. configurable: true
  73106. });
  73107. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  73108. get: function () {
  73109. return 3;
  73110. },
  73111. enumerable: true,
  73112. configurable: true
  73113. });
  73114. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  73115. get: function () {
  73116. return SceneLoader._ForceFullSceneLoadingForIncremental;
  73117. },
  73118. set: function (value) {
  73119. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  73120. },
  73121. enumerable: true,
  73122. configurable: true
  73123. });
  73124. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  73125. get: function () {
  73126. return SceneLoader._ShowLoadingScreen;
  73127. },
  73128. set: function (value) {
  73129. SceneLoader._ShowLoadingScreen = value;
  73130. },
  73131. enumerable: true,
  73132. configurable: true
  73133. });
  73134. Object.defineProperty(SceneLoader, "loggingLevel", {
  73135. get: function () {
  73136. return SceneLoader._loggingLevel;
  73137. },
  73138. set: function (value) {
  73139. SceneLoader._loggingLevel = value;
  73140. },
  73141. enumerable: true,
  73142. configurable: true
  73143. });
  73144. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  73145. get: function () {
  73146. return SceneLoader._CleanBoneMatrixWeights;
  73147. },
  73148. set: function (value) {
  73149. SceneLoader._CleanBoneMatrixWeights = value;
  73150. },
  73151. enumerable: true,
  73152. configurable: true
  73153. });
  73154. SceneLoader._getDefaultPlugin = function () {
  73155. return SceneLoader._registeredPlugins[".babylon"];
  73156. };
  73157. SceneLoader._getPluginForExtension = function (extension) {
  73158. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  73159. if (registeredPlugin) {
  73160. return registeredPlugin;
  73161. }
  73162. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  73163. return SceneLoader._getDefaultPlugin();
  73164. };
  73165. SceneLoader._getPluginForDirectLoad = function (data) {
  73166. for (var extension in SceneLoader._registeredPlugins) {
  73167. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  73168. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  73169. return SceneLoader._registeredPlugins[extension];
  73170. }
  73171. }
  73172. return SceneLoader._getDefaultPlugin();
  73173. };
  73174. SceneLoader._getPluginForFilename = function (sceneFilename) {
  73175. var queryStringPosition = sceneFilename.indexOf("?");
  73176. if (queryStringPosition !== -1) {
  73177. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  73178. }
  73179. var dotPosition = sceneFilename.lastIndexOf(".");
  73180. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  73181. return SceneLoader._getPluginForExtension(extension);
  73182. };
  73183. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  73184. SceneLoader._getDirectLoad = function (sceneFilename) {
  73185. if (sceneFilename.substr(0, 5) === "data:") {
  73186. return sceneFilename.substr(5);
  73187. }
  73188. return null;
  73189. };
  73190. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  73191. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  73192. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  73193. var plugin;
  73194. if (registeredPlugin.plugin.createPlugin) {
  73195. plugin = registeredPlugin.plugin.createPlugin();
  73196. }
  73197. else {
  73198. plugin = registeredPlugin.plugin;
  73199. }
  73200. var useArrayBuffer = registeredPlugin.isBinary;
  73201. var database;
  73202. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  73203. var dataCallback = function (data, responseURL) {
  73204. if (scene.isDisposed) {
  73205. onError("Scene has been disposed");
  73206. return;
  73207. }
  73208. scene.database = database;
  73209. onSuccess(plugin, data, responseURL);
  73210. };
  73211. var request = null;
  73212. var pluginDisposed = false;
  73213. var onDisposeObservable = plugin.onDisposeObservable;
  73214. if (onDisposeObservable) {
  73215. onDisposeObservable.add(function () {
  73216. pluginDisposed = true;
  73217. if (request) {
  73218. request.abort();
  73219. request = null;
  73220. }
  73221. onDispose();
  73222. });
  73223. }
  73224. var manifestChecked = function () {
  73225. if (pluginDisposed) {
  73226. return;
  73227. }
  73228. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  73229. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  73230. } : undefined, database, useArrayBuffer, function (request, exception) {
  73231. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  73232. });
  73233. };
  73234. if (directLoad) {
  73235. dataCallback(directLoad);
  73236. return plugin;
  73237. }
  73238. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  73239. var engine = scene.getEngine();
  73240. var canUseOfflineSupport = engine.enableOfflineSupport;
  73241. if (canUseOfflineSupport) {
  73242. // Also check for exceptions
  73243. var exceptionFound = false;
  73244. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  73245. var regex = _a[_i];
  73246. if (regex.test(fileInfo.url)) {
  73247. exceptionFound = true;
  73248. break;
  73249. }
  73250. }
  73251. canUseOfflineSupport = !exceptionFound;
  73252. }
  73253. if (canUseOfflineSupport) {
  73254. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  73255. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  73256. }
  73257. else {
  73258. manifestChecked();
  73259. }
  73260. }
  73261. // Loading file from disk via input file or drag'n'drop
  73262. else {
  73263. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  73264. if (file) {
  73265. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  73266. }
  73267. else {
  73268. onError("Unable to find file named " + fileInfo.name);
  73269. }
  73270. }
  73271. return plugin;
  73272. };
  73273. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  73274. var url;
  73275. var name;
  73276. if (!sceneFilename) {
  73277. url = rootUrl;
  73278. name = BABYLON.Tools.GetFilename(rootUrl);
  73279. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  73280. }
  73281. else {
  73282. if (sceneFilename.substr(0, 1) === "/") {
  73283. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  73284. return null;
  73285. }
  73286. url = rootUrl + sceneFilename;
  73287. name = sceneFilename;
  73288. }
  73289. ;
  73290. return {
  73291. url: url,
  73292. rootUrl: rootUrl,
  73293. name: name
  73294. };
  73295. };
  73296. // Public functions
  73297. SceneLoader.GetPluginForExtension = function (extension) {
  73298. return SceneLoader._getPluginForExtension(extension).plugin;
  73299. };
  73300. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  73301. return !!SceneLoader._registeredPlugins[extension];
  73302. };
  73303. SceneLoader.RegisterPlugin = function (plugin) {
  73304. if (typeof plugin.extensions === "string") {
  73305. var extension = plugin.extensions;
  73306. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73307. plugin: plugin,
  73308. isBinary: false
  73309. };
  73310. }
  73311. else {
  73312. var extensions = plugin.extensions;
  73313. Object.keys(extensions).forEach(function (extension) {
  73314. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73315. plugin: plugin,
  73316. isBinary: extensions[extension].isBinary
  73317. };
  73318. });
  73319. }
  73320. };
  73321. /**
  73322. * Import meshes into a scene
  73323. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73324. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73325. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73326. * @param scene the instance of BABYLON.Scene to append to
  73327. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  73328. * @param onProgress a callback with a progress event for each file being loaded
  73329. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73330. * @param pluginExtension the extension used to determine the plugin
  73331. * @returns The loaded plugin
  73332. */
  73333. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73334. if (sceneFilename === void 0) { sceneFilename = ""; }
  73335. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73336. if (onSuccess === void 0) { onSuccess = null; }
  73337. if (onProgress === void 0) { onProgress = null; }
  73338. if (onError === void 0) { onError = null; }
  73339. if (pluginExtension === void 0) { pluginExtension = null; }
  73340. if (!scene) {
  73341. BABYLON.Tools.Error("No scene available to import mesh to");
  73342. return null;
  73343. }
  73344. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73345. if (!fileInfo) {
  73346. return null;
  73347. }
  73348. var loadingToken = {};
  73349. scene._addPendingData(loadingToken);
  73350. var disposeHandler = function () {
  73351. scene._removePendingData(loadingToken);
  73352. };
  73353. var errorHandler = function (message, exception) {
  73354. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  73355. if (onError) {
  73356. onError(scene, errorMessage, exception);
  73357. }
  73358. else {
  73359. BABYLON.Tools.Error(errorMessage);
  73360. // should the exception be thrown?
  73361. }
  73362. disposeHandler();
  73363. };
  73364. var progressHandler = onProgress ? function (event) {
  73365. try {
  73366. onProgress(event);
  73367. }
  73368. catch (e) {
  73369. errorHandler("Error in onProgress callback", e);
  73370. }
  73371. } : undefined;
  73372. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  73373. scene.importedMeshesFiles.push(fileInfo.url);
  73374. if (onSuccess) {
  73375. try {
  73376. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  73377. }
  73378. catch (e) {
  73379. errorHandler("Error in onSuccess callback", e);
  73380. }
  73381. }
  73382. scene._removePendingData(loadingToken);
  73383. };
  73384. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73385. if (plugin.rewriteRootURL) {
  73386. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  73387. }
  73388. if (plugin.importMesh) {
  73389. var syncedPlugin = plugin;
  73390. var meshes = new Array();
  73391. var particleSystems = new Array();
  73392. var skeletons = new Array();
  73393. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  73394. return;
  73395. }
  73396. scene.loadingPluginName = plugin.name;
  73397. successHandler(meshes, particleSystems, skeletons, []);
  73398. }
  73399. else {
  73400. var asyncedPlugin = plugin;
  73401. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  73402. scene.loadingPluginName = plugin.name;
  73403. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  73404. }).catch(function (error) {
  73405. errorHandler(error.message, error);
  73406. });
  73407. }
  73408. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73409. };
  73410. /**
  73411. * Import meshes into a scene
  73412. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73413. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73414. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73415. * @param scene the instance of BABYLON.Scene to append to
  73416. * @param onProgress a callback with a progress event for each file being loaded
  73417. * @param pluginExtension the extension used to determine the plugin
  73418. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  73419. */
  73420. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73421. if (sceneFilename === void 0) { sceneFilename = ""; }
  73422. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73423. if (onProgress === void 0) { onProgress = null; }
  73424. if (pluginExtension === void 0) { pluginExtension = null; }
  73425. return new Promise(function (resolve, reject) {
  73426. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  73427. resolve({
  73428. meshes: meshes,
  73429. particleSystems: particleSystems,
  73430. skeletons: skeletons,
  73431. animationGroups: animationGroups
  73432. });
  73433. }, onProgress, function (scene, message, exception) {
  73434. reject(exception || new Error(message));
  73435. }, pluginExtension);
  73436. });
  73437. };
  73438. /**
  73439. * Load a scene
  73440. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73441. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73442. * @param engine is the instance of BABYLON.Engine to use to create the scene
  73443. * @param onSuccess a callback with the scene when import succeeds
  73444. * @param onProgress a callback with a progress event for each file being loaded
  73445. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73446. * @param pluginExtension the extension used to determine the plugin
  73447. * @returns The loaded plugin
  73448. */
  73449. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  73450. if (onSuccess === void 0) { onSuccess = null; }
  73451. if (onProgress === void 0) { onProgress = null; }
  73452. if (onError === void 0) { onError = null; }
  73453. if (pluginExtension === void 0) { pluginExtension = null; }
  73454. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  73455. };
  73456. /**
  73457. * Load a scene
  73458. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73459. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73460. * @param engine is the instance of BABYLON.Engine to use to create the scene
  73461. * @param onProgress a callback with a progress event for each file being loaded
  73462. * @param pluginExtension the extension used to determine the plugin
  73463. * @returns The loaded scene
  73464. */
  73465. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  73466. if (onProgress === void 0) { onProgress = null; }
  73467. if (pluginExtension === void 0) { pluginExtension = null; }
  73468. return new Promise(function (resolve, reject) {
  73469. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  73470. resolve(scene);
  73471. }, onProgress, function (scene, message, exception) {
  73472. reject(exception || new Error(message));
  73473. }, pluginExtension);
  73474. });
  73475. };
  73476. /**
  73477. * Append a scene
  73478. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73479. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73480. * @param scene is the instance of BABYLON.Scene to append to
  73481. * @param onSuccess a callback with the scene when import succeeds
  73482. * @param onProgress a callback with a progress event for each file being loaded
  73483. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73484. * @param pluginExtension the extension used to determine the plugin
  73485. * @returns The loaded plugin
  73486. */
  73487. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73488. if (sceneFilename === void 0) { sceneFilename = ""; }
  73489. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73490. if (onSuccess === void 0) { onSuccess = null; }
  73491. if (onProgress === void 0) { onProgress = null; }
  73492. if (onError === void 0) { onError = null; }
  73493. if (pluginExtension === void 0) { pluginExtension = null; }
  73494. if (!scene) {
  73495. BABYLON.Tools.Error("No scene available to append to");
  73496. return null;
  73497. }
  73498. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73499. if (!fileInfo) {
  73500. return null;
  73501. }
  73502. if (SceneLoader.ShowLoadingScreen) {
  73503. scene.getEngine().displayLoadingUI();
  73504. }
  73505. var loadingToken = {};
  73506. scene._addPendingData(loadingToken);
  73507. var disposeHandler = function () {
  73508. scene._removePendingData(loadingToken);
  73509. scene.getEngine().hideLoadingUI();
  73510. };
  73511. var errorHandler = function (message, exception) {
  73512. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  73513. if (onError) {
  73514. onError(scene, errorMessage, exception);
  73515. }
  73516. else {
  73517. BABYLON.Tools.Error(errorMessage);
  73518. // should the exception be thrown?
  73519. }
  73520. disposeHandler();
  73521. };
  73522. var progressHandler = onProgress ? function (event) {
  73523. try {
  73524. onProgress(event);
  73525. }
  73526. catch (e) {
  73527. errorHandler("Error in onProgress callback", e);
  73528. }
  73529. } : undefined;
  73530. var successHandler = function () {
  73531. if (onSuccess) {
  73532. try {
  73533. onSuccess(scene);
  73534. }
  73535. catch (e) {
  73536. errorHandler("Error in onSuccess callback", e);
  73537. }
  73538. }
  73539. scene._removePendingData(loadingToken);
  73540. };
  73541. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73542. if (plugin.load) {
  73543. var syncedPlugin = plugin;
  73544. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  73545. return;
  73546. }
  73547. scene.loadingPluginName = plugin.name;
  73548. successHandler();
  73549. }
  73550. else {
  73551. var asyncedPlugin = plugin;
  73552. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  73553. scene.loadingPluginName = plugin.name;
  73554. successHandler();
  73555. }).catch(function (error) {
  73556. errorHandler(error.message, error);
  73557. });
  73558. }
  73559. if (SceneLoader.ShowLoadingScreen) {
  73560. scene.executeWhenReady(function () {
  73561. scene.getEngine().hideLoadingUI();
  73562. });
  73563. }
  73564. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73565. };
  73566. /**
  73567. * Append a scene
  73568. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73569. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73570. * @param scene is the instance of BABYLON.Scene to append to
  73571. * @param onProgress a callback with a progress event for each file being loaded
  73572. * @param pluginExtension the extension used to determine the plugin
  73573. * @returns The given scene
  73574. */
  73575. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73576. if (sceneFilename === void 0) { sceneFilename = ""; }
  73577. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73578. if (onProgress === void 0) { onProgress = null; }
  73579. if (pluginExtension === void 0) { pluginExtension = null; }
  73580. return new Promise(function (resolve, reject) {
  73581. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  73582. resolve(scene);
  73583. }, onProgress, function (scene, message, exception) {
  73584. reject(exception || new Error(message));
  73585. }, pluginExtension);
  73586. });
  73587. };
  73588. /**
  73589. * Load a scene into an asset container
  73590. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73591. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73592. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  73593. * @param onSuccess a callback with the scene when import succeeds
  73594. * @param onProgress a callback with a progress event for each file being loaded
  73595. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73596. * @param pluginExtension the extension used to determine the plugin
  73597. * @returns The loaded plugin
  73598. */
  73599. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73600. if (sceneFilename === void 0) { sceneFilename = ""; }
  73601. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73602. if (onSuccess === void 0) { onSuccess = null; }
  73603. if (onProgress === void 0) { onProgress = null; }
  73604. if (onError === void 0) { onError = null; }
  73605. if (pluginExtension === void 0) { pluginExtension = null; }
  73606. if (!scene) {
  73607. BABYLON.Tools.Error("No scene available to load asset container to");
  73608. return null;
  73609. }
  73610. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73611. if (!fileInfo) {
  73612. return null;
  73613. }
  73614. var loadingToken = {};
  73615. scene._addPendingData(loadingToken);
  73616. var disposeHandler = function () {
  73617. scene._removePendingData(loadingToken);
  73618. };
  73619. var errorHandler = function (message, exception) {
  73620. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  73621. if (onError) {
  73622. onError(scene, errorMessage, exception);
  73623. }
  73624. else {
  73625. BABYLON.Tools.Error(errorMessage);
  73626. // should the exception be thrown?
  73627. }
  73628. disposeHandler();
  73629. };
  73630. var progressHandler = onProgress ? function (event) {
  73631. try {
  73632. onProgress(event);
  73633. }
  73634. catch (e) {
  73635. errorHandler("Error in onProgress callback", e);
  73636. }
  73637. } : undefined;
  73638. var successHandler = function (assets) {
  73639. if (onSuccess) {
  73640. try {
  73641. onSuccess(assets);
  73642. }
  73643. catch (e) {
  73644. errorHandler("Error in onSuccess callback", e);
  73645. }
  73646. }
  73647. scene._removePendingData(loadingToken);
  73648. };
  73649. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73650. if (plugin.loadAssetContainer) {
  73651. var syncedPlugin = plugin;
  73652. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  73653. if (!assetContainer) {
  73654. return;
  73655. }
  73656. scene.loadingPluginName = plugin.name;
  73657. successHandler(assetContainer);
  73658. }
  73659. else if (plugin.loadAssetContainerAsync) {
  73660. var asyncedPlugin = plugin;
  73661. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  73662. scene.loadingPluginName = plugin.name;
  73663. successHandler(assetContainer);
  73664. }).catch(function (error) {
  73665. errorHandler(error.message, error);
  73666. });
  73667. }
  73668. else {
  73669. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  73670. }
  73671. if (SceneLoader.ShowLoadingScreen) {
  73672. scene.executeWhenReady(function () {
  73673. scene.getEngine().hideLoadingUI();
  73674. });
  73675. }
  73676. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73677. };
  73678. /**
  73679. * Load a scene into an asset container
  73680. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73681. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73682. * @param scene is the instance of BABYLON.Scene to append to
  73683. * @param onProgress a callback with a progress event for each file being loaded
  73684. * @param pluginExtension the extension used to determine the plugin
  73685. * @returns The loaded asset container
  73686. */
  73687. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73688. if (sceneFilename === void 0) { sceneFilename = ""; }
  73689. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73690. if (onProgress === void 0) { onProgress = null; }
  73691. if (pluginExtension === void 0) { pluginExtension = null; }
  73692. return new Promise(function (resolve, reject) {
  73693. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  73694. resolve(assetContainer);
  73695. }, onProgress, function (scene, message, exception) {
  73696. reject(exception || new Error(message));
  73697. }, pluginExtension);
  73698. });
  73699. };
  73700. // Flags
  73701. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  73702. SceneLoader._ShowLoadingScreen = true;
  73703. SceneLoader._CleanBoneMatrixWeights = false;
  73704. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  73705. // Members
  73706. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  73707. SceneLoader._registeredPlugins = {};
  73708. return SceneLoader;
  73709. }());
  73710. BABYLON.SceneLoader = SceneLoader;
  73711. ;
  73712. })(BABYLON || (BABYLON = {}));
  73713. //# sourceMappingURL=babylon.sceneLoader.js.map
  73714. var BABYLON;
  73715. (function (BABYLON) {
  73716. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  73717. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  73718. var parsedMaterial = parsedData.materials[index];
  73719. if (parsedMaterial.id === id) {
  73720. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  73721. }
  73722. }
  73723. return null;
  73724. };
  73725. var isDescendantOf = function (mesh, names, hierarchyIds) {
  73726. for (var i in names) {
  73727. if (mesh.name === names[i]) {
  73728. hierarchyIds.push(mesh.id);
  73729. return true;
  73730. }
  73731. }
  73732. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  73733. hierarchyIds.push(mesh.id);
  73734. return true;
  73735. }
  73736. return false;
  73737. };
  73738. var logOperation = function (operation, producer) {
  73739. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  73740. };
  73741. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  73742. if (addToScene === void 0) { addToScene = false; }
  73743. var container = new BABYLON.AssetContainer(scene);
  73744. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  73745. // when SceneLoader.debugLogging = true (default), or exception encountered.
  73746. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  73747. // and avoid problems with multiple concurrent .babylon loads.
  73748. var log = "importScene has failed JSON parse";
  73749. try {
  73750. var parsedData = JSON.parse(data);
  73751. log = "";
  73752. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  73753. var index;
  73754. var cache;
  73755. // Lights
  73756. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  73757. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  73758. var parsedLight = parsedData.lights[index];
  73759. var light = BABYLON.Light.Parse(parsedLight, scene);
  73760. if (light) {
  73761. container.lights.push(light);
  73762. log += (index === 0 ? "\n\tLights:" : "");
  73763. log += "\n\t\t" + light.toString(fullDetails);
  73764. }
  73765. }
  73766. }
  73767. // Animations
  73768. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  73769. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  73770. var parsedAnimation = parsedData.animations[index];
  73771. var animation = BABYLON.Animation.Parse(parsedAnimation);
  73772. scene.animations.push(animation);
  73773. container.animations.push(animation);
  73774. log += (index === 0 ? "\n\tAnimations:" : "");
  73775. log += "\n\t\t" + animation.toString(fullDetails);
  73776. }
  73777. }
  73778. // Materials
  73779. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  73780. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  73781. var parsedMaterial = parsedData.materials[index];
  73782. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  73783. container.materials.push(mat);
  73784. log += (index === 0 ? "\n\tMaterials:" : "");
  73785. log += "\n\t\t" + mat.toString(fullDetails);
  73786. }
  73787. }
  73788. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  73789. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  73790. var parsedMultiMaterial = parsedData.multiMaterials[index];
  73791. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  73792. container.multiMaterials.push(mmat);
  73793. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  73794. log += "\n\t\t" + mmat.toString(fullDetails);
  73795. }
  73796. }
  73797. // Morph targets
  73798. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  73799. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  73800. var managerData = _a[_i];
  73801. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  73802. }
  73803. }
  73804. // Skeletons
  73805. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  73806. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  73807. var parsedSkeleton = parsedData.skeletons[index];
  73808. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  73809. container.skeletons.push(skeleton);
  73810. log += (index === 0 ? "\n\tSkeletons:" : "");
  73811. log += "\n\t\t" + skeleton.toString(fullDetails);
  73812. }
  73813. }
  73814. // Geometries
  73815. var geometries = parsedData.geometries;
  73816. if (geometries !== undefined && geometries !== null) {
  73817. var addedGeometry = new Array();
  73818. // Boxes
  73819. var boxes = geometries.boxes;
  73820. if (boxes !== undefined && boxes !== null) {
  73821. for (index = 0, cache = boxes.length; index < cache; index++) {
  73822. var parsedBox = boxes[index];
  73823. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  73824. }
  73825. }
  73826. // Spheres
  73827. var spheres = geometries.spheres;
  73828. if (spheres !== undefined && spheres !== null) {
  73829. for (index = 0, cache = spheres.length; index < cache; index++) {
  73830. var parsedSphere = spheres[index];
  73831. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  73832. }
  73833. }
  73834. // Cylinders
  73835. var cylinders = geometries.cylinders;
  73836. if (cylinders !== undefined && cylinders !== null) {
  73837. for (index = 0, cache = cylinders.length; index < cache; index++) {
  73838. var parsedCylinder = cylinders[index];
  73839. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  73840. }
  73841. }
  73842. // Toruses
  73843. var toruses = geometries.toruses;
  73844. if (toruses !== undefined && toruses !== null) {
  73845. for (index = 0, cache = toruses.length; index < cache; index++) {
  73846. var parsedTorus = toruses[index];
  73847. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  73848. }
  73849. }
  73850. // Grounds
  73851. var grounds = geometries.grounds;
  73852. if (grounds !== undefined && grounds !== null) {
  73853. for (index = 0, cache = grounds.length; index < cache; index++) {
  73854. var parsedGround = grounds[index];
  73855. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  73856. }
  73857. }
  73858. // Planes
  73859. var planes = geometries.planes;
  73860. if (planes !== undefined && planes !== null) {
  73861. for (index = 0, cache = planes.length; index < cache; index++) {
  73862. var parsedPlane = planes[index];
  73863. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  73864. }
  73865. }
  73866. // TorusKnots
  73867. var torusKnots = geometries.torusKnots;
  73868. if (torusKnots !== undefined && torusKnots !== null) {
  73869. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  73870. var parsedTorusKnot = torusKnots[index];
  73871. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  73872. }
  73873. }
  73874. // VertexData
  73875. var vertexData = geometries.vertexData;
  73876. if (vertexData !== undefined && vertexData !== null) {
  73877. for (index = 0, cache = vertexData.length; index < cache; index++) {
  73878. var parsedVertexData = vertexData[index];
  73879. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  73880. }
  73881. }
  73882. addedGeometry.forEach(function (g) {
  73883. if (g) {
  73884. container.geometries.push(g);
  73885. }
  73886. });
  73887. }
  73888. // Transform nodes
  73889. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  73890. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  73891. var parsedTransformNode = parsedData.transformNodes[index];
  73892. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  73893. container.transformNodes.push(node);
  73894. }
  73895. }
  73896. // Meshes
  73897. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  73898. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  73899. var parsedMesh = parsedData.meshes[index];
  73900. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  73901. container.meshes.push(mesh);
  73902. log += (index === 0 ? "\n\tMeshes:" : "");
  73903. log += "\n\t\t" + mesh.toString(fullDetails);
  73904. }
  73905. }
  73906. // Cameras
  73907. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  73908. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  73909. var parsedCamera = parsedData.cameras[index];
  73910. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  73911. container.cameras.push(camera);
  73912. log += (index === 0 ? "\n\tCameras:" : "");
  73913. log += "\n\t\t" + camera.toString(fullDetails);
  73914. }
  73915. }
  73916. // Animation Groups
  73917. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  73918. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  73919. var parsedAnimationGroup = parsedData.animationGroups[index];
  73920. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  73921. container.animationGroups.push(animationGroup);
  73922. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  73923. log += "\n\t\t" + animationGroup.toString(fullDetails);
  73924. }
  73925. }
  73926. // Browsing all the graph to connect the dots
  73927. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  73928. var camera = scene.cameras[index];
  73929. if (camera._waitingParentId) {
  73930. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  73931. camera._waitingParentId = null;
  73932. }
  73933. }
  73934. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  73935. var light_1 = scene.lights[index];
  73936. if (light_1 && light_1._waitingParentId) {
  73937. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  73938. light_1._waitingParentId = null;
  73939. }
  73940. }
  73941. // Connect parents & children and parse actions
  73942. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  73943. var transformNode = scene.transformNodes[index];
  73944. if (transformNode._waitingParentId) {
  73945. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  73946. transformNode._waitingParentId = null;
  73947. }
  73948. }
  73949. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  73950. var mesh = scene.meshes[index];
  73951. if (mesh._waitingParentId) {
  73952. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  73953. mesh._waitingParentId = null;
  73954. }
  73955. if (mesh._waitingActions) {
  73956. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  73957. mesh._waitingActions = null;
  73958. }
  73959. }
  73960. // freeze world matrix application
  73961. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  73962. var currentMesh = scene.meshes[index];
  73963. if (currentMesh._waitingFreezeWorldMatrix) {
  73964. currentMesh.freezeWorldMatrix();
  73965. currentMesh._waitingFreezeWorldMatrix = null;
  73966. }
  73967. else {
  73968. currentMesh.computeWorldMatrix(true);
  73969. }
  73970. }
  73971. // Lights exclusions / inclusions
  73972. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  73973. var light_2 = scene.lights[index];
  73974. // Excluded check
  73975. if (light_2._excludedMeshesIds.length > 0) {
  73976. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  73977. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  73978. if (excludedMesh) {
  73979. light_2.excludedMeshes.push(excludedMesh);
  73980. }
  73981. }
  73982. light_2._excludedMeshesIds = [];
  73983. }
  73984. // Included check
  73985. if (light_2._includedOnlyMeshesIds.length > 0) {
  73986. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  73987. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  73988. if (includedOnlyMesh) {
  73989. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  73990. }
  73991. }
  73992. light_2._includedOnlyMeshesIds = [];
  73993. }
  73994. }
  73995. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  73996. // Actions (scene)
  73997. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  73998. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  73999. }
  74000. if (!addToScene) {
  74001. container.removeAllFromScene();
  74002. }
  74003. }
  74004. catch (err) {
  74005. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74006. if (onError) {
  74007. onError(msg, err);
  74008. }
  74009. else {
  74010. BABYLON.Tools.Log(msg);
  74011. throw err;
  74012. }
  74013. }
  74014. finally {
  74015. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74016. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74017. }
  74018. }
  74019. return container;
  74020. };
  74021. BABYLON.SceneLoader.RegisterPlugin({
  74022. name: "babylon.js",
  74023. extensions: ".babylon",
  74024. canDirectLoad: function (data) {
  74025. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74026. return true;
  74027. }
  74028. return false;
  74029. },
  74030. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74031. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74032. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74033. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74034. // and avoid problems with multiple concurrent .babylon loads.
  74035. var log = "importMesh has failed JSON parse";
  74036. try {
  74037. var parsedData = JSON.parse(data);
  74038. log = "";
  74039. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74040. if (!meshesNames) {
  74041. meshesNames = null;
  74042. }
  74043. else if (!Array.isArray(meshesNames)) {
  74044. meshesNames = [meshesNames];
  74045. }
  74046. var hierarchyIds = new Array();
  74047. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74048. var loadedSkeletonsIds = [];
  74049. var loadedMaterialsIds = [];
  74050. var index;
  74051. var cache;
  74052. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74053. var parsedMesh = parsedData.meshes[index];
  74054. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74055. if (meshesNames !== null) {
  74056. // Remove found mesh name from list.
  74057. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74058. }
  74059. //Geometry?
  74060. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74061. //does the file contain geometries?
  74062. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74063. //find the correct geometry and add it to the scene
  74064. var found = false;
  74065. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74066. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74067. return;
  74068. }
  74069. else {
  74070. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74071. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74072. switch (geometryType) {
  74073. case "boxes":
  74074. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74075. break;
  74076. case "spheres":
  74077. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74078. break;
  74079. case "cylinders":
  74080. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74081. break;
  74082. case "toruses":
  74083. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74084. break;
  74085. case "grounds":
  74086. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74087. break;
  74088. case "planes":
  74089. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74090. break;
  74091. case "torusKnots":
  74092. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74093. break;
  74094. case "vertexData":
  74095. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  74096. break;
  74097. }
  74098. found = true;
  74099. }
  74100. });
  74101. }
  74102. });
  74103. if (found === false) {
  74104. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  74105. }
  74106. }
  74107. }
  74108. // Material ?
  74109. if (parsedMesh.materialId) {
  74110. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  74111. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74112. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  74113. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  74114. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  74115. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  74116. var subMatId = parsedMultiMaterial.materials[matIndex];
  74117. loadedMaterialsIds.push(subMatId);
  74118. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  74119. if (mat) {
  74120. log += "\n\tMaterial " + mat.toString(fullDetails);
  74121. }
  74122. }
  74123. loadedMaterialsIds.push(parsedMultiMaterial.id);
  74124. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74125. if (mmat) {
  74126. materialFound = true;
  74127. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  74128. }
  74129. break;
  74130. }
  74131. }
  74132. }
  74133. if (materialFound === false) {
  74134. loadedMaterialsIds.push(parsedMesh.materialId);
  74135. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  74136. if (!mat) {
  74137. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  74138. }
  74139. else {
  74140. log += "\n\tMaterial " + mat.toString(fullDetails);
  74141. }
  74142. }
  74143. }
  74144. // Skeleton ?
  74145. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74146. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  74147. if (skeletonAlreadyLoaded === false) {
  74148. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  74149. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  74150. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  74151. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74152. skeletons.push(skeleton);
  74153. loadedSkeletonsIds.push(parsedSkeleton.id);
  74154. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  74155. }
  74156. }
  74157. }
  74158. }
  74159. // Morph targets ?
  74160. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74161. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74162. var managerData = _a[_i];
  74163. BABYLON.MorphTargetManager.Parse(managerData, scene);
  74164. }
  74165. }
  74166. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74167. meshes.push(mesh);
  74168. log += "\n\tMesh " + mesh.toString(fullDetails);
  74169. }
  74170. }
  74171. // Connecting parents
  74172. var currentMesh;
  74173. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74174. currentMesh = scene.meshes[index];
  74175. if (currentMesh._waitingParentId) {
  74176. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  74177. currentMesh._waitingParentId = null;
  74178. }
  74179. }
  74180. // freeze and compute world matrix application
  74181. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74182. currentMesh = scene.meshes[index];
  74183. if (currentMesh._waitingFreezeWorldMatrix) {
  74184. currentMesh.freezeWorldMatrix();
  74185. currentMesh._waitingFreezeWorldMatrix = null;
  74186. }
  74187. else {
  74188. currentMesh.computeWorldMatrix(true);
  74189. }
  74190. }
  74191. }
  74192. // Particles
  74193. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  74194. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  74195. if (parser) {
  74196. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  74197. var parsedParticleSystem = parsedData.particleSystems[index];
  74198. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  74199. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  74200. }
  74201. }
  74202. }
  74203. }
  74204. return true;
  74205. }
  74206. catch (err) {
  74207. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  74208. if (onError) {
  74209. onError(msg, err);
  74210. }
  74211. else {
  74212. BABYLON.Tools.Log(msg);
  74213. throw err;
  74214. }
  74215. }
  74216. finally {
  74217. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74218. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74219. }
  74220. }
  74221. return false;
  74222. },
  74223. load: function (scene, data, rootUrl, onError) {
  74224. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74225. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74226. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74227. // and avoid problems with multiple concurrent .babylon loads.
  74228. var log = "importScene has failed JSON parse";
  74229. try {
  74230. var parsedData = JSON.parse(data);
  74231. log = "";
  74232. // Scene
  74233. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  74234. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  74235. }
  74236. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  74237. scene.autoClear = parsedData.autoClear;
  74238. }
  74239. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  74240. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  74241. }
  74242. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  74243. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  74244. }
  74245. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  74246. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  74247. }
  74248. // Fog
  74249. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  74250. scene.fogMode = parsedData.fogMode;
  74251. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  74252. scene.fogStart = parsedData.fogStart;
  74253. scene.fogEnd = parsedData.fogEnd;
  74254. scene.fogDensity = parsedData.fogDensity;
  74255. log += "\tFog mode for scene: ";
  74256. switch (scene.fogMode) {
  74257. // getters not compiling, so using hardcoded
  74258. case 1:
  74259. log += "exp\n";
  74260. break;
  74261. case 2:
  74262. log += "exp2\n";
  74263. break;
  74264. case 3:
  74265. log += "linear\n";
  74266. break;
  74267. }
  74268. }
  74269. //Physics
  74270. if (parsedData.physicsEnabled) {
  74271. var physicsPlugin;
  74272. if (parsedData.physicsEngine === "cannon") {
  74273. physicsPlugin = new BABYLON.CannonJSPlugin();
  74274. }
  74275. else if (parsedData.physicsEngine === "oimo") {
  74276. physicsPlugin = new BABYLON.OimoJSPlugin();
  74277. }
  74278. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  74279. //else - default engine, which is currently oimo
  74280. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  74281. scene.enablePhysics(physicsGravity, physicsPlugin);
  74282. }
  74283. // Metadata
  74284. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  74285. scene.metadata = parsedData.metadata;
  74286. }
  74287. //collisions, if defined. otherwise, default is true
  74288. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  74289. scene.collisionsEnabled = parsedData.collisionsEnabled;
  74290. }
  74291. scene.workerCollisions = !!parsedData.workerCollisions;
  74292. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  74293. if (!container) {
  74294. return false;
  74295. }
  74296. if (parsedData.autoAnimate) {
  74297. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  74298. }
  74299. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  74300. scene.setActiveCameraByID(parsedData.activeCameraID);
  74301. }
  74302. // Environment texture
  74303. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  74304. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  74305. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  74306. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  74307. if (parsedData.environmentTextureRotationY) {
  74308. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  74309. }
  74310. scene.environmentTexture = hdrTexture;
  74311. }
  74312. else {
  74313. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  74314. if (parsedData.environmentTextureRotationY) {
  74315. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  74316. }
  74317. scene.environmentTexture = cubeTexture;
  74318. }
  74319. if (parsedData.createDefaultSkybox === true) {
  74320. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  74321. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  74322. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  74323. }
  74324. }
  74325. // Finish
  74326. return true;
  74327. }
  74328. catch (err) {
  74329. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  74330. if (onError) {
  74331. onError(msg, err);
  74332. }
  74333. else {
  74334. BABYLON.Tools.Log(msg);
  74335. throw err;
  74336. }
  74337. }
  74338. finally {
  74339. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74340. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74341. }
  74342. }
  74343. return false;
  74344. },
  74345. loadAssetContainer: function (scene, data, rootUrl, onError) {
  74346. var container = loadAssetContainer(scene, data, rootUrl, onError);
  74347. return container;
  74348. }
  74349. });
  74350. })(BABYLON || (BABYLON = {}));
  74351. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  74352. var BABYLON;
  74353. (function (BABYLON) {
  74354. var FilesInput = /** @class */ (function () {
  74355. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  74356. this.onProcessFileCallback = function () { return true; };
  74357. this._engine = engine;
  74358. this._currentScene = scene;
  74359. this._sceneLoadedCallback = sceneLoadedCallback;
  74360. this._progressCallback = progressCallback;
  74361. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  74362. this._textureLoadingCallback = textureLoadingCallback;
  74363. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  74364. this._onReloadCallback = onReloadCallback;
  74365. this._errorCallback = errorCallback;
  74366. }
  74367. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  74368. var _this = this;
  74369. if (elementToMonitor) {
  74370. this._elementToMonitor = elementToMonitor;
  74371. this._dragEnterHandler = function (e) { _this.drag(e); };
  74372. this._dragOverHandler = function (e) { _this.drag(e); };
  74373. this._dropHandler = function (e) { _this.drop(e); };
  74374. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  74375. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  74376. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  74377. }
  74378. };
  74379. FilesInput.prototype.dispose = function () {
  74380. if (!this._elementToMonitor) {
  74381. return;
  74382. }
  74383. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  74384. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  74385. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  74386. };
  74387. FilesInput.prototype.renderFunction = function () {
  74388. if (this._additionalRenderLoopLogicCallback) {
  74389. this._additionalRenderLoopLogicCallback();
  74390. }
  74391. if (this._currentScene) {
  74392. if (this._textureLoadingCallback) {
  74393. var remaining = this._currentScene.getWaitingItemsCount();
  74394. if (remaining > 0) {
  74395. this._textureLoadingCallback(remaining);
  74396. }
  74397. }
  74398. this._currentScene.render();
  74399. }
  74400. };
  74401. FilesInput.prototype.drag = function (e) {
  74402. e.stopPropagation();
  74403. e.preventDefault();
  74404. };
  74405. FilesInput.prototype.drop = function (eventDrop) {
  74406. eventDrop.stopPropagation();
  74407. eventDrop.preventDefault();
  74408. this.loadFiles(eventDrop);
  74409. };
  74410. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  74411. var _this = this;
  74412. var reader = folder.createReader();
  74413. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  74414. reader.readEntries(function (entries) {
  74415. remaining.count += entries.length;
  74416. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  74417. var entry = entries_1[_i];
  74418. if (entry.isFile) {
  74419. entry.file(function (file) {
  74420. file.correctName = relativePath + file.name;
  74421. files.push(file);
  74422. if (--remaining.count === 0) {
  74423. callback();
  74424. }
  74425. });
  74426. }
  74427. else if (entry.isDirectory) {
  74428. _this._traverseFolder(entry, files, remaining, callback);
  74429. }
  74430. }
  74431. if (--remaining.count) {
  74432. callback();
  74433. }
  74434. });
  74435. };
  74436. FilesInput.prototype._processFiles = function (files) {
  74437. for (var i = 0; i < files.length; i++) {
  74438. var name = files[i].correctName.toLowerCase();
  74439. var extension = name.split('.').pop();
  74440. if (!this.onProcessFileCallback(files[i], name, extension)) {
  74441. continue;
  74442. }
  74443. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  74444. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  74445. this._sceneFileToLoad = files[i];
  74446. }
  74447. FilesInput.FilesToLoad[name] = files[i];
  74448. }
  74449. };
  74450. FilesInput.prototype.loadFiles = function (event) {
  74451. var _this = this;
  74452. // Handling data transfer via drag'n'drop
  74453. if (event && event.dataTransfer && event.dataTransfer.files) {
  74454. this._filesToLoad = event.dataTransfer.files;
  74455. }
  74456. // Handling files from input files
  74457. if (event && event.target && event.target.files) {
  74458. this._filesToLoad = event.target.files;
  74459. }
  74460. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  74461. return;
  74462. }
  74463. if (this._startingProcessingFilesCallback) {
  74464. this._startingProcessingFilesCallback(this._filesToLoad);
  74465. }
  74466. if (this._filesToLoad && this._filesToLoad.length > 0) {
  74467. var files_1 = new Array();
  74468. var folders = [];
  74469. var items = event.dataTransfer ? event.dataTransfer.items : null;
  74470. for (var i = 0; i < this._filesToLoad.length; i++) {
  74471. var fileToLoad = this._filesToLoad[i];
  74472. var name_1 = fileToLoad.name.toLowerCase();
  74473. var entry = void 0;
  74474. fileToLoad.correctName = name_1;
  74475. if (items) {
  74476. var item = items[i];
  74477. if (item.getAsEntry) {
  74478. entry = item.getAsEntry();
  74479. }
  74480. else if (item.webkitGetAsEntry) {
  74481. entry = item.webkitGetAsEntry();
  74482. }
  74483. }
  74484. if (!entry) {
  74485. files_1.push(fileToLoad);
  74486. }
  74487. else {
  74488. if (entry.isDirectory) {
  74489. folders.push(entry);
  74490. }
  74491. else {
  74492. files_1.push(fileToLoad);
  74493. }
  74494. }
  74495. }
  74496. if (folders.length === 0) {
  74497. this._processFiles(files_1);
  74498. this._processReload();
  74499. }
  74500. else {
  74501. var remaining = { count: folders.length };
  74502. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  74503. var folder = folders_1[_i];
  74504. this._traverseFolder(folder, files_1, remaining, function () {
  74505. _this._processFiles(files_1);
  74506. if (remaining.count === 0) {
  74507. _this._processReload();
  74508. }
  74509. });
  74510. }
  74511. }
  74512. }
  74513. };
  74514. FilesInput.prototype._processReload = function () {
  74515. if (this._onReloadCallback) {
  74516. this._onReloadCallback(this._sceneFileToLoad);
  74517. }
  74518. else {
  74519. this.reload();
  74520. }
  74521. };
  74522. FilesInput.prototype.reload = function () {
  74523. var _this = this;
  74524. // If a scene file has been provided
  74525. if (this._sceneFileToLoad) {
  74526. if (this._currentScene) {
  74527. if (BABYLON.Tools.errorsCount > 0) {
  74528. BABYLON.Tools.ClearLogCache();
  74529. }
  74530. this._engine.stopRenderLoop();
  74531. }
  74532. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  74533. if (_this._progressCallback) {
  74534. _this._progressCallback(progress);
  74535. }
  74536. }).then(function (scene) {
  74537. if (_this._currentScene) {
  74538. _this._currentScene.dispose();
  74539. }
  74540. _this._currentScene = scene;
  74541. if (_this._sceneLoadedCallback) {
  74542. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  74543. }
  74544. // Wait for textures and shaders to be ready
  74545. _this._currentScene.executeWhenReady(function () {
  74546. _this._engine.runRenderLoop(function () {
  74547. _this.renderFunction();
  74548. });
  74549. });
  74550. }).catch(function (error) {
  74551. if (_this._errorCallback) {
  74552. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  74553. }
  74554. });
  74555. }
  74556. else {
  74557. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  74558. }
  74559. };
  74560. FilesInput.FilesToLoad = {};
  74561. return FilesInput;
  74562. }());
  74563. BABYLON.FilesInput = FilesInput;
  74564. })(BABYLON || (BABYLON = {}));
  74565. //# sourceMappingURL=babylon.filesInput.js.map
  74566. var BABYLON;
  74567. (function (BABYLON) {
  74568. var Tags = /** @class */ (function () {
  74569. function Tags() {
  74570. }
  74571. Tags.EnableFor = function (obj) {
  74572. obj._tags = obj._tags || {};
  74573. obj.hasTags = function () {
  74574. return Tags.HasTags(obj);
  74575. };
  74576. obj.addTags = function (tagsString) {
  74577. return Tags.AddTagsTo(obj, tagsString);
  74578. };
  74579. obj.removeTags = function (tagsString) {
  74580. return Tags.RemoveTagsFrom(obj, tagsString);
  74581. };
  74582. obj.matchesTagsQuery = function (tagsQuery) {
  74583. return Tags.MatchesQuery(obj, tagsQuery);
  74584. };
  74585. };
  74586. Tags.DisableFor = function (obj) {
  74587. delete obj._tags;
  74588. delete obj.hasTags;
  74589. delete obj.addTags;
  74590. delete obj.removeTags;
  74591. delete obj.matchesTagsQuery;
  74592. };
  74593. Tags.HasTags = function (obj) {
  74594. if (!obj._tags) {
  74595. return false;
  74596. }
  74597. return !BABYLON.Tools.IsEmpty(obj._tags);
  74598. };
  74599. Tags.GetTags = function (obj, asString) {
  74600. if (asString === void 0) { asString = true; }
  74601. if (!obj._tags) {
  74602. return null;
  74603. }
  74604. if (asString) {
  74605. var tagsArray = [];
  74606. for (var tag in obj._tags) {
  74607. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  74608. tagsArray.push(tag);
  74609. }
  74610. }
  74611. return tagsArray.join(" ");
  74612. }
  74613. else {
  74614. return obj._tags;
  74615. }
  74616. };
  74617. // the tags 'true' and 'false' are reserved and cannot be used as tags
  74618. // a tag cannot start with '||', '&&', and '!'
  74619. // it cannot contain whitespaces
  74620. Tags.AddTagsTo = function (obj, tagsString) {
  74621. if (!tagsString) {
  74622. return;
  74623. }
  74624. if (typeof tagsString !== "string") {
  74625. return;
  74626. }
  74627. var tags = tagsString.split(" ");
  74628. tags.forEach(function (tag, index, array) {
  74629. Tags._AddTagTo(obj, tag);
  74630. });
  74631. };
  74632. Tags._AddTagTo = function (obj, tag) {
  74633. tag = tag.trim();
  74634. if (tag === "" || tag === "true" || tag === "false") {
  74635. return;
  74636. }
  74637. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  74638. return;
  74639. }
  74640. Tags.EnableFor(obj);
  74641. obj._tags[tag] = true;
  74642. };
  74643. Tags.RemoveTagsFrom = function (obj, tagsString) {
  74644. if (!Tags.HasTags(obj)) {
  74645. return;
  74646. }
  74647. var tags = tagsString.split(" ");
  74648. for (var t in tags) {
  74649. Tags._RemoveTagFrom(obj, tags[t]);
  74650. }
  74651. };
  74652. Tags._RemoveTagFrom = function (obj, tag) {
  74653. delete obj._tags[tag];
  74654. };
  74655. Tags.MatchesQuery = function (obj, tagsQuery) {
  74656. if (tagsQuery === undefined) {
  74657. return true;
  74658. }
  74659. if (tagsQuery === "") {
  74660. return Tags.HasTags(obj);
  74661. }
  74662. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  74663. };
  74664. return Tags;
  74665. }());
  74666. BABYLON.Tags = Tags;
  74667. })(BABYLON || (BABYLON = {}));
  74668. //# sourceMappingURL=babylon.tags.js.map
  74669. var BABYLON;
  74670. (function (BABYLON) {
  74671. /**
  74672. * Class used to evalaute queries containing `and` and `or` operators
  74673. */
  74674. var AndOrNotEvaluator = /** @class */ (function () {
  74675. function AndOrNotEvaluator() {
  74676. }
  74677. /**
  74678. * Evaluate a query
  74679. * @param query defines the query to evaluate
  74680. * @param evaluateCallback defines the callback used to filter result
  74681. * @returns true if the query matches
  74682. */
  74683. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  74684. if (!query.match(/\([^\(\)]*\)/g)) {
  74685. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  74686. }
  74687. else {
  74688. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  74689. // remove parenthesis
  74690. r = r.slice(1, r.length - 1);
  74691. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  74692. });
  74693. }
  74694. if (query === "true") {
  74695. return true;
  74696. }
  74697. if (query === "false") {
  74698. return false;
  74699. }
  74700. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  74701. };
  74702. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  74703. evaluateCallback = evaluateCallback || (function (r) {
  74704. return r === "true" ? true : false;
  74705. });
  74706. var result;
  74707. var or = parenthesisContent.split("||");
  74708. for (var i in or) {
  74709. if (or.hasOwnProperty(i)) {
  74710. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  74711. var and = ori.split("&&");
  74712. if (and.length > 1) {
  74713. for (var j = 0; j < and.length; ++j) {
  74714. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  74715. if (andj !== "true" && andj !== "false") {
  74716. if (andj[0] === "!") {
  74717. result = !evaluateCallback(andj.substring(1));
  74718. }
  74719. else {
  74720. result = evaluateCallback(andj);
  74721. }
  74722. }
  74723. else {
  74724. result = andj === "true" ? true : false;
  74725. }
  74726. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  74727. ori = "false";
  74728. break;
  74729. }
  74730. }
  74731. }
  74732. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  74733. result = true;
  74734. break;
  74735. }
  74736. // result equals false (or undefined)
  74737. if (ori !== "true" && ori !== "false") {
  74738. if (ori[0] === "!") {
  74739. result = !evaluateCallback(ori.substring(1));
  74740. }
  74741. else {
  74742. result = evaluateCallback(ori);
  74743. }
  74744. }
  74745. else {
  74746. result = ori === "true" ? true : false;
  74747. }
  74748. }
  74749. }
  74750. // the whole parenthesis scope is replaced by 'true' or 'false'
  74751. return result ? "true" : "false";
  74752. };
  74753. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  74754. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  74755. // remove whitespaces
  74756. r = r.replace(/[\s]/g, function () { return ""; });
  74757. return r.length % 2 ? "!" : "";
  74758. });
  74759. booleanString = booleanString.trim();
  74760. if (booleanString === "!true") {
  74761. booleanString = "false";
  74762. }
  74763. else if (booleanString === "!false") {
  74764. booleanString = "true";
  74765. }
  74766. return booleanString;
  74767. };
  74768. return AndOrNotEvaluator;
  74769. }());
  74770. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  74771. })(BABYLON || (BABYLON = {}));
  74772. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  74773. var BABYLON;
  74774. (function (BABYLON) {
  74775. /**
  74776. * Class used to enable access to IndexedDB
  74777. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  74778. */
  74779. var Database = /** @class */ (function () {
  74780. /**
  74781. * Creates a new Database
  74782. * @param urlToScene defines the url to load the scene
  74783. * @param callbackManifestChecked defines the callback to use when manifest is checked
  74784. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  74785. */
  74786. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  74787. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  74788. var _this = this;
  74789. // Handling various flavors of prefixed version of IndexedDB
  74790. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  74791. this.callbackManifestChecked = callbackManifestChecked;
  74792. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  74793. this.db = null;
  74794. this._enableSceneOffline = false;
  74795. this._enableTexturesOffline = false;
  74796. this.manifestVersionFound = 0;
  74797. this.mustUpdateRessources = false;
  74798. this.hasReachedQuota = false;
  74799. if (!Database.IDBStorageEnabled) {
  74800. this.callbackManifestChecked(true);
  74801. }
  74802. else {
  74803. if (disableManifestCheck) {
  74804. this._enableSceneOffline = true;
  74805. this._enableTexturesOffline = true;
  74806. this.manifestVersionFound = 1;
  74807. BABYLON.Tools.SetImmediate(function () {
  74808. _this.callbackManifestChecked(true);
  74809. });
  74810. }
  74811. else {
  74812. this._checkManifestFile();
  74813. }
  74814. }
  74815. }
  74816. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  74817. /**
  74818. * Gets a boolean indicating if scene must be saved in the database
  74819. */
  74820. get: function () {
  74821. return this._enableSceneOffline;
  74822. },
  74823. enumerable: true,
  74824. configurable: true
  74825. });
  74826. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  74827. /**
  74828. * Gets a boolean indicating if textures must be saved in the database
  74829. */
  74830. get: function () {
  74831. return this._enableTexturesOffline;
  74832. },
  74833. enumerable: true,
  74834. configurable: true
  74835. });
  74836. Database.prototype._checkManifestFile = function () {
  74837. var _this = this;
  74838. var noManifestFile = function () {
  74839. _this._enableSceneOffline = false;
  74840. _this._enableTexturesOffline = false;
  74841. _this.callbackManifestChecked(false);
  74842. };
  74843. var timeStampUsed = false;
  74844. var manifestURL = this.currentSceneUrl + ".manifest";
  74845. var xhr = new XMLHttpRequest();
  74846. if (navigator.onLine) {
  74847. // Adding a timestamp to by-pass browsers' cache
  74848. timeStampUsed = true;
  74849. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  74850. }
  74851. xhr.open("GET", manifestURL, true);
  74852. xhr.addEventListener("load", function () {
  74853. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74854. try {
  74855. var manifestFile = JSON.parse(xhr.response);
  74856. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  74857. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  74858. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  74859. _this.manifestVersionFound = manifestFile.version;
  74860. }
  74861. if (_this.callbackManifestChecked) {
  74862. _this.callbackManifestChecked(true);
  74863. }
  74864. }
  74865. catch (ex) {
  74866. noManifestFile();
  74867. }
  74868. }
  74869. else {
  74870. noManifestFile();
  74871. }
  74872. }, false);
  74873. xhr.addEventListener("error", function (event) {
  74874. if (timeStampUsed) {
  74875. timeStampUsed = false;
  74876. // Let's retry without the timeStamp
  74877. // It could fail when coupled with HTML5 Offline API
  74878. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  74879. xhr.open("GET", retryManifestURL, true);
  74880. xhr.send();
  74881. }
  74882. else {
  74883. noManifestFile();
  74884. }
  74885. }, false);
  74886. try {
  74887. xhr.send();
  74888. }
  74889. catch (ex) {
  74890. BABYLON.Tools.Error("Error on XHR send request.");
  74891. this.callbackManifestChecked(false);
  74892. }
  74893. };
  74894. /**
  74895. * Open the database and make it available
  74896. * @param successCallback defines the callback to call on success
  74897. * @param errorCallback defines the callback to call on error
  74898. */
  74899. Database.prototype.openAsync = function (successCallback, errorCallback) {
  74900. var _this = this;
  74901. var handleError = function () {
  74902. _this.isSupported = false;
  74903. if (errorCallback)
  74904. errorCallback();
  74905. };
  74906. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  74907. // Your browser doesn't support IndexedDB
  74908. this.isSupported = false;
  74909. if (errorCallback)
  74910. errorCallback();
  74911. }
  74912. else {
  74913. // If the DB hasn't been opened or created yet
  74914. if (!this.db) {
  74915. this.hasReachedQuota = false;
  74916. this.isSupported = true;
  74917. var request = this.idbFactory.open("babylonjs", 1);
  74918. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  74919. request.onerror = function (event) {
  74920. handleError();
  74921. };
  74922. // executes when a version change transaction cannot complete due to other active transactions
  74923. request.onblocked = function (event) {
  74924. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  74925. handleError();
  74926. };
  74927. // DB has been opened successfully
  74928. request.onsuccess = function (event) {
  74929. _this.db = request.result;
  74930. successCallback();
  74931. };
  74932. // Initialization of the DB. Creating Scenes & Textures stores
  74933. request.onupgradeneeded = function (event) {
  74934. _this.db = (event.target).result;
  74935. if (_this.db) {
  74936. try {
  74937. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  74938. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  74939. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  74940. }
  74941. catch (ex) {
  74942. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  74943. handleError();
  74944. }
  74945. }
  74946. };
  74947. }
  74948. // DB has already been created and opened
  74949. else {
  74950. if (successCallback)
  74951. successCallback();
  74952. }
  74953. }
  74954. };
  74955. /**
  74956. * Loads an image from the database
  74957. * @param url defines the url to load from
  74958. * @param image defines the target DOM image
  74959. */
  74960. Database.prototype.loadImageFromDB = function (url, image) {
  74961. var _this = this;
  74962. var completeURL = Database._ReturnFullUrlLocation(url);
  74963. var saveAndLoadImage = function () {
  74964. if (!_this.hasReachedQuota && _this.db !== null) {
  74965. // the texture is not yet in the DB, let's try to save it
  74966. _this._saveImageIntoDBAsync(completeURL, image);
  74967. }
  74968. // If the texture is not in the DB and we've reached the DB quota limit
  74969. // let's load it directly from the web
  74970. else {
  74971. image.src = url;
  74972. }
  74973. };
  74974. if (!this.mustUpdateRessources) {
  74975. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  74976. }
  74977. // First time we're download the images or update requested in the manifest file by a version change
  74978. else {
  74979. saveAndLoadImage();
  74980. }
  74981. };
  74982. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  74983. if (this.isSupported && this.db !== null) {
  74984. var texture;
  74985. var transaction = this.db.transaction(["textures"]);
  74986. transaction.onabort = function (event) {
  74987. image.src = url;
  74988. };
  74989. transaction.oncomplete = function (event) {
  74990. var blobTextureURL;
  74991. if (texture) {
  74992. var URL = window.URL || window.webkitURL;
  74993. blobTextureURL = URL.createObjectURL(texture.data);
  74994. image.onerror = function () {
  74995. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  74996. image.src = url;
  74997. };
  74998. image.src = blobTextureURL;
  74999. }
  75000. else {
  75001. notInDBCallback();
  75002. }
  75003. };
  75004. var getRequest = transaction.objectStore("textures").get(url);
  75005. getRequest.onsuccess = function (event) {
  75006. texture = (event.target).result;
  75007. };
  75008. getRequest.onerror = function (event) {
  75009. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  75010. image.src = url;
  75011. };
  75012. }
  75013. else {
  75014. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75015. image.src = url;
  75016. }
  75017. };
  75018. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  75019. var _this = this;
  75020. if (this.isSupported) {
  75021. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  75022. var generateBlobUrl = function () {
  75023. var blobTextureURL;
  75024. if (blob) {
  75025. var URL = window.URL || window.webkitURL;
  75026. try {
  75027. blobTextureURL = URL.createObjectURL(blob);
  75028. }
  75029. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  75030. catch (ex) {
  75031. blobTextureURL = URL.createObjectURL(blob);
  75032. }
  75033. }
  75034. if (blobTextureURL) {
  75035. image.src = blobTextureURL;
  75036. }
  75037. };
  75038. if (Database.IsUASupportingBlobStorage) { // Create XHR
  75039. var xhr = new XMLHttpRequest(), blob;
  75040. xhr.open("GET", url, true);
  75041. xhr.responseType = "blob";
  75042. xhr.addEventListener("load", function () {
  75043. if (xhr.status === 200 && _this.db) {
  75044. // Blob as response (XHR2)
  75045. blob = xhr.response;
  75046. var transaction = _this.db.transaction(["textures"], "readwrite");
  75047. // the transaction could abort because of a QuotaExceededError error
  75048. transaction.onabort = function (event) {
  75049. try {
  75050. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75051. var srcElement = (event.srcElement || event.target);
  75052. var error = srcElement.error;
  75053. if (error && error.name === "QuotaExceededError") {
  75054. _this.hasReachedQuota = true;
  75055. }
  75056. }
  75057. catch (ex) { }
  75058. generateBlobUrl();
  75059. };
  75060. transaction.oncomplete = function (event) {
  75061. generateBlobUrl();
  75062. };
  75063. var newTexture = { textureUrl: url, data: blob };
  75064. try {
  75065. // Put the blob into the dabase
  75066. var addRequest = transaction.objectStore("textures").put(newTexture);
  75067. addRequest.onsuccess = function (event) {
  75068. };
  75069. addRequest.onerror = function (event) {
  75070. generateBlobUrl();
  75071. };
  75072. }
  75073. catch (ex) {
  75074. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  75075. if (ex.code === 25) {
  75076. Database.IsUASupportingBlobStorage = false;
  75077. }
  75078. image.src = url;
  75079. }
  75080. }
  75081. else {
  75082. image.src = url;
  75083. }
  75084. }, false);
  75085. xhr.addEventListener("error", function (event) {
  75086. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  75087. image.src = url;
  75088. }, false);
  75089. xhr.send();
  75090. }
  75091. else {
  75092. image.src = url;
  75093. }
  75094. }
  75095. else {
  75096. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75097. image.src = url;
  75098. }
  75099. };
  75100. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  75101. var _this = this;
  75102. var updateVersion = function () {
  75103. // the version is not yet in the DB or we need to update it
  75104. _this._saveVersionIntoDBAsync(url, versionLoaded);
  75105. };
  75106. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  75107. };
  75108. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  75109. var _this = this;
  75110. if (this.isSupported && this.db) {
  75111. var version;
  75112. try {
  75113. var transaction = this.db.transaction(["versions"]);
  75114. transaction.oncomplete = function (event) {
  75115. if (version) {
  75116. // If the version in the JSON file is different from the version in DB
  75117. if (_this.manifestVersionFound !== version.data) {
  75118. _this.mustUpdateRessources = true;
  75119. updateInDBCallback();
  75120. }
  75121. else {
  75122. callback(version.data);
  75123. }
  75124. }
  75125. // version was not found in DB
  75126. else {
  75127. _this.mustUpdateRessources = true;
  75128. updateInDBCallback();
  75129. }
  75130. };
  75131. transaction.onabort = function (event) {
  75132. callback(-1);
  75133. };
  75134. var getRequest = transaction.objectStore("versions").get(url);
  75135. getRequest.onsuccess = function (event) {
  75136. version = (event.target).result;
  75137. };
  75138. getRequest.onerror = function (event) {
  75139. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  75140. callback(-1);
  75141. };
  75142. }
  75143. catch (ex) {
  75144. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  75145. callback(-1);
  75146. }
  75147. }
  75148. else {
  75149. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75150. callback(-1);
  75151. }
  75152. };
  75153. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  75154. var _this = this;
  75155. if (this.isSupported && !this.hasReachedQuota && this.db) {
  75156. try {
  75157. // Open a transaction to the database
  75158. var transaction = this.db.transaction(["versions"], "readwrite");
  75159. // the transaction could abort because of a QuotaExceededError error
  75160. transaction.onabort = function (event) {
  75161. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75162. var error = event.srcElement['error'];
  75163. if (error && error.name === "QuotaExceededError") {
  75164. _this.hasReachedQuota = true;
  75165. }
  75166. }
  75167. catch (ex) { }
  75168. callback(-1);
  75169. };
  75170. transaction.oncomplete = function (event) {
  75171. callback(_this.manifestVersionFound);
  75172. };
  75173. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  75174. // Put the scene into the database
  75175. var addRequest = transaction.objectStore("versions").put(newVersion);
  75176. addRequest.onsuccess = function (event) {
  75177. };
  75178. addRequest.onerror = function (event) {
  75179. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  75180. };
  75181. }
  75182. catch (ex) {
  75183. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  75184. callback(-1);
  75185. }
  75186. }
  75187. else {
  75188. callback(-1);
  75189. }
  75190. };
  75191. /**
  75192. * Loads a file from database
  75193. * @param url defines the URL to load from
  75194. * @param sceneLoaded defines a callback to call on success
  75195. * @param progressCallBack defines a callback to call when progress changed
  75196. * @param errorCallback defines a callback to call on error
  75197. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  75198. */
  75199. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  75200. var _this = this;
  75201. var completeUrl = Database._ReturnFullUrlLocation(url);
  75202. var saveAndLoadFile = function () {
  75203. // the scene is not yet in the DB, let's try to save it
  75204. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75205. };
  75206. this._checkVersionFromDB(completeUrl, function (version) {
  75207. if (version !== -1) {
  75208. if (!_this.mustUpdateRessources) {
  75209. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  75210. }
  75211. else {
  75212. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75213. }
  75214. }
  75215. else {
  75216. if (errorCallback) {
  75217. errorCallback();
  75218. }
  75219. }
  75220. });
  75221. };
  75222. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  75223. if (this.isSupported && this.db) {
  75224. var targetStore;
  75225. if (url.indexOf(".babylon") !== -1) {
  75226. targetStore = "scenes";
  75227. }
  75228. else {
  75229. targetStore = "textures";
  75230. }
  75231. var file;
  75232. var transaction = this.db.transaction([targetStore]);
  75233. transaction.oncomplete = function (event) {
  75234. if (file) {
  75235. callback(file.data);
  75236. }
  75237. // file was not found in DB
  75238. else {
  75239. notInDBCallback();
  75240. }
  75241. };
  75242. transaction.onabort = function (event) {
  75243. notInDBCallback();
  75244. };
  75245. var getRequest = transaction.objectStore(targetStore).get(url);
  75246. getRequest.onsuccess = function (event) {
  75247. file = (event.target).result;
  75248. };
  75249. getRequest.onerror = function (event) {
  75250. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  75251. notInDBCallback();
  75252. };
  75253. }
  75254. else {
  75255. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75256. callback();
  75257. }
  75258. };
  75259. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  75260. var _this = this;
  75261. if (this.isSupported) {
  75262. var targetStore;
  75263. if (url.indexOf(".babylon") !== -1) {
  75264. targetStore = "scenes";
  75265. }
  75266. else {
  75267. targetStore = "textures";
  75268. }
  75269. // Create XHR
  75270. var xhr = new XMLHttpRequest();
  75271. var fileData;
  75272. xhr.open("GET", url + "?" + Date.now(), true);
  75273. if (useArrayBuffer) {
  75274. xhr.responseType = "arraybuffer";
  75275. }
  75276. if (progressCallback) {
  75277. xhr.onprogress = progressCallback;
  75278. }
  75279. xhr.addEventListener("load", function () {
  75280. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  75281. // Blob as response (XHR2)
  75282. //fileData = xhr.responseText;
  75283. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  75284. if (!_this.hasReachedQuota && _this.db) {
  75285. // Open a transaction to the database
  75286. var transaction = _this.db.transaction([targetStore], "readwrite");
  75287. // the transaction could abort because of a QuotaExceededError error
  75288. transaction.onabort = function (event) {
  75289. try {
  75290. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75291. var error = event.srcElement['error'];
  75292. if (error && error.name === "QuotaExceededError") {
  75293. _this.hasReachedQuota = true;
  75294. }
  75295. }
  75296. catch (ex) { }
  75297. callback(fileData);
  75298. };
  75299. transaction.oncomplete = function (event) {
  75300. callback(fileData);
  75301. };
  75302. var newFile;
  75303. if (targetStore === "scenes") {
  75304. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  75305. }
  75306. else {
  75307. newFile = { textureUrl: url, data: fileData };
  75308. }
  75309. try {
  75310. // Put the scene into the database
  75311. var addRequest = transaction.objectStore(targetStore).put(newFile);
  75312. addRequest.onsuccess = function (event) {
  75313. };
  75314. addRequest.onerror = function (event) {
  75315. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  75316. };
  75317. }
  75318. catch (ex) {
  75319. callback(fileData);
  75320. }
  75321. }
  75322. else {
  75323. callback(fileData);
  75324. }
  75325. }
  75326. else {
  75327. if (xhr.status >= 400 && errorCallback) {
  75328. errorCallback(xhr);
  75329. }
  75330. else {
  75331. callback();
  75332. }
  75333. }
  75334. }, false);
  75335. xhr.addEventListener("error", function (event) {
  75336. BABYLON.Tools.Error("error on XHR request.");
  75337. callback();
  75338. }, false);
  75339. xhr.send();
  75340. }
  75341. else {
  75342. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75343. callback();
  75344. }
  75345. };
  75346. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  75347. Database.IsUASupportingBlobStorage = true;
  75348. /** Gets a boolean indicating if Database storate is enabled */
  75349. Database.IDBStorageEnabled = true;
  75350. Database._ParseURL = function (url) {
  75351. var a = document.createElement('a');
  75352. a.href = url;
  75353. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  75354. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  75355. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  75356. return absLocation;
  75357. };
  75358. Database._ReturnFullUrlLocation = function (url) {
  75359. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  75360. return (Database._ParseURL(window.location.href) + url);
  75361. }
  75362. else {
  75363. return url;
  75364. }
  75365. };
  75366. return Database;
  75367. }());
  75368. BABYLON.Database = Database;
  75369. })(BABYLON || (BABYLON = {}));
  75370. //# sourceMappingURL=babylon.database.js.map
  75371. var BABYLON;
  75372. (function (BABYLON) {
  75373. var FresnelParameters = /** @class */ (function () {
  75374. function FresnelParameters() {
  75375. this._isEnabled = true;
  75376. this.leftColor = BABYLON.Color3.White();
  75377. this.rightColor = BABYLON.Color3.Black();
  75378. this.bias = 0;
  75379. this.power = 1;
  75380. }
  75381. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  75382. get: function () {
  75383. return this._isEnabled;
  75384. },
  75385. set: function (value) {
  75386. if (this._isEnabled === value) {
  75387. return;
  75388. }
  75389. this._isEnabled = value;
  75390. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  75391. },
  75392. enumerable: true,
  75393. configurable: true
  75394. });
  75395. FresnelParameters.prototype.clone = function () {
  75396. var newFresnelParameters = new FresnelParameters();
  75397. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  75398. return newFresnelParameters;
  75399. };
  75400. FresnelParameters.prototype.serialize = function () {
  75401. var serializationObject = {};
  75402. serializationObject.isEnabled = this.isEnabled;
  75403. serializationObject.leftColor = this.leftColor.asArray();
  75404. serializationObject.rightColor = this.rightColor.asArray();
  75405. serializationObject.bias = this.bias;
  75406. serializationObject.power = this.power;
  75407. return serializationObject;
  75408. };
  75409. FresnelParameters.Parse = function (parsedFresnelParameters) {
  75410. var fresnelParameters = new FresnelParameters();
  75411. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  75412. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  75413. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  75414. fresnelParameters.bias = parsedFresnelParameters.bias;
  75415. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  75416. return fresnelParameters;
  75417. };
  75418. return FresnelParameters;
  75419. }());
  75420. BABYLON.FresnelParameters = FresnelParameters;
  75421. })(BABYLON || (BABYLON = {}));
  75422. //# sourceMappingURL=babylon.fresnelParameters.js.map
  75423. var BABYLON;
  75424. (function (BABYLON) {
  75425. var MultiMaterial = /** @class */ (function (_super) {
  75426. __extends(MultiMaterial, _super);
  75427. function MultiMaterial(name, scene) {
  75428. var _this = _super.call(this, name, scene, true) || this;
  75429. scene.multiMaterials.push(_this);
  75430. _this.subMaterials = new Array();
  75431. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  75432. return _this;
  75433. }
  75434. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  75435. get: function () {
  75436. return this._subMaterials;
  75437. },
  75438. set: function (value) {
  75439. this._subMaterials = value;
  75440. this._hookArray(value);
  75441. },
  75442. enumerable: true,
  75443. configurable: true
  75444. });
  75445. MultiMaterial.prototype._hookArray = function (array) {
  75446. var _this = this;
  75447. var oldPush = array.push;
  75448. array.push = function () {
  75449. var items = [];
  75450. for (var _i = 0; _i < arguments.length; _i++) {
  75451. items[_i] = arguments[_i];
  75452. }
  75453. var result = oldPush.apply(array, items);
  75454. _this._markAllSubMeshesAsTexturesDirty();
  75455. return result;
  75456. };
  75457. var oldSplice = array.splice;
  75458. array.splice = function (index, deleteCount) {
  75459. var deleted = oldSplice.apply(array, [index, deleteCount]);
  75460. _this._markAllSubMeshesAsTexturesDirty();
  75461. return deleted;
  75462. };
  75463. };
  75464. // Properties
  75465. MultiMaterial.prototype.getSubMaterial = function (index) {
  75466. if (index < 0 || index >= this.subMaterials.length) {
  75467. return this.getScene().defaultMaterial;
  75468. }
  75469. return this.subMaterials[index];
  75470. };
  75471. MultiMaterial.prototype.getActiveTextures = function () {
  75472. var _a;
  75473. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  75474. if (subMaterial) {
  75475. return subMaterial.getActiveTextures();
  75476. }
  75477. else {
  75478. return [];
  75479. }
  75480. }));
  75481. };
  75482. // Methods
  75483. MultiMaterial.prototype.getClassName = function () {
  75484. return "MultiMaterial";
  75485. };
  75486. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75487. for (var index = 0; index < this.subMaterials.length; index++) {
  75488. var subMaterial = this.subMaterials[index];
  75489. if (subMaterial) {
  75490. if (subMaterial.storeEffectOnSubMeshes) {
  75491. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  75492. return false;
  75493. }
  75494. continue;
  75495. }
  75496. if (!subMaterial.isReady(mesh)) {
  75497. return false;
  75498. }
  75499. }
  75500. }
  75501. return true;
  75502. };
  75503. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  75504. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  75505. for (var index = 0; index < this.subMaterials.length; index++) {
  75506. var subMaterial = null;
  75507. var current = this.subMaterials[index];
  75508. if (cloneChildren && current) {
  75509. subMaterial = current.clone(name + "-" + current.name);
  75510. }
  75511. else {
  75512. subMaterial = this.subMaterials[index];
  75513. }
  75514. newMultiMaterial.subMaterials.push(subMaterial);
  75515. }
  75516. return newMultiMaterial;
  75517. };
  75518. MultiMaterial.prototype.serialize = function () {
  75519. var serializationObject = {};
  75520. serializationObject.name = this.name;
  75521. serializationObject.id = this.id;
  75522. if (BABYLON.Tags) {
  75523. serializationObject.tags = BABYLON.Tags.GetTags(this);
  75524. }
  75525. serializationObject.materials = [];
  75526. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  75527. var subMat = this.subMaterials[matIndex];
  75528. if (subMat) {
  75529. serializationObject.materials.push(subMat.id);
  75530. }
  75531. else {
  75532. serializationObject.materials.push(null);
  75533. }
  75534. }
  75535. return serializationObject;
  75536. };
  75537. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75538. var scene = this.getScene();
  75539. if (!scene) {
  75540. return;
  75541. }
  75542. var index = scene.multiMaterials.indexOf(this);
  75543. if (index >= 0) {
  75544. scene.multiMaterials.splice(index, 1);
  75545. }
  75546. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  75547. };
  75548. return MultiMaterial;
  75549. }(BABYLON.Material));
  75550. BABYLON.MultiMaterial = MultiMaterial;
  75551. })(BABYLON || (BABYLON = {}));
  75552. //# sourceMappingURL=babylon.multiMaterial.js.map
  75553. var BABYLON;
  75554. (function (BABYLON) {
  75555. /**
  75556. * Manage the touch inputs to control the movement of a free camera.
  75557. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  75558. */
  75559. var FreeCameraTouchInput = /** @class */ (function () {
  75560. function FreeCameraTouchInput() {
  75561. /**
  75562. * Defines the touch sensibility for rotation.
  75563. * The higher the faster.
  75564. */
  75565. this.touchAngularSensibility = 200000.0;
  75566. /**
  75567. * Defines the touch sensibility for move.
  75568. * The higher the faster.
  75569. */
  75570. this.touchMoveSensibility = 250.0;
  75571. this._offsetX = null;
  75572. this._offsetY = null;
  75573. this._pointerPressed = new Array();
  75574. }
  75575. /**
  75576. * Attach the input controls to a specific dom element to get the input from.
  75577. * @param element Defines the element the controls should be listened from
  75578. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  75579. */
  75580. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  75581. var _this = this;
  75582. var previousPosition = null;
  75583. if (this._pointerInput === undefined) {
  75584. this._onLostFocus = function (evt) {
  75585. _this._offsetX = null;
  75586. _this._offsetY = null;
  75587. };
  75588. this._pointerInput = function (p, s) {
  75589. var evt = p.event;
  75590. if (evt.pointerType === "mouse") {
  75591. return;
  75592. }
  75593. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75594. if (!noPreventDefault) {
  75595. evt.preventDefault();
  75596. }
  75597. _this._pointerPressed.push(evt.pointerId);
  75598. if (_this._pointerPressed.length !== 1) {
  75599. return;
  75600. }
  75601. previousPosition = {
  75602. x: evt.clientX,
  75603. y: evt.clientY
  75604. };
  75605. }
  75606. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  75607. if (!noPreventDefault) {
  75608. evt.preventDefault();
  75609. }
  75610. var index = _this._pointerPressed.indexOf(evt.pointerId);
  75611. if (index === -1) {
  75612. return;
  75613. }
  75614. _this._pointerPressed.splice(index, 1);
  75615. if (index != 0) {
  75616. return;
  75617. }
  75618. previousPosition = null;
  75619. _this._offsetX = null;
  75620. _this._offsetY = null;
  75621. }
  75622. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  75623. if (!noPreventDefault) {
  75624. evt.preventDefault();
  75625. }
  75626. if (!previousPosition) {
  75627. return;
  75628. }
  75629. var index = _this._pointerPressed.indexOf(evt.pointerId);
  75630. if (index != 0) {
  75631. return;
  75632. }
  75633. _this._offsetX = evt.clientX - previousPosition.x;
  75634. _this._offsetY = -(evt.clientY - previousPosition.y);
  75635. }
  75636. };
  75637. }
  75638. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  75639. if (this._onLostFocus) {
  75640. element.addEventListener("blur", this._onLostFocus);
  75641. }
  75642. };
  75643. /**
  75644. * Detach the current controls from the specified dom element.
  75645. * @param element Defines the element to stop listening the inputs from
  75646. */
  75647. FreeCameraTouchInput.prototype.detachControl = function (element) {
  75648. if (this._pointerInput && element) {
  75649. if (this._observer) {
  75650. this.camera.getScene().onPointerObservable.remove(this._observer);
  75651. this._observer = null;
  75652. }
  75653. if (this._onLostFocus) {
  75654. element.removeEventListener("blur", this._onLostFocus);
  75655. this._onLostFocus = null;
  75656. }
  75657. this._pointerPressed = [];
  75658. this._offsetX = null;
  75659. this._offsetY = null;
  75660. }
  75661. };
  75662. /**
  75663. * Update the current camera state depending on the inputs that have been used this frame.
  75664. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  75665. */
  75666. FreeCameraTouchInput.prototype.checkInputs = function () {
  75667. if (this._offsetX && this._offsetY) {
  75668. var camera = this.camera;
  75669. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  75670. if (this._pointerPressed.length > 1) {
  75671. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  75672. }
  75673. else {
  75674. var speed = camera._computeLocalCameraSpeed();
  75675. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  75676. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  75677. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  75678. }
  75679. }
  75680. };
  75681. /**
  75682. * Gets the class name of the current intput.
  75683. * @returns the class name
  75684. */
  75685. FreeCameraTouchInput.prototype.getClassName = function () {
  75686. return "FreeCameraTouchInput";
  75687. };
  75688. /**
  75689. * Get the friendly name associated with the input class.
  75690. * @returns the input friendly name
  75691. */
  75692. FreeCameraTouchInput.prototype.getSimpleName = function () {
  75693. return "touch";
  75694. };
  75695. __decorate([
  75696. BABYLON.serialize()
  75697. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  75698. __decorate([
  75699. BABYLON.serialize()
  75700. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  75701. return FreeCameraTouchInput;
  75702. }());
  75703. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  75704. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  75705. })(BABYLON || (BABYLON = {}));
  75706. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  75707. var BABYLON;
  75708. (function (BABYLON) {
  75709. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  75710. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  75711. });
  75712. /**
  75713. * This represents a FPS type of camera controlled by touch.
  75714. * This is like a universal camera minus the Gamepad controls.
  75715. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  75716. */
  75717. var TouchCamera = /** @class */ (function (_super) {
  75718. __extends(TouchCamera, _super);
  75719. /**
  75720. * Instantiates a new touch camera.
  75721. * This represents a FPS type of camera controlled by touch.
  75722. * This is like a universal camera minus the Gamepad controls.
  75723. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  75724. * @param name Define the name of the camera in the scene
  75725. * @param position Define the start position of the camera in the scene
  75726. * @param scene Define the scene the camera belongs to
  75727. */
  75728. function TouchCamera(name, position, scene) {
  75729. var _this = _super.call(this, name, position, scene) || this;
  75730. _this.inputs.addTouch();
  75731. _this._setupInputs();
  75732. return _this;
  75733. }
  75734. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  75735. /**
  75736. * Defines the touch sensibility for rotation.
  75737. * The higher the faster.
  75738. */
  75739. get: function () {
  75740. var touch = this.inputs.attached["touch"];
  75741. if (touch)
  75742. return touch.touchAngularSensibility;
  75743. return 0;
  75744. },
  75745. set: function (value) {
  75746. var touch = this.inputs.attached["touch"];
  75747. if (touch)
  75748. touch.touchAngularSensibility = value;
  75749. },
  75750. enumerable: true,
  75751. configurable: true
  75752. });
  75753. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  75754. /**
  75755. * Defines the touch sensibility for move.
  75756. * The higher the faster.
  75757. */
  75758. get: function () {
  75759. var touch = this.inputs.attached["touch"];
  75760. if (touch)
  75761. return touch.touchMoveSensibility;
  75762. return 0;
  75763. },
  75764. set: function (value) {
  75765. var touch = this.inputs.attached["touch"];
  75766. if (touch)
  75767. touch.touchMoveSensibility = value;
  75768. },
  75769. enumerable: true,
  75770. configurable: true
  75771. });
  75772. /**
  75773. * Gets the current object class name.
  75774. * @return the class name
  75775. */
  75776. TouchCamera.prototype.getClassName = function () {
  75777. return "TouchCamera";
  75778. };
  75779. /** @hidden */
  75780. TouchCamera.prototype._setupInputs = function () {
  75781. var mouse = this.inputs.attached["mouse"];
  75782. if (mouse) {
  75783. mouse.touchEnabled = false;
  75784. }
  75785. };
  75786. return TouchCamera;
  75787. }(BABYLON.FreeCamera));
  75788. BABYLON.TouchCamera = TouchCamera;
  75789. })(BABYLON || (BABYLON = {}));
  75790. //# sourceMappingURL=babylon.touchCamera.js.map
  75791. var BABYLON;
  75792. (function (BABYLON) {
  75793. var ProceduralTexture = /** @class */ (function (_super) {
  75794. __extends(ProceduralTexture, _super);
  75795. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  75796. if (fallbackTexture === void 0) { fallbackTexture = null; }
  75797. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75798. if (isCube === void 0) { isCube = false; }
  75799. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  75800. _this.isCube = isCube;
  75801. _this.isEnabled = true;
  75802. _this._currentRefreshId = -1;
  75803. _this._refreshRate = 1;
  75804. /**
  75805. * Event raised when the texture is generated
  75806. */
  75807. _this.onGeneratedObservable = new BABYLON.Observable();
  75808. _this._vertexBuffers = {};
  75809. _this._uniforms = new Array();
  75810. _this._samplers = new Array();
  75811. /** @hidden */
  75812. _this._textures = {};
  75813. _this._floats = {};
  75814. _this._ints = {};
  75815. _this._floatsArrays = {};
  75816. _this._colors3 = {};
  75817. _this._colors4 = {};
  75818. _this._vectors2 = {};
  75819. _this._vectors3 = {};
  75820. _this._matrices = {};
  75821. _this._fallbackTextureUsed = false;
  75822. _this._cachedDefines = "";
  75823. _this._contentUpdateId = -1;
  75824. scene = _this.getScene();
  75825. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  75826. if (!component) {
  75827. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  75828. scene._addComponent(component);
  75829. }
  75830. scene.proceduralTextures.push(_this);
  75831. _this._engine = scene.getEngine();
  75832. _this.name = name;
  75833. _this.isRenderTarget = true;
  75834. _this._size = size;
  75835. _this._generateMipMaps = generateMipMaps;
  75836. _this.setFragment(fragment);
  75837. _this._fallbackTexture = fallbackTexture;
  75838. if (isCube) {
  75839. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  75840. _this.setFloat("face", 0);
  75841. }
  75842. else {
  75843. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  75844. }
  75845. // VBO
  75846. var vertices = [];
  75847. vertices.push(1, 1);
  75848. vertices.push(-1, 1);
  75849. vertices.push(-1, -1);
  75850. vertices.push(1, -1);
  75851. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75852. _this._createIndexBuffer();
  75853. return _this;
  75854. }
  75855. /**
  75856. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  75857. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  75858. */
  75859. ProceduralTexture.prototype.getContent = function () {
  75860. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  75861. return this._contentData;
  75862. }
  75863. this._contentData = this.readPixels(0, 0, this._contentData);
  75864. this._contentUpdateId = this._currentRefreshId;
  75865. return this._contentData;
  75866. };
  75867. ProceduralTexture.prototype._createIndexBuffer = function () {
  75868. var engine = this._engine;
  75869. // Indices
  75870. var indices = [];
  75871. indices.push(0);
  75872. indices.push(1);
  75873. indices.push(2);
  75874. indices.push(0);
  75875. indices.push(2);
  75876. indices.push(3);
  75877. this._indexBuffer = engine.createIndexBuffer(indices);
  75878. };
  75879. /** @hidden */
  75880. ProceduralTexture.prototype._rebuild = function () {
  75881. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75882. if (vb) {
  75883. vb._rebuild();
  75884. }
  75885. this._createIndexBuffer();
  75886. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  75887. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  75888. }
  75889. };
  75890. ProceduralTexture.prototype.reset = function () {
  75891. if (this._effect === undefined) {
  75892. return;
  75893. }
  75894. var engine = this._engine;
  75895. engine._releaseEffect(this._effect);
  75896. };
  75897. ProceduralTexture.prototype._getDefines = function () {
  75898. return "";
  75899. };
  75900. ProceduralTexture.prototype.isReady = function () {
  75901. var _this = this;
  75902. var engine = this._engine;
  75903. var shaders;
  75904. if (!this._fragment) {
  75905. return false;
  75906. }
  75907. if (this._fallbackTextureUsed) {
  75908. return true;
  75909. }
  75910. var defines = this._getDefines();
  75911. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  75912. return true;
  75913. }
  75914. if (this._fragment.fragmentElement !== undefined) {
  75915. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  75916. }
  75917. else {
  75918. shaders = { vertex: "procedural", fragment: this._fragment };
  75919. }
  75920. this._cachedDefines = defines;
  75921. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  75922. _this.releaseInternalTexture();
  75923. if (_this._fallbackTexture) {
  75924. _this._texture = _this._fallbackTexture._texture;
  75925. if (_this._texture) {
  75926. _this._texture.incrementReferences();
  75927. }
  75928. }
  75929. _this._fallbackTextureUsed = true;
  75930. });
  75931. return this._effect.isReady();
  75932. };
  75933. ProceduralTexture.prototype.resetRefreshCounter = function () {
  75934. this._currentRefreshId = -1;
  75935. };
  75936. ProceduralTexture.prototype.setFragment = function (fragment) {
  75937. this._fragment = fragment;
  75938. };
  75939. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  75940. get: function () {
  75941. return this._refreshRate;
  75942. },
  75943. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  75944. set: function (value) {
  75945. this._refreshRate = value;
  75946. this.resetRefreshCounter();
  75947. },
  75948. enumerable: true,
  75949. configurable: true
  75950. });
  75951. /** @hidden */
  75952. ProceduralTexture.prototype._shouldRender = function () {
  75953. if (!this.isEnabled || !this.isReady() || !this._texture) {
  75954. if (this._texture) {
  75955. this._texture.isReady = false;
  75956. }
  75957. return false;
  75958. }
  75959. if (this._fallbackTextureUsed) {
  75960. return false;
  75961. }
  75962. if (this._currentRefreshId === -1) { // At least render once
  75963. this._currentRefreshId = 1;
  75964. return true;
  75965. }
  75966. if (this.refreshRate === this._currentRefreshId) {
  75967. this._currentRefreshId = 1;
  75968. return true;
  75969. }
  75970. this._currentRefreshId++;
  75971. return false;
  75972. };
  75973. ProceduralTexture.prototype.getRenderSize = function () {
  75974. return this._size;
  75975. };
  75976. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  75977. if (this._fallbackTextureUsed) {
  75978. return;
  75979. }
  75980. this.releaseInternalTexture();
  75981. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  75982. // Update properties
  75983. this._size = size;
  75984. this._generateMipMaps = generateMipMaps;
  75985. };
  75986. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  75987. if (this._uniforms.indexOf(uniformName) === -1) {
  75988. this._uniforms.push(uniformName);
  75989. }
  75990. };
  75991. ProceduralTexture.prototype.setTexture = function (name, texture) {
  75992. if (this._samplers.indexOf(name) === -1) {
  75993. this._samplers.push(name);
  75994. }
  75995. this._textures[name] = texture;
  75996. return this;
  75997. };
  75998. ProceduralTexture.prototype.setFloat = function (name, value) {
  75999. this._checkUniform(name);
  76000. this._floats[name] = value;
  76001. return this;
  76002. };
  76003. /**
  76004. * Set the value of an uniform to an integer value
  76005. * @param name defines the name of the uniform
  76006. * @param value defines the value to set
  76007. * @returns the current procedural texture
  76008. */
  76009. ProceduralTexture.prototype.setInt = function (name, value) {
  76010. this._checkUniform(name);
  76011. this._ints[name] = value;
  76012. return this;
  76013. };
  76014. ProceduralTexture.prototype.setFloats = function (name, value) {
  76015. this._checkUniform(name);
  76016. this._floatsArrays[name] = value;
  76017. return this;
  76018. };
  76019. ProceduralTexture.prototype.setColor3 = function (name, value) {
  76020. this._checkUniform(name);
  76021. this._colors3[name] = value;
  76022. return this;
  76023. };
  76024. ProceduralTexture.prototype.setColor4 = function (name, value) {
  76025. this._checkUniform(name);
  76026. this._colors4[name] = value;
  76027. return this;
  76028. };
  76029. ProceduralTexture.prototype.setVector2 = function (name, value) {
  76030. this._checkUniform(name);
  76031. this._vectors2[name] = value;
  76032. return this;
  76033. };
  76034. ProceduralTexture.prototype.setVector3 = function (name, value) {
  76035. this._checkUniform(name);
  76036. this._vectors3[name] = value;
  76037. return this;
  76038. };
  76039. ProceduralTexture.prototype.setMatrix = function (name, value) {
  76040. this._checkUniform(name);
  76041. this._matrices[name] = value;
  76042. return this;
  76043. };
  76044. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76045. var scene = this.getScene();
  76046. if (!scene) {
  76047. return;
  76048. }
  76049. var engine = this._engine;
  76050. // Render
  76051. engine.enableEffect(this._effect);
  76052. engine.setState(false);
  76053. // Texture
  76054. for (var name in this._textures) {
  76055. this._effect.setTexture(name, this._textures[name]);
  76056. }
  76057. // Float
  76058. for (name in this._ints) {
  76059. this._effect.setInt(name, this._ints[name]);
  76060. }
  76061. // Float
  76062. for (name in this._floats) {
  76063. this._effect.setFloat(name, this._floats[name]);
  76064. }
  76065. // Floats
  76066. for (name in this._floatsArrays) {
  76067. this._effect.setArray(name, this._floatsArrays[name]);
  76068. }
  76069. // Color3
  76070. for (name in this._colors3) {
  76071. this._effect.setColor3(name, this._colors3[name]);
  76072. }
  76073. // Color4
  76074. for (name in this._colors4) {
  76075. var color = this._colors4[name];
  76076. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  76077. }
  76078. // Vector2
  76079. for (name in this._vectors2) {
  76080. this._effect.setVector2(name, this._vectors2[name]);
  76081. }
  76082. // Vector3
  76083. for (name in this._vectors3) {
  76084. this._effect.setVector3(name, this._vectors3[name]);
  76085. }
  76086. // Matrix
  76087. for (name in this._matrices) {
  76088. this._effect.setMatrix(name, this._matrices[name]);
  76089. }
  76090. if (!this._texture) {
  76091. return;
  76092. }
  76093. if (this.isCube) {
  76094. for (var face = 0; face < 6; face++) {
  76095. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  76096. // VBOs
  76097. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76098. this._effect.setFloat("face", face);
  76099. // Clear
  76100. engine.clear(scene.clearColor, true, true, true);
  76101. // Draw order
  76102. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76103. // Mipmaps
  76104. if (face === 5) {
  76105. engine.generateMipMapsForCubemap(this._texture);
  76106. }
  76107. }
  76108. }
  76109. else {
  76110. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  76111. // VBOs
  76112. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76113. // Clear
  76114. engine.clear(scene.clearColor, true, true, true);
  76115. // Draw order
  76116. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76117. }
  76118. // Unbind
  76119. engine.unBindFramebuffer(this._texture, this.isCube);
  76120. if (this.onGenerated) {
  76121. this.onGenerated();
  76122. }
  76123. this.onGeneratedObservable.notifyObservers(this);
  76124. };
  76125. ProceduralTexture.prototype.clone = function () {
  76126. var textureSize = this.getSize();
  76127. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  76128. // Base texture
  76129. newTexture.hasAlpha = this.hasAlpha;
  76130. newTexture.level = this.level;
  76131. // RenderTarget Texture
  76132. newTexture.coordinatesMode = this.coordinatesMode;
  76133. return newTexture;
  76134. };
  76135. ProceduralTexture.prototype.dispose = function () {
  76136. var scene = this.getScene();
  76137. if (!scene) {
  76138. return;
  76139. }
  76140. var index = scene.proceduralTextures.indexOf(this);
  76141. if (index >= 0) {
  76142. scene.proceduralTextures.splice(index, 1);
  76143. }
  76144. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76145. if (vertexBuffer) {
  76146. vertexBuffer.dispose();
  76147. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76148. }
  76149. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  76150. this._indexBuffer = null;
  76151. }
  76152. _super.prototype.dispose.call(this);
  76153. };
  76154. __decorate([
  76155. BABYLON.serialize()
  76156. ], ProceduralTexture.prototype, "_size", void 0);
  76157. __decorate([
  76158. BABYLON.serialize()
  76159. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  76160. __decorate([
  76161. BABYLON.serialize()
  76162. ], ProceduralTexture.prototype, "isEnabled", void 0);
  76163. __decorate([
  76164. BABYLON.serialize()
  76165. ], ProceduralTexture.prototype, "refreshRate", null);
  76166. return ProceduralTexture;
  76167. }(BABYLON.Texture));
  76168. BABYLON.ProceduralTexture = ProceduralTexture;
  76169. })(BABYLON || (BABYLON = {}));
  76170. //# sourceMappingURL=babylon.proceduralTexture.js.map
  76171. var BABYLON;
  76172. (function (BABYLON) {
  76173. /**
  76174. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  76175. * in a given scene.
  76176. */
  76177. var ProceduralTextureSceneComponent = /** @class */ (function () {
  76178. /**
  76179. * Creates a new instance of the component for the given scene
  76180. * @param scene Defines the scene to register the component in
  76181. */
  76182. function ProceduralTextureSceneComponent(scene) {
  76183. /**
  76184. * The component name helpfull to identify the component in the list of scene components.
  76185. */
  76186. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  76187. this.scene = scene;
  76188. this.scene.proceduralTextures = new Array();
  76189. scene.layers = new Array();
  76190. }
  76191. /**
  76192. * Registers the component in a given scene
  76193. */
  76194. ProceduralTextureSceneComponent.prototype.register = function () {
  76195. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  76196. };
  76197. /**
  76198. * Rebuilds the elements related to this component in case of
  76199. * context lost for instance.
  76200. */
  76201. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  76202. // Nothing to do here.
  76203. };
  76204. /**
  76205. * Disposes the component and the associated ressources.
  76206. */
  76207. ProceduralTextureSceneComponent.prototype.dispose = function () {
  76208. // Nothing to do here.
  76209. };
  76210. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  76211. if (this.scene.proceduralTexturesEnabled) {
  76212. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76213. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  76214. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  76215. if (proceduralTexture._shouldRender()) {
  76216. proceduralTexture.render();
  76217. }
  76218. }
  76219. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76220. }
  76221. };
  76222. return ProceduralTextureSceneComponent;
  76223. }());
  76224. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  76225. })(BABYLON || (BABYLON = {}));
  76226. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  76227. var BABYLON;
  76228. (function (BABYLON) {
  76229. var CustomProceduralTexture = /** @class */ (function (_super) {
  76230. __extends(CustomProceduralTexture, _super);
  76231. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  76232. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  76233. _this._animate = true;
  76234. _this._time = 0;
  76235. _this._texturePath = texturePath;
  76236. //Try to load json
  76237. _this.loadJson(texturePath);
  76238. _this.refreshRate = 1;
  76239. return _this;
  76240. }
  76241. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  76242. var _this = this;
  76243. var noConfigFile = function () {
  76244. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  76245. try {
  76246. _this.setFragment(_this._texturePath);
  76247. }
  76248. catch (ex) {
  76249. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  76250. }
  76251. };
  76252. var configFileUrl = jsonUrl + "/config.json";
  76253. var xhr = new XMLHttpRequest();
  76254. xhr.open("GET", configFileUrl, true);
  76255. xhr.addEventListener("load", function () {
  76256. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76257. try {
  76258. _this._config = JSON.parse(xhr.response);
  76259. _this.updateShaderUniforms();
  76260. _this.updateTextures();
  76261. _this.setFragment(_this._texturePath + "/custom");
  76262. _this._animate = _this._config.animate;
  76263. _this.refreshRate = _this._config.refreshrate;
  76264. }
  76265. catch (ex) {
  76266. noConfigFile();
  76267. }
  76268. }
  76269. else {
  76270. noConfigFile();
  76271. }
  76272. }, false);
  76273. xhr.addEventListener("error", function () {
  76274. noConfigFile();
  76275. }, false);
  76276. try {
  76277. xhr.send();
  76278. }
  76279. catch (ex) {
  76280. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  76281. }
  76282. };
  76283. CustomProceduralTexture.prototype.isReady = function () {
  76284. if (!_super.prototype.isReady.call(this)) {
  76285. return false;
  76286. }
  76287. for (var name in this._textures) {
  76288. var texture = this._textures[name];
  76289. if (!texture.isReady()) {
  76290. return false;
  76291. }
  76292. }
  76293. return true;
  76294. };
  76295. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76296. var scene = this.getScene();
  76297. if (this._animate && scene) {
  76298. this._time += scene.getAnimationRatio() * 0.03;
  76299. this.updateShaderUniforms();
  76300. }
  76301. _super.prototype.render.call(this, useCameraPostProcess);
  76302. };
  76303. CustomProceduralTexture.prototype.updateTextures = function () {
  76304. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  76305. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  76306. }
  76307. };
  76308. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  76309. if (this._config) {
  76310. for (var j = 0; j < this._config.uniforms.length; j++) {
  76311. var uniform = this._config.uniforms[j];
  76312. switch (uniform.type) {
  76313. case "float":
  76314. this.setFloat(uniform.name, uniform.value);
  76315. break;
  76316. case "color3":
  76317. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  76318. break;
  76319. case "color4":
  76320. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  76321. break;
  76322. case "vector2":
  76323. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  76324. break;
  76325. case "vector3":
  76326. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  76327. break;
  76328. }
  76329. }
  76330. }
  76331. this.setFloat("time", this._time);
  76332. };
  76333. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  76334. get: function () {
  76335. return this._animate;
  76336. },
  76337. set: function (value) {
  76338. this._animate = value;
  76339. },
  76340. enumerable: true,
  76341. configurable: true
  76342. });
  76343. return CustomProceduralTexture;
  76344. }(BABYLON.ProceduralTexture));
  76345. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  76346. })(BABYLON || (BABYLON = {}));
  76347. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  76348. var BABYLON;
  76349. (function (BABYLON) {
  76350. /**
  76351. * Manage the gamepad inputs to control a free camera.
  76352. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76353. */
  76354. var FreeCameraGamepadInput = /** @class */ (function () {
  76355. function FreeCameraGamepadInput() {
  76356. /**
  76357. * Defines the gamepad rotation sensiblity.
  76358. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  76359. */
  76360. this.gamepadAngularSensibility = 200;
  76361. /**
  76362. * Defines the gamepad move sensiblity.
  76363. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  76364. */
  76365. this.gamepadMoveSensibility = 40;
  76366. this._cameraTransform = BABYLON.Matrix.Identity();
  76367. this._deltaTransform = BABYLON.Vector3.Zero();
  76368. this._vector3 = BABYLON.Vector3.Zero();
  76369. this._vector2 = BABYLON.Vector2.Zero();
  76370. }
  76371. /**
  76372. * Attach the input controls to a specific dom element to get the input from.
  76373. * @param element Defines the element the controls should be listened from
  76374. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76375. */
  76376. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  76377. var _this = this;
  76378. var manager = this.camera.getScene().gamepadManager;
  76379. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76380. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76381. // prioritize XBOX gamepads.
  76382. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  76383. _this.gamepad = gamepad;
  76384. }
  76385. }
  76386. });
  76387. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76388. if (_this.gamepad === gamepad) {
  76389. _this.gamepad = null;
  76390. }
  76391. });
  76392. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  76393. };
  76394. /**
  76395. * Detach the current controls from the specified dom element.
  76396. * @param element Defines the element to stop listening the inputs from
  76397. */
  76398. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  76399. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76400. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76401. this.gamepad = null;
  76402. };
  76403. /**
  76404. * Update the current camera state depending on the inputs that have been used this frame.
  76405. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76406. */
  76407. FreeCameraGamepadInput.prototype.checkInputs = function () {
  76408. if (this.gamepad && this.gamepad.leftStick) {
  76409. var camera = this.camera;
  76410. var LSValues = this.gamepad.leftStick;
  76411. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  76412. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  76413. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  76414. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  76415. var RSValues = this.gamepad.rightStick;
  76416. if (RSValues) {
  76417. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  76418. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  76419. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  76420. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  76421. }
  76422. else {
  76423. RSValues = { x: 0, y: 0 };
  76424. }
  76425. if (!camera.rotationQuaternion) {
  76426. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  76427. }
  76428. else {
  76429. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  76430. }
  76431. var speed = camera._computeLocalCameraSpeed() * 50.0;
  76432. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  76433. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  76434. camera.cameraDirection.addInPlace(this._deltaTransform);
  76435. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  76436. camera.cameraRotation.addInPlace(this._vector2);
  76437. }
  76438. };
  76439. /**
  76440. * Gets the class name of the current intput.
  76441. * @returns the class name
  76442. */
  76443. FreeCameraGamepadInput.prototype.getClassName = function () {
  76444. return "FreeCameraGamepadInput";
  76445. };
  76446. /**
  76447. * Get the friendly name associated with the input class.
  76448. * @returns the input friendly name
  76449. */
  76450. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  76451. return "gamepad";
  76452. };
  76453. __decorate([
  76454. BABYLON.serialize()
  76455. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  76456. __decorate([
  76457. BABYLON.serialize()
  76458. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  76459. return FreeCameraGamepadInput;
  76460. }());
  76461. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  76462. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  76463. })(BABYLON || (BABYLON = {}));
  76464. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  76465. var BABYLON;
  76466. (function (BABYLON) {
  76467. /**
  76468. * Manage the gamepad inputs to control an arc rotate camera.
  76469. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76470. */
  76471. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  76472. function ArcRotateCameraGamepadInput() {
  76473. /**
  76474. * Defines the gamepad rotation sensiblity.
  76475. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  76476. */
  76477. this.gamepadRotationSensibility = 80;
  76478. /**
  76479. * Defines the gamepad move sensiblity.
  76480. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  76481. */
  76482. this.gamepadMoveSensibility = 40;
  76483. }
  76484. /**
  76485. * Attach the input controls to a specific dom element to get the input from.
  76486. * @param element Defines the element the controls should be listened from
  76487. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76488. */
  76489. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  76490. var _this = this;
  76491. var manager = this.camera.getScene().gamepadManager;
  76492. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76493. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76494. // prioritize XBOX gamepads.
  76495. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  76496. _this.gamepad = gamepad;
  76497. }
  76498. }
  76499. });
  76500. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76501. if (_this.gamepad === gamepad) {
  76502. _this.gamepad = null;
  76503. }
  76504. });
  76505. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  76506. };
  76507. /**
  76508. * Detach the current controls from the specified dom element.
  76509. * @param element Defines the element to stop listening the inputs from
  76510. */
  76511. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  76512. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76513. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76514. this.gamepad = null;
  76515. };
  76516. /**
  76517. * Update the current camera state depending on the inputs that have been used this frame.
  76518. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76519. */
  76520. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  76521. if (this.gamepad) {
  76522. var camera = this.camera;
  76523. var RSValues = this.gamepad.rightStick;
  76524. if (RSValues) {
  76525. if (RSValues.x != 0) {
  76526. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  76527. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  76528. camera.inertialAlphaOffset += normalizedRX;
  76529. }
  76530. }
  76531. if (RSValues.y != 0) {
  76532. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  76533. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  76534. camera.inertialBetaOffset += normalizedRY;
  76535. }
  76536. }
  76537. }
  76538. var LSValues = this.gamepad.leftStick;
  76539. if (LSValues && LSValues.y != 0) {
  76540. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  76541. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  76542. this.camera.inertialRadiusOffset -= normalizedLY;
  76543. }
  76544. }
  76545. }
  76546. };
  76547. /**
  76548. * Gets the class name of the current intput.
  76549. * @returns the class name
  76550. */
  76551. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  76552. return "ArcRotateCameraGamepadInput";
  76553. };
  76554. /**
  76555. * Get the friendly name associated with the input class.
  76556. * @returns the input friendly name
  76557. */
  76558. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  76559. return "gamepad";
  76560. };
  76561. __decorate([
  76562. BABYLON.serialize()
  76563. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  76564. __decorate([
  76565. BABYLON.serialize()
  76566. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  76567. return ArcRotateCameraGamepadInput;
  76568. }());
  76569. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  76570. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  76571. })(BABYLON || (BABYLON = {}));
  76572. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  76573. var BABYLON;
  76574. (function (BABYLON) {
  76575. var GamepadManager = /** @class */ (function () {
  76576. function GamepadManager(_scene) {
  76577. var _this = this;
  76578. this._scene = _scene;
  76579. this._babylonGamepads = [];
  76580. this._oneGamepadConnected = false;
  76581. /** @hidden */
  76582. this._isMonitoring = false;
  76583. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  76584. if (!BABYLON.Tools.IsWindowObjectExist()) {
  76585. this._gamepadEventSupported = false;
  76586. }
  76587. else {
  76588. this._gamepadEventSupported = 'GamepadEvent' in window;
  76589. this._gamepadSupport = (navigator.getGamepads ||
  76590. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  76591. }
  76592. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  76593. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  76594. for (var i in _this._babylonGamepads) {
  76595. var gamepad = _this._babylonGamepads[i];
  76596. if (gamepad && gamepad._isConnected) {
  76597. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  76598. }
  76599. }
  76600. });
  76601. this._onGamepadConnectedEvent = function (evt) {
  76602. var gamepad = evt.gamepad;
  76603. if (gamepad.index in _this._babylonGamepads) {
  76604. if (_this._babylonGamepads[gamepad.index].isConnected) {
  76605. return;
  76606. }
  76607. }
  76608. var newGamepad;
  76609. if (_this._babylonGamepads[gamepad.index]) {
  76610. newGamepad = _this._babylonGamepads[gamepad.index];
  76611. newGamepad.browserGamepad = gamepad;
  76612. newGamepad._isConnected = true;
  76613. }
  76614. else {
  76615. newGamepad = _this._addNewGamepad(gamepad);
  76616. }
  76617. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  76618. _this._startMonitoringGamepads();
  76619. };
  76620. this._onGamepadDisconnectedEvent = function (evt) {
  76621. var gamepad = evt.gamepad;
  76622. // Remove the gamepad from the list of gamepads to monitor.
  76623. for (var i in _this._babylonGamepads) {
  76624. if (_this._babylonGamepads[i].index === gamepad.index) {
  76625. var disconnectedGamepad = _this._babylonGamepads[i];
  76626. disconnectedGamepad._isConnected = false;
  76627. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  76628. break;
  76629. }
  76630. }
  76631. };
  76632. if (this._gamepadSupport) {
  76633. //first add already-connected gamepads
  76634. this._updateGamepadObjects();
  76635. if (this._babylonGamepads.length) {
  76636. this._startMonitoringGamepads();
  76637. }
  76638. // Checking if the gamepad connected event is supported (like in Firefox)
  76639. if (this._gamepadEventSupported) {
  76640. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  76641. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  76642. }
  76643. else {
  76644. this._startMonitoringGamepads();
  76645. }
  76646. }
  76647. }
  76648. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  76649. get: function () {
  76650. return this._babylonGamepads;
  76651. },
  76652. enumerable: true,
  76653. configurable: true
  76654. });
  76655. GamepadManager.prototype.getGamepadByType = function (type) {
  76656. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  76657. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  76658. var gamepad = _a[_i];
  76659. if (gamepad && gamepad.type === type) {
  76660. return gamepad;
  76661. }
  76662. }
  76663. return null;
  76664. };
  76665. GamepadManager.prototype.dispose = function () {
  76666. if (this._gamepadEventSupported) {
  76667. if (this._onGamepadConnectedEvent) {
  76668. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  76669. }
  76670. if (this._onGamepadDisconnectedEvent) {
  76671. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  76672. }
  76673. this._onGamepadConnectedEvent = null;
  76674. this._onGamepadDisconnectedEvent = null;
  76675. }
  76676. this._babylonGamepads.forEach(function (gamepad) {
  76677. gamepad.dispose();
  76678. });
  76679. this.onGamepadConnectedObservable.clear();
  76680. this.onGamepadDisconnectedObservable.clear();
  76681. this._oneGamepadConnected = false;
  76682. this._stopMonitoringGamepads();
  76683. this._babylonGamepads = [];
  76684. };
  76685. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  76686. if (!this._oneGamepadConnected) {
  76687. this._oneGamepadConnected = true;
  76688. }
  76689. var newGamepad;
  76690. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  76691. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  76692. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  76693. }
  76694. // if pose is supported, use the (WebVR) pose enabled controller
  76695. else if (gamepad.pose) {
  76696. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  76697. }
  76698. else {
  76699. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  76700. }
  76701. this._babylonGamepads[newGamepad.index] = newGamepad;
  76702. return newGamepad;
  76703. };
  76704. GamepadManager.prototype._startMonitoringGamepads = function () {
  76705. if (!this._isMonitoring) {
  76706. this._isMonitoring = true;
  76707. //back-comp
  76708. if (!this._scene) {
  76709. this._checkGamepadsStatus();
  76710. }
  76711. }
  76712. };
  76713. GamepadManager.prototype._stopMonitoringGamepads = function () {
  76714. this._isMonitoring = false;
  76715. };
  76716. /** @hidden */
  76717. GamepadManager.prototype._checkGamepadsStatus = function () {
  76718. var _this = this;
  76719. // Hack to be compatible Chrome
  76720. this._updateGamepadObjects();
  76721. for (var i in this._babylonGamepads) {
  76722. var gamepad = this._babylonGamepads[i];
  76723. if (!gamepad || !gamepad.isConnected) {
  76724. continue;
  76725. }
  76726. gamepad.update();
  76727. }
  76728. if (this._isMonitoring && !this._scene) {
  76729. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  76730. }
  76731. };
  76732. // This function is called only on Chrome, which does not properly support
  76733. // connection/disconnection events and forces you to recopy again the gamepad object
  76734. GamepadManager.prototype._updateGamepadObjects = function () {
  76735. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  76736. for (var i = 0; i < gamepads.length; i++) {
  76737. var gamepad = gamepads[i];
  76738. if (gamepad) {
  76739. if (!this._babylonGamepads[gamepad.index]) {
  76740. var newGamepad = this._addNewGamepad(gamepad);
  76741. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  76742. }
  76743. else {
  76744. // Forced to copy again this object for Chrome for unknown reason
  76745. this._babylonGamepads[i].browserGamepad = gamepad;
  76746. if (!this._babylonGamepads[i].isConnected) {
  76747. this._babylonGamepads[i]._isConnected = true;
  76748. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  76749. }
  76750. }
  76751. }
  76752. }
  76753. };
  76754. return GamepadManager;
  76755. }());
  76756. BABYLON.GamepadManager = GamepadManager;
  76757. })(BABYLON || (BABYLON = {}));
  76758. //# sourceMappingURL=babylon.gamepadManager.js.map
  76759. var BABYLON;
  76760. (function (BABYLON) {
  76761. var StickValues = /** @class */ (function () {
  76762. function StickValues(x, y) {
  76763. this.x = x;
  76764. this.y = y;
  76765. }
  76766. return StickValues;
  76767. }());
  76768. BABYLON.StickValues = StickValues;
  76769. var Gamepad = /** @class */ (function () {
  76770. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  76771. if (leftStickX === void 0) { leftStickX = 0; }
  76772. if (leftStickY === void 0) { leftStickY = 1; }
  76773. if (rightStickX === void 0) { rightStickX = 2; }
  76774. if (rightStickY === void 0) { rightStickY = 3; }
  76775. this.id = id;
  76776. this.index = index;
  76777. this.browserGamepad = browserGamepad;
  76778. this._leftStick = { x: 0, y: 0 };
  76779. this._rightStick = { x: 0, y: 0 };
  76780. /** @hidden */
  76781. this._isConnected = true;
  76782. this._invertLeftStickY = false;
  76783. this.type = Gamepad.GAMEPAD;
  76784. this._leftStickAxisX = leftStickX;
  76785. this._leftStickAxisY = leftStickY;
  76786. this._rightStickAxisX = rightStickX;
  76787. this._rightStickAxisY = rightStickY;
  76788. if (this.browserGamepad.axes.length >= 2) {
  76789. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  76790. }
  76791. if (this.browserGamepad.axes.length >= 4) {
  76792. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  76793. }
  76794. }
  76795. Object.defineProperty(Gamepad.prototype, "isConnected", {
  76796. get: function () {
  76797. return this._isConnected;
  76798. },
  76799. enumerable: true,
  76800. configurable: true
  76801. });
  76802. Gamepad.prototype.onleftstickchanged = function (callback) {
  76803. this._onleftstickchanged = callback;
  76804. };
  76805. Gamepad.prototype.onrightstickchanged = function (callback) {
  76806. this._onrightstickchanged = callback;
  76807. };
  76808. Object.defineProperty(Gamepad.prototype, "leftStick", {
  76809. get: function () {
  76810. return this._leftStick;
  76811. },
  76812. set: function (newValues) {
  76813. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  76814. this._onleftstickchanged(newValues);
  76815. }
  76816. this._leftStick = newValues;
  76817. },
  76818. enumerable: true,
  76819. configurable: true
  76820. });
  76821. Object.defineProperty(Gamepad.prototype, "rightStick", {
  76822. get: function () {
  76823. return this._rightStick;
  76824. },
  76825. set: function (newValues) {
  76826. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  76827. this._onrightstickchanged(newValues);
  76828. }
  76829. this._rightStick = newValues;
  76830. },
  76831. enumerable: true,
  76832. configurable: true
  76833. });
  76834. Gamepad.prototype.update = function () {
  76835. if (this._leftStick) {
  76836. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  76837. if (this._invertLeftStickY) {
  76838. this.leftStick.y *= -1;
  76839. }
  76840. }
  76841. if (this._rightStick) {
  76842. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  76843. }
  76844. };
  76845. Gamepad.prototype.dispose = function () {
  76846. };
  76847. Gamepad.GAMEPAD = 0;
  76848. Gamepad.GENERIC = 1;
  76849. Gamepad.XBOX = 2;
  76850. Gamepad.POSE_ENABLED = 3;
  76851. return Gamepad;
  76852. }());
  76853. BABYLON.Gamepad = Gamepad;
  76854. var GenericPad = /** @class */ (function (_super) {
  76855. __extends(GenericPad, _super);
  76856. function GenericPad(id, index, browserGamepad) {
  76857. var _this = _super.call(this, id, index, browserGamepad) || this;
  76858. _this.onButtonDownObservable = new BABYLON.Observable();
  76859. _this.onButtonUpObservable = new BABYLON.Observable();
  76860. _this.type = Gamepad.GENERIC;
  76861. _this._buttons = new Array(browserGamepad.buttons.length);
  76862. return _this;
  76863. }
  76864. GenericPad.prototype.onbuttondown = function (callback) {
  76865. this._onbuttondown = callback;
  76866. };
  76867. GenericPad.prototype.onbuttonup = function (callback) {
  76868. this._onbuttonup = callback;
  76869. };
  76870. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  76871. if (newValue !== currentValue) {
  76872. if (newValue === 1) {
  76873. if (this._onbuttondown) {
  76874. this._onbuttondown(buttonIndex);
  76875. }
  76876. this.onButtonDownObservable.notifyObservers(buttonIndex);
  76877. }
  76878. if (newValue === 0) {
  76879. if (this._onbuttonup) {
  76880. this._onbuttonup(buttonIndex);
  76881. }
  76882. this.onButtonUpObservable.notifyObservers(buttonIndex);
  76883. }
  76884. }
  76885. return newValue;
  76886. };
  76887. GenericPad.prototype.update = function () {
  76888. _super.prototype.update.call(this);
  76889. for (var index = 0; index < this._buttons.length; index++) {
  76890. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  76891. }
  76892. };
  76893. GenericPad.prototype.dispose = function () {
  76894. _super.prototype.dispose.call(this);
  76895. this.onButtonDownObservable.clear();
  76896. this.onButtonUpObservable.clear();
  76897. };
  76898. return GenericPad;
  76899. }(Gamepad));
  76900. BABYLON.GenericPad = GenericPad;
  76901. })(BABYLON || (BABYLON = {}));
  76902. //# sourceMappingURL=babylon.gamepad.js.map
  76903. var BABYLON;
  76904. (function (BABYLON) {
  76905. /**
  76906. * Defines supported buttons for XBox360 compatible gamepads
  76907. */
  76908. var Xbox360Button;
  76909. (function (Xbox360Button) {
  76910. /** A */
  76911. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  76912. /** B */
  76913. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  76914. /** X */
  76915. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  76916. /** Y */
  76917. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  76918. /** Start */
  76919. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  76920. /** Back */
  76921. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  76922. /** Left button */
  76923. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  76924. /** Right button */
  76925. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  76926. /** Left stick */
  76927. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  76928. /** Right stick */
  76929. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  76930. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  76931. /** Defines values for XBox360 DPad */
  76932. var Xbox360Dpad;
  76933. (function (Xbox360Dpad) {
  76934. /** Up */
  76935. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  76936. /** Down */
  76937. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  76938. /** Left */
  76939. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  76940. /** Right */
  76941. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  76942. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  76943. /**
  76944. * Defines a XBox360 gamepad
  76945. */
  76946. var Xbox360Pad = /** @class */ (function (_super) {
  76947. __extends(Xbox360Pad, _super);
  76948. /**
  76949. * Creates a new XBox360 gamepad object
  76950. * @param id defines the id of this gamepad
  76951. * @param index defines its index
  76952. * @param gamepad defines the internal HTML gamepad object
  76953. * @param xboxOne defines if it is a XBox One gamepad
  76954. */
  76955. function Xbox360Pad(id, index, gamepad, xboxOne) {
  76956. if (xboxOne === void 0) { xboxOne = false; }
  76957. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  76958. _this._leftTrigger = 0;
  76959. _this._rightTrigger = 0;
  76960. /** Observable raised when a button is pressed */
  76961. _this.onButtonDownObservable = new BABYLON.Observable();
  76962. /** Observable raised when a button is released */
  76963. _this.onButtonUpObservable = new BABYLON.Observable();
  76964. /** Observable raised when a pad is pressed */
  76965. _this.onPadDownObservable = new BABYLON.Observable();
  76966. /** Observable raised when a pad is released */
  76967. _this.onPadUpObservable = new BABYLON.Observable();
  76968. _this._buttonA = 0;
  76969. _this._buttonB = 0;
  76970. _this._buttonX = 0;
  76971. _this._buttonY = 0;
  76972. _this._buttonBack = 0;
  76973. _this._buttonStart = 0;
  76974. _this._buttonLB = 0;
  76975. _this._buttonRB = 0;
  76976. _this._buttonLeftStick = 0;
  76977. _this._buttonRightStick = 0;
  76978. _this._dPadUp = 0;
  76979. _this._dPadDown = 0;
  76980. _this._dPadLeft = 0;
  76981. _this._dPadRight = 0;
  76982. _this._isXboxOnePad = false;
  76983. _this.type = BABYLON.Gamepad.XBOX;
  76984. _this._isXboxOnePad = xboxOne;
  76985. return _this;
  76986. }
  76987. /**
  76988. * Defines the callback to call when left trigger is pressed
  76989. * @param callback defines the callback to use
  76990. */
  76991. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  76992. this._onlefttriggerchanged = callback;
  76993. };
  76994. /**
  76995. * Defines the callback to call when right trigger is pressed
  76996. * @param callback defines the callback to use
  76997. */
  76998. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  76999. this._onrighttriggerchanged = callback;
  77000. };
  77001. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  77002. /**
  77003. * Gets or sets left trigger value
  77004. */
  77005. get: function () {
  77006. return this._leftTrigger;
  77007. },
  77008. set: function (newValue) {
  77009. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  77010. this._onlefttriggerchanged(newValue);
  77011. }
  77012. this._leftTrigger = newValue;
  77013. },
  77014. enumerable: true,
  77015. configurable: true
  77016. });
  77017. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  77018. /**
  77019. * Gets or sets right trigger value
  77020. */
  77021. get: function () {
  77022. return this._rightTrigger;
  77023. },
  77024. set: function (newValue) {
  77025. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  77026. this._onrighttriggerchanged(newValue);
  77027. }
  77028. this._rightTrigger = newValue;
  77029. },
  77030. enumerable: true,
  77031. configurable: true
  77032. });
  77033. /**
  77034. * Defines the callback to call when a button is pressed
  77035. * @param callback defines the callback to use
  77036. */
  77037. Xbox360Pad.prototype.onbuttondown = function (callback) {
  77038. this._onbuttondown = callback;
  77039. };
  77040. /**
  77041. * Defines the callback to call when a button is released
  77042. * @param callback defines the callback to use
  77043. */
  77044. Xbox360Pad.prototype.onbuttonup = function (callback) {
  77045. this._onbuttonup = callback;
  77046. };
  77047. /**
  77048. * Defines the callback to call when a pad is pressed
  77049. * @param callback defines the callback to use
  77050. */
  77051. Xbox360Pad.prototype.ondpaddown = function (callback) {
  77052. this._ondpaddown = callback;
  77053. };
  77054. /**
  77055. * Defines the callback to call when a pad is released
  77056. * @param callback defines the callback to use
  77057. */
  77058. Xbox360Pad.prototype.ondpadup = function (callback) {
  77059. this._ondpadup = callback;
  77060. };
  77061. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  77062. if (newValue !== currentValue) {
  77063. if (newValue === 1) {
  77064. if (this._onbuttondown) {
  77065. this._onbuttondown(buttonType);
  77066. }
  77067. this.onButtonDownObservable.notifyObservers(buttonType);
  77068. }
  77069. if (newValue === 0) {
  77070. if (this._onbuttonup) {
  77071. this._onbuttonup(buttonType);
  77072. }
  77073. this.onButtonUpObservable.notifyObservers(buttonType);
  77074. }
  77075. }
  77076. return newValue;
  77077. };
  77078. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  77079. if (newValue !== currentValue) {
  77080. if (newValue === 1) {
  77081. if (this._ondpaddown) {
  77082. this._ondpaddown(buttonType);
  77083. }
  77084. this.onPadDownObservable.notifyObservers(buttonType);
  77085. }
  77086. if (newValue === 0) {
  77087. if (this._ondpadup) {
  77088. this._ondpadup(buttonType);
  77089. }
  77090. this.onPadUpObservable.notifyObservers(buttonType);
  77091. }
  77092. }
  77093. return newValue;
  77094. };
  77095. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  77096. /** Gets or sets value of A button */
  77097. get: function () {
  77098. return this._buttonA;
  77099. },
  77100. set: function (value) {
  77101. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  77102. },
  77103. enumerable: true,
  77104. configurable: true
  77105. });
  77106. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  77107. /** Gets or sets value of B button */
  77108. get: function () {
  77109. return this._buttonB;
  77110. },
  77111. set: function (value) {
  77112. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  77113. },
  77114. enumerable: true,
  77115. configurable: true
  77116. });
  77117. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  77118. /** Gets or sets value of X button */
  77119. get: function () {
  77120. return this._buttonX;
  77121. },
  77122. set: function (value) {
  77123. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  77124. },
  77125. enumerable: true,
  77126. configurable: true
  77127. });
  77128. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  77129. /** Gets or sets value of Y button */
  77130. get: function () {
  77131. return this._buttonY;
  77132. },
  77133. set: function (value) {
  77134. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  77135. },
  77136. enumerable: true,
  77137. configurable: true
  77138. });
  77139. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  77140. /** Gets or sets value of Start button */
  77141. get: function () {
  77142. return this._buttonStart;
  77143. },
  77144. set: function (value) {
  77145. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  77146. },
  77147. enumerable: true,
  77148. configurable: true
  77149. });
  77150. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  77151. /** Gets or sets value of Back button */
  77152. get: function () {
  77153. return this._buttonBack;
  77154. },
  77155. set: function (value) {
  77156. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  77157. },
  77158. enumerable: true,
  77159. configurable: true
  77160. });
  77161. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  77162. /** Gets or sets value of Left button */
  77163. get: function () {
  77164. return this._buttonLB;
  77165. },
  77166. set: function (value) {
  77167. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  77168. },
  77169. enumerable: true,
  77170. configurable: true
  77171. });
  77172. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  77173. /** Gets or sets value of Right button */
  77174. get: function () {
  77175. return this._buttonRB;
  77176. },
  77177. set: function (value) {
  77178. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  77179. },
  77180. enumerable: true,
  77181. configurable: true
  77182. });
  77183. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  77184. /** Gets or sets value of left stick */
  77185. get: function () {
  77186. return this._buttonLeftStick;
  77187. },
  77188. set: function (value) {
  77189. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  77190. },
  77191. enumerable: true,
  77192. configurable: true
  77193. });
  77194. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  77195. /** Gets or sets value of right stick */
  77196. get: function () {
  77197. return this._buttonRightStick;
  77198. },
  77199. set: function (value) {
  77200. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  77201. },
  77202. enumerable: true,
  77203. configurable: true
  77204. });
  77205. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  77206. /** Gets or sets value of DPad up */
  77207. get: function () {
  77208. return this._dPadUp;
  77209. },
  77210. set: function (value) {
  77211. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  77212. },
  77213. enumerable: true,
  77214. configurable: true
  77215. });
  77216. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  77217. /** Gets or sets value of DPad down */
  77218. get: function () {
  77219. return this._dPadDown;
  77220. },
  77221. set: function (value) {
  77222. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  77223. },
  77224. enumerable: true,
  77225. configurable: true
  77226. });
  77227. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  77228. /** Gets or sets value of DPad left */
  77229. get: function () {
  77230. return this._dPadLeft;
  77231. },
  77232. set: function (value) {
  77233. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  77234. },
  77235. enumerable: true,
  77236. configurable: true
  77237. });
  77238. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  77239. /** Gets or sets value of DPad right */
  77240. get: function () {
  77241. return this._dPadRight;
  77242. },
  77243. set: function (value) {
  77244. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  77245. },
  77246. enumerable: true,
  77247. configurable: true
  77248. });
  77249. /**
  77250. * Force the gamepad to synchronize with device values
  77251. */
  77252. Xbox360Pad.prototype.update = function () {
  77253. _super.prototype.update.call(this);
  77254. if (this._isXboxOnePad) {
  77255. this.buttonA = this.browserGamepad.buttons[0].value;
  77256. this.buttonB = this.browserGamepad.buttons[1].value;
  77257. this.buttonX = this.browserGamepad.buttons[2].value;
  77258. this.buttonY = this.browserGamepad.buttons[3].value;
  77259. this.buttonLB = this.browserGamepad.buttons[4].value;
  77260. this.buttonRB = this.browserGamepad.buttons[5].value;
  77261. this.leftTrigger = this.browserGamepad.axes[2];
  77262. this.rightTrigger = this.browserGamepad.axes[5];
  77263. this.buttonBack = this.browserGamepad.buttons[9].value;
  77264. this.buttonStart = this.browserGamepad.buttons[8].value;
  77265. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  77266. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  77267. this.dPadUp = this.browserGamepad.buttons[11].value;
  77268. this.dPadDown = this.browserGamepad.buttons[12].value;
  77269. this.dPadLeft = this.browserGamepad.buttons[13].value;
  77270. this.dPadRight = this.browserGamepad.buttons[14].value;
  77271. }
  77272. else {
  77273. this.buttonA = this.browserGamepad.buttons[0].value;
  77274. this.buttonB = this.browserGamepad.buttons[1].value;
  77275. this.buttonX = this.browserGamepad.buttons[2].value;
  77276. this.buttonY = this.browserGamepad.buttons[3].value;
  77277. this.buttonLB = this.browserGamepad.buttons[4].value;
  77278. this.buttonRB = this.browserGamepad.buttons[5].value;
  77279. this.leftTrigger = this.browserGamepad.buttons[6].value;
  77280. this.rightTrigger = this.browserGamepad.buttons[7].value;
  77281. this.buttonBack = this.browserGamepad.buttons[8].value;
  77282. this.buttonStart = this.browserGamepad.buttons[9].value;
  77283. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  77284. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  77285. this.dPadUp = this.browserGamepad.buttons[12].value;
  77286. this.dPadDown = this.browserGamepad.buttons[13].value;
  77287. this.dPadLeft = this.browserGamepad.buttons[14].value;
  77288. this.dPadRight = this.browserGamepad.buttons[15].value;
  77289. }
  77290. };
  77291. Xbox360Pad.prototype.dispose = function () {
  77292. _super.prototype.dispose.call(this);
  77293. this.onButtonDownObservable.clear();
  77294. this.onButtonUpObservable.clear();
  77295. this.onPadDownObservable.clear();
  77296. this.onPadUpObservable.clear();
  77297. };
  77298. return Xbox360Pad;
  77299. }(BABYLON.Gamepad));
  77300. BABYLON.Xbox360Pad = Xbox360Pad;
  77301. })(BABYLON || (BABYLON = {}));
  77302. //# sourceMappingURL=babylon.xboxGamepad.js.map
  77303. var BABYLON;
  77304. (function (BABYLON) {
  77305. /**
  77306. * Defines the types of pose enabled controllers that are supported
  77307. */
  77308. var PoseEnabledControllerType;
  77309. (function (PoseEnabledControllerType) {
  77310. /**
  77311. * HTC Vive
  77312. */
  77313. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  77314. /**
  77315. * Oculus Rift
  77316. */
  77317. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  77318. /**
  77319. * Windows mixed reality
  77320. */
  77321. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  77322. /**
  77323. * Samsung gear VR
  77324. */
  77325. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  77326. /**
  77327. * Google Daydream
  77328. */
  77329. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  77330. /**
  77331. * Generic
  77332. */
  77333. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  77334. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  77335. /**
  77336. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  77337. */
  77338. var PoseEnabledControllerHelper = /** @class */ (function () {
  77339. function PoseEnabledControllerHelper() {
  77340. }
  77341. /**
  77342. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  77343. * @param vrGamepad the gamepad to initialized
  77344. * @returns a vr controller of the type the gamepad identified as
  77345. */
  77346. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  77347. // Oculus Touch
  77348. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  77349. return new BABYLON.OculusTouchController(vrGamepad);
  77350. }
  77351. // Windows Mixed Reality controllers
  77352. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  77353. return new BABYLON.WindowsMotionController(vrGamepad);
  77354. }
  77355. // HTC Vive
  77356. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  77357. return new BABYLON.ViveController(vrGamepad);
  77358. }
  77359. // Samsung/Oculus Gear VR or Oculus Go
  77360. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  77361. return new BABYLON.GearVRController(vrGamepad);
  77362. }
  77363. // Google Daydream
  77364. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  77365. return new BABYLON.DaydreamController(vrGamepad);
  77366. }
  77367. // Generic
  77368. else {
  77369. return new BABYLON.GenericController(vrGamepad);
  77370. }
  77371. };
  77372. return PoseEnabledControllerHelper;
  77373. }());
  77374. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  77375. /**
  77376. * Defines the PoseEnabledController object that contains state of a vr capable controller
  77377. */
  77378. var PoseEnabledController = /** @class */ (function (_super) {
  77379. __extends(PoseEnabledController, _super);
  77380. /**
  77381. * Creates a new PoseEnabledController from a gamepad
  77382. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  77383. */
  77384. function PoseEnabledController(browserGamepad) {
  77385. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  77386. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77387. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77388. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  77389. /**
  77390. * The device position in babylon space
  77391. */
  77392. _this.devicePosition = BABYLON.Vector3.Zero();
  77393. /**
  77394. * The device rotation in babylon space
  77395. */
  77396. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  77397. /**
  77398. * The scale factor of the device in babylon space
  77399. */
  77400. _this.deviceScaleFactor = 1;
  77401. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  77402. /**
  77403. * Internal, matrix used to convert room space to babylon space
  77404. * @hidden
  77405. */
  77406. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77407. /**
  77408. * Node to be used when casting a ray from the controller
  77409. * @hidden
  77410. */
  77411. _this._pointingPoseNode = null;
  77412. _this._workingMatrix = BABYLON.Matrix.Identity();
  77413. /**
  77414. * @hidden
  77415. */
  77416. _this._meshAttachedObservable = new BABYLON.Observable();
  77417. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  77418. _this.controllerType = PoseEnabledControllerType.GENERIC;
  77419. _this.position = BABYLON.Vector3.Zero();
  77420. _this.rotationQuaternion = new BABYLON.Quaternion();
  77421. _this._calculatedPosition = BABYLON.Vector3.Zero();
  77422. _this._calculatedRotation = new BABYLON.Quaternion();
  77423. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  77424. return _this;
  77425. }
  77426. /**
  77427. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  77428. */
  77429. PoseEnabledController.prototype.update = function () {
  77430. _super.prototype.update.call(this);
  77431. this._updatePoseAndMesh();
  77432. };
  77433. /**
  77434. * Updates only the pose device and mesh without doing any button event checking
  77435. */
  77436. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  77437. var pose = this.browserGamepad.pose;
  77438. this.updateFromDevice(pose);
  77439. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  77440. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  77441. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  77442. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  77443. if (this._mesh) {
  77444. this._mesh.position.copyFrom(this.devicePosition);
  77445. if (this._mesh.rotationQuaternion) {
  77446. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  77447. }
  77448. }
  77449. };
  77450. /**
  77451. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  77452. * @param poseData raw pose fromthe device
  77453. */
  77454. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  77455. if (poseData) {
  77456. this.rawPose = poseData;
  77457. if (poseData.position) {
  77458. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  77459. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  77460. this._deviceRoomPosition.z *= -1;
  77461. }
  77462. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  77463. this._calculatedPosition.addInPlace(this.position);
  77464. }
  77465. var pose = this.rawPose;
  77466. if (poseData.orientation && pose.orientation) {
  77467. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  77468. if (this._mesh) {
  77469. if (this._mesh.getScene().useRightHandedSystem) {
  77470. this._deviceRoomRotationQuaternion.z *= -1;
  77471. this._deviceRoomRotationQuaternion.w *= -1;
  77472. }
  77473. else {
  77474. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  77475. }
  77476. }
  77477. // if the camera is set, rotate to the camera's rotation
  77478. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  77479. }
  77480. }
  77481. };
  77482. /**
  77483. * Attaches a mesh to the controller
  77484. * @param mesh the mesh to be attached
  77485. */
  77486. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  77487. if (this._mesh) {
  77488. this._mesh.parent = null;
  77489. }
  77490. this._mesh = mesh;
  77491. if (this._poseControlledCamera) {
  77492. this._mesh.parent = this._poseControlledCamera;
  77493. }
  77494. if (!this._mesh.rotationQuaternion) {
  77495. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  77496. }
  77497. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  77498. this._updatePoseAndMesh();
  77499. if (this._pointingPoseNode) {
  77500. var parents = [];
  77501. var obj = this._pointingPoseNode;
  77502. while (obj.parent) {
  77503. parents.push(obj.parent);
  77504. obj = obj.parent;
  77505. }
  77506. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  77507. }
  77508. this._meshAttachedObservable.notifyObservers(mesh);
  77509. };
  77510. /**
  77511. * Attaches the controllers mesh to a camera
  77512. * @param camera the camera the mesh should be attached to
  77513. */
  77514. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  77515. this._poseControlledCamera = camera;
  77516. if (this._mesh) {
  77517. this._mesh.parent = this._poseControlledCamera;
  77518. }
  77519. };
  77520. /**
  77521. * Disposes of the controller
  77522. */
  77523. PoseEnabledController.prototype.dispose = function () {
  77524. if (this._mesh) {
  77525. this._mesh.dispose();
  77526. }
  77527. this._mesh = null;
  77528. _super.prototype.dispose.call(this);
  77529. };
  77530. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  77531. /**
  77532. * The mesh that is attached to the controller
  77533. */
  77534. get: function () {
  77535. return this._mesh;
  77536. },
  77537. enumerable: true,
  77538. configurable: true
  77539. });
  77540. /**
  77541. * Gets the ray of the controller in the direction the controller is pointing
  77542. * @param length the length the resulting ray should be
  77543. * @returns a ray in the direction the controller is pointing
  77544. */
  77545. PoseEnabledController.prototype.getForwardRay = function (length) {
  77546. if (length === void 0) { length = 100; }
  77547. if (!this.mesh) {
  77548. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  77549. }
  77550. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  77551. var origin = m.getTranslation();
  77552. var forward = new BABYLON.Vector3(0, 0, -1);
  77553. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  77554. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  77555. return new BABYLON.Ray(origin, direction, length);
  77556. };
  77557. /**
  77558. * Name of the child mesh that can be used to cast a ray from the controller
  77559. */
  77560. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  77561. return PoseEnabledController;
  77562. }(BABYLON.Gamepad));
  77563. BABYLON.PoseEnabledController = PoseEnabledController;
  77564. })(BABYLON || (BABYLON = {}));
  77565. //# sourceMappingURL=babylon.poseEnabledController.js.map
  77566. var BABYLON;
  77567. (function (BABYLON) {
  77568. /**
  77569. * Defines the WebVRController object that represents controllers tracked in 3D space
  77570. */
  77571. var WebVRController = /** @class */ (function (_super) {
  77572. __extends(WebVRController, _super);
  77573. /**
  77574. * Creates a new WebVRController from a gamepad
  77575. * @param vrGamepad the gamepad that the WebVRController should be created from
  77576. */
  77577. function WebVRController(vrGamepad) {
  77578. var _this = _super.call(this, vrGamepad) || this;
  77579. // Observables
  77580. /**
  77581. * Fired when the trigger state has changed
  77582. */
  77583. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  77584. /**
  77585. * Fired when the main button state has changed
  77586. */
  77587. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  77588. /**
  77589. * Fired when the secondary button state has changed
  77590. */
  77591. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  77592. /**
  77593. * Fired when the pad state has changed
  77594. */
  77595. _this.onPadStateChangedObservable = new BABYLON.Observable();
  77596. /**
  77597. * Fired when controllers stick values have changed
  77598. */
  77599. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  77600. /**
  77601. * X and Y axis corrisponding to the controllers joystick
  77602. */
  77603. _this.pad = { x: 0, y: 0 };
  77604. // avoid GC, store state in a tmp object
  77605. _this._changes = {
  77606. pressChanged: false,
  77607. touchChanged: false,
  77608. valueChanged: false,
  77609. changed: false
  77610. };
  77611. _this._buttons = new Array(vrGamepad.buttons.length);
  77612. _this.hand = vrGamepad.hand;
  77613. return _this;
  77614. }
  77615. /**
  77616. * Fired when a controller button's state has changed
  77617. * @param callback the callback containing the button that was modified
  77618. */
  77619. WebVRController.prototype.onButtonStateChange = function (callback) {
  77620. this._onButtonStateChange = callback;
  77621. };
  77622. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  77623. /**
  77624. * The default controller model for the controller
  77625. */
  77626. get: function () {
  77627. return this._defaultModel;
  77628. },
  77629. enumerable: true,
  77630. configurable: true
  77631. });
  77632. /**
  77633. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  77634. */
  77635. WebVRController.prototype.update = function () {
  77636. _super.prototype.update.call(this);
  77637. for (var index = 0; index < this._buttons.length; index++) {
  77638. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  77639. }
  77640. ;
  77641. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  77642. this.pad.x = this.leftStick.x;
  77643. this.pad.y = this.leftStick.y;
  77644. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  77645. }
  77646. };
  77647. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  77648. if (!newState) {
  77649. newState = {
  77650. pressed: false,
  77651. touched: false,
  77652. value: 0
  77653. };
  77654. }
  77655. if (!currentState) {
  77656. this._buttons[buttonIndex] = {
  77657. pressed: newState.pressed,
  77658. touched: newState.touched,
  77659. value: newState.value
  77660. };
  77661. return;
  77662. }
  77663. this._checkChanges(newState, currentState);
  77664. if (this._changes.changed) {
  77665. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  77666. this._handleButtonChange(buttonIndex, newState, this._changes);
  77667. }
  77668. this._buttons[buttonIndex].pressed = newState.pressed;
  77669. this._buttons[buttonIndex].touched = newState.touched;
  77670. // oculus triggers are never 0, thou not touched.
  77671. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  77672. };
  77673. WebVRController.prototype._checkChanges = function (newState, currentState) {
  77674. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  77675. this._changes.touchChanged = newState.touched !== currentState.touched;
  77676. this._changes.valueChanged = newState.value !== currentState.value;
  77677. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  77678. return this._changes;
  77679. };
  77680. /**
  77681. * Disposes of th webVRCOntroller
  77682. */
  77683. WebVRController.prototype.dispose = function () {
  77684. _super.prototype.dispose.call(this);
  77685. this.onTriggerStateChangedObservable.clear();
  77686. this.onMainButtonStateChangedObservable.clear();
  77687. this.onSecondaryButtonStateChangedObservable.clear();
  77688. this.onPadStateChangedObservable.clear();
  77689. this.onPadValuesChangedObservable.clear();
  77690. };
  77691. return WebVRController;
  77692. }(BABYLON.PoseEnabledController));
  77693. BABYLON.WebVRController = WebVRController;
  77694. })(BABYLON || (BABYLON = {}));
  77695. //# sourceMappingURL=babylon.webVRController.js.map
  77696. var BABYLON;
  77697. (function (BABYLON) {
  77698. /**
  77699. * Oculus Touch Controller
  77700. */
  77701. var OculusTouchController = /** @class */ (function (_super) {
  77702. __extends(OculusTouchController, _super);
  77703. /**
  77704. * Creates a new OculusTouchController from a gamepad
  77705. * @param vrGamepad the gamepad that the controller should be created from
  77706. */
  77707. function OculusTouchController(vrGamepad) {
  77708. var _this = _super.call(this, vrGamepad) || this;
  77709. /**
  77710. * Fired when the secondary trigger on this controller is modified
  77711. */
  77712. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  77713. /**
  77714. * Fired when the thumb rest on this controller is modified
  77715. */
  77716. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  77717. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  77718. return _this;
  77719. }
  77720. /**
  77721. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77722. * @param scene scene in which to add meshes
  77723. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77724. */
  77725. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77726. var _this = this;
  77727. var meshName;
  77728. // Hand
  77729. if (this.hand === 'left') {
  77730. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  77731. }
  77732. else { // Right is the default if no hand is specified
  77733. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  77734. }
  77735. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  77736. /*
  77737. Parent Mesh name: oculus_touch_left
  77738. - body
  77739. - trigger
  77740. - thumbstick
  77741. - grip
  77742. - button_y
  77743. - button_x
  77744. - button_enter
  77745. */
  77746. _this._defaultModel = newMeshes[1];
  77747. _this.attachToMesh(_this._defaultModel);
  77748. if (meshLoaded) {
  77749. meshLoaded(_this._defaultModel);
  77750. }
  77751. });
  77752. };
  77753. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  77754. /**
  77755. * Fired when the A button on this controller is modified
  77756. */
  77757. get: function () {
  77758. if (this.hand === 'right') {
  77759. return this.onMainButtonStateChangedObservable;
  77760. }
  77761. else {
  77762. throw new Error('No A button on left hand');
  77763. }
  77764. },
  77765. enumerable: true,
  77766. configurable: true
  77767. });
  77768. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  77769. /**
  77770. * Fired when the B button on this controller is modified
  77771. */
  77772. get: function () {
  77773. if (this.hand === 'right') {
  77774. return this.onSecondaryButtonStateChangedObservable;
  77775. }
  77776. else {
  77777. throw new Error('No B button on left hand');
  77778. }
  77779. },
  77780. enumerable: true,
  77781. configurable: true
  77782. });
  77783. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  77784. /**
  77785. * Fired when the X button on this controller is modified
  77786. */
  77787. get: function () {
  77788. if (this.hand === 'left') {
  77789. return this.onMainButtonStateChangedObservable;
  77790. }
  77791. else {
  77792. throw new Error('No X button on right hand');
  77793. }
  77794. },
  77795. enumerable: true,
  77796. configurable: true
  77797. });
  77798. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  77799. /**
  77800. * Fired when the Y button on this controller is modified
  77801. */
  77802. get: function () {
  77803. if (this.hand === 'left') {
  77804. return this.onSecondaryButtonStateChangedObservable;
  77805. }
  77806. else {
  77807. throw new Error('No Y button on right hand');
  77808. }
  77809. },
  77810. enumerable: true,
  77811. configurable: true
  77812. });
  77813. /**
  77814. * Called once for each button that changed state since the last frame
  77815. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  77816. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  77817. * 2) secondary trigger (same)
  77818. * 3) A (right) X (left), touch, pressed = value
  77819. * 4) B / Y
  77820. * 5) thumb rest
  77821. * @param buttonIdx Which button index changed
  77822. * @param state New state of the button
  77823. * @param changes Which properties on the state changed since last frame
  77824. */
  77825. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77826. var notifyObject = state; //{ state: state, changes: changes };
  77827. var triggerDirection = this.hand === 'right' ? -1 : 1;
  77828. switch (buttonIdx) {
  77829. case 0:
  77830. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  77831. return;
  77832. case 1: // index trigger
  77833. if (this._defaultModel) {
  77834. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  77835. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  77836. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  77837. }
  77838. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  77839. return;
  77840. case 2: // secondary trigger
  77841. if (this._defaultModel) {
  77842. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  77843. }
  77844. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  77845. return;
  77846. case 3:
  77847. if (this._defaultModel) {
  77848. if (notifyObject.pressed) {
  77849. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  77850. }
  77851. else {
  77852. (this._defaultModel.getChildren()[1]).position.y = 0;
  77853. }
  77854. }
  77855. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  77856. return;
  77857. case 4:
  77858. if (this._defaultModel) {
  77859. if (notifyObject.pressed) {
  77860. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  77861. }
  77862. else {
  77863. (this._defaultModel.getChildren()[2]).position.y = 0;
  77864. }
  77865. }
  77866. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  77867. return;
  77868. case 5:
  77869. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  77870. return;
  77871. }
  77872. };
  77873. /**
  77874. * Base Url for the controller model.
  77875. */
  77876. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  77877. /**
  77878. * File name for the left controller model.
  77879. */
  77880. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  77881. /**
  77882. * File name for the right controller model.
  77883. */
  77884. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  77885. return OculusTouchController;
  77886. }(BABYLON.WebVRController));
  77887. BABYLON.OculusTouchController = OculusTouchController;
  77888. })(BABYLON || (BABYLON = {}));
  77889. //# sourceMappingURL=babylon.oculusTouchController.js.map
  77890. var BABYLON;
  77891. (function (BABYLON) {
  77892. /**
  77893. * Vive Controller
  77894. */
  77895. var ViveController = /** @class */ (function (_super) {
  77896. __extends(ViveController, _super);
  77897. /**
  77898. * Creates a new ViveController from a gamepad
  77899. * @param vrGamepad the gamepad that the controller should be created from
  77900. */
  77901. function ViveController(vrGamepad) {
  77902. var _this = _super.call(this, vrGamepad) || this;
  77903. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  77904. _this._invertLeftStickY = true;
  77905. return _this;
  77906. }
  77907. /**
  77908. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77909. * @param scene scene in which to add meshes
  77910. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77911. */
  77912. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77913. var _this = this;
  77914. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  77915. /*
  77916. Parent Mesh name: ViveWand
  77917. - body
  77918. - r_gripper
  77919. - l_gripper
  77920. - menu_button
  77921. - system_button
  77922. - trackpad
  77923. - trigger
  77924. - LED
  77925. */
  77926. _this._defaultModel = newMeshes[1];
  77927. _this.attachToMesh(_this._defaultModel);
  77928. if (meshLoaded) {
  77929. meshLoaded(_this._defaultModel);
  77930. }
  77931. });
  77932. };
  77933. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  77934. /**
  77935. * Fired when the left button on this controller is modified
  77936. */
  77937. get: function () {
  77938. return this.onMainButtonStateChangedObservable;
  77939. },
  77940. enumerable: true,
  77941. configurable: true
  77942. });
  77943. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  77944. /**
  77945. * Fired when the right button on this controller is modified
  77946. */
  77947. get: function () {
  77948. return this.onMainButtonStateChangedObservable;
  77949. },
  77950. enumerable: true,
  77951. configurable: true
  77952. });
  77953. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  77954. /**
  77955. * Fired when the menu button on this controller is modified
  77956. */
  77957. get: function () {
  77958. return this.onSecondaryButtonStateChangedObservable;
  77959. },
  77960. enumerable: true,
  77961. configurable: true
  77962. });
  77963. /**
  77964. * Called once for each button that changed state since the last frame
  77965. * Vive mapping:
  77966. * 0: touchpad
  77967. * 1: trigger
  77968. * 2: left AND right buttons
  77969. * 3: menu button
  77970. * @param buttonIdx Which button index changed
  77971. * @param state New state of the button
  77972. * @param changes Which properties on the state changed since last frame
  77973. */
  77974. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77975. var notifyObject = state; //{ state: state, changes: changes };
  77976. switch (buttonIdx) {
  77977. case 0:
  77978. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  77979. return;
  77980. case 1: // index trigger
  77981. if (this._defaultModel) {
  77982. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  77983. }
  77984. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  77985. return;
  77986. case 2: // left AND right button
  77987. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  77988. return;
  77989. case 3:
  77990. if (this._defaultModel) {
  77991. if (notifyObject.pressed) {
  77992. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  77993. }
  77994. else {
  77995. (this._defaultModel.getChildren()[2]).position.y = 0;
  77996. }
  77997. }
  77998. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  77999. return;
  78000. }
  78001. };
  78002. /**
  78003. * Base Url for the controller model.
  78004. */
  78005. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  78006. /**
  78007. * File name for the controller model.
  78008. */
  78009. ViveController.MODEL_FILENAME = 'wand.babylon';
  78010. return ViveController;
  78011. }(BABYLON.WebVRController));
  78012. BABYLON.ViveController = ViveController;
  78013. })(BABYLON || (BABYLON = {}));
  78014. //# sourceMappingURL=babylon.viveController.js.map
  78015. var BABYLON;
  78016. (function (BABYLON) {
  78017. /**
  78018. * Generic Controller
  78019. */
  78020. var GenericController = /** @class */ (function (_super) {
  78021. __extends(GenericController, _super);
  78022. /**
  78023. * Creates a new GenericController from a gamepad
  78024. * @param vrGamepad the gamepad that the controller should be created from
  78025. */
  78026. function GenericController(vrGamepad) {
  78027. return _super.call(this, vrGamepad) || this;
  78028. }
  78029. /**
  78030. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78031. * @param scene scene in which to add meshes
  78032. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78033. */
  78034. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78035. var _this = this;
  78036. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  78037. _this._defaultModel = newMeshes[1];
  78038. _this.attachToMesh(_this._defaultModel);
  78039. if (meshLoaded) {
  78040. meshLoaded(_this._defaultModel);
  78041. }
  78042. });
  78043. };
  78044. /**
  78045. * Called once for each button that changed state since the last frame
  78046. * @param buttonIdx Which button index changed
  78047. * @param state New state of the button
  78048. * @param changes Which properties on the state changed since last frame
  78049. */
  78050. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78051. console.log("Button id: " + buttonIdx + "state: ");
  78052. console.dir(state);
  78053. };
  78054. /**
  78055. * Base Url for the controller model.
  78056. */
  78057. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78058. /**
  78059. * File name for the controller model.
  78060. */
  78061. GenericController.MODEL_FILENAME = 'generic.babylon';
  78062. return GenericController;
  78063. }(BABYLON.WebVRController));
  78064. BABYLON.GenericController = GenericController;
  78065. })(BABYLON || (BABYLON = {}));
  78066. //# sourceMappingURL=babylon.genericController.js.map
  78067. var BABYLON;
  78068. (function (BABYLON) {
  78069. /**
  78070. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  78071. */
  78072. var LoadedMeshInfo = /** @class */ (function () {
  78073. function LoadedMeshInfo() {
  78074. /**
  78075. * Map of the button meshes contained in the controller
  78076. */
  78077. this.buttonMeshes = {};
  78078. /**
  78079. * Map of the axis meshes contained in the controller
  78080. */
  78081. this.axisMeshes = {};
  78082. }
  78083. return LoadedMeshInfo;
  78084. }());
  78085. /**
  78086. * Defines the WindowsMotionController object that the state of the windows motion controller
  78087. */
  78088. var WindowsMotionController = /** @class */ (function (_super) {
  78089. __extends(WindowsMotionController, _super);
  78090. /**
  78091. * Creates a new WindowsMotionController from a gamepad
  78092. * @param vrGamepad the gamepad that the controller should be created from
  78093. */
  78094. function WindowsMotionController(vrGamepad) {
  78095. var _this = _super.call(this, vrGamepad) || this;
  78096. _this._mapping = {
  78097. // Semantic button names
  78098. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  78099. // A mapping of the button name to glTF model node name
  78100. // that should be transformed by button value.
  78101. buttonMeshNames: {
  78102. 'trigger': 'SELECT',
  78103. 'menu': 'MENU',
  78104. 'grip': 'GRASP',
  78105. 'thumbstick': 'THUMBSTICK_PRESS',
  78106. 'trackpad': 'TOUCHPAD_PRESS'
  78107. },
  78108. // This mapping is used to translate from the Motion Controller to Babylon semantics
  78109. buttonObservableNames: {
  78110. 'trigger': 'onTriggerStateChangedObservable',
  78111. 'menu': 'onSecondaryButtonStateChangedObservable',
  78112. 'grip': 'onMainButtonStateChangedObservable',
  78113. 'thumbstick': 'onPadStateChangedObservable',
  78114. 'trackpad': 'onTrackpadChangedObservable'
  78115. },
  78116. // A mapping of the axis name to glTF model node name
  78117. // that should be transformed by axis value.
  78118. // This array mirrors the browserGamepad.axes array, such that
  78119. // the mesh corresponding to axis 0 is in this array index 0.
  78120. axisMeshNames: [
  78121. 'THUMBSTICK_X',
  78122. 'THUMBSTICK_Y',
  78123. 'TOUCHPAD_TOUCH_X',
  78124. 'TOUCHPAD_TOUCH_Y'
  78125. ],
  78126. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  78127. };
  78128. /**
  78129. * Fired when the trackpad on this controller is clicked
  78130. */
  78131. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  78132. /**
  78133. * Fired when the trackpad on this controller is modified
  78134. */
  78135. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  78136. /**
  78137. * The current x and y values of this controller's trackpad
  78138. */
  78139. _this.trackpad = { x: 0, y: 0 };
  78140. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  78141. _this._loadedMeshInfo = null;
  78142. return _this;
  78143. }
  78144. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  78145. /**
  78146. * Fired when the trigger on this controller is modified
  78147. */
  78148. get: function () {
  78149. return this.onTriggerStateChangedObservable;
  78150. },
  78151. enumerable: true,
  78152. configurable: true
  78153. });
  78154. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  78155. /**
  78156. * Fired when the menu button on this controller is modified
  78157. */
  78158. get: function () {
  78159. return this.onSecondaryButtonStateChangedObservable;
  78160. },
  78161. enumerable: true,
  78162. configurable: true
  78163. });
  78164. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  78165. /**
  78166. * Fired when the grip button on this controller is modified
  78167. */
  78168. get: function () {
  78169. return this.onMainButtonStateChangedObservable;
  78170. },
  78171. enumerable: true,
  78172. configurable: true
  78173. });
  78174. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  78175. /**
  78176. * Fired when the thumbstick button on this controller is modified
  78177. */
  78178. get: function () {
  78179. return this.onPadStateChangedObservable;
  78180. },
  78181. enumerable: true,
  78182. configurable: true
  78183. });
  78184. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  78185. /**
  78186. * Fired when the touchpad button on this controller is modified
  78187. */
  78188. get: function () {
  78189. return this.onTrackpadChangedObservable;
  78190. },
  78191. enumerable: true,
  78192. configurable: true
  78193. });
  78194. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  78195. /**
  78196. * Fired when the touchpad values on this controller are modified
  78197. */
  78198. get: function () {
  78199. return this.onTrackpadValuesChangedObservable;
  78200. },
  78201. enumerable: true,
  78202. configurable: true
  78203. });
  78204. WindowsMotionController.prototype._updateTrackpad = function () {
  78205. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  78206. this.trackpad.x = this.browserGamepad["axes"][2];
  78207. this.trackpad.y = this.browserGamepad["axes"][3];
  78208. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  78209. }
  78210. };
  78211. /**
  78212. * Called once per frame by the engine.
  78213. */
  78214. WindowsMotionController.prototype.update = function () {
  78215. _super.prototype.update.call(this);
  78216. if (this.browserGamepad.axes) {
  78217. this._updateTrackpad();
  78218. // Only need to animate axes if there is a loaded mesh
  78219. if (this._loadedMeshInfo) {
  78220. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  78221. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  78222. }
  78223. }
  78224. }
  78225. };
  78226. /**
  78227. * Called once for each button that changed state since the last frame
  78228. * @param buttonIdx Which button index changed
  78229. * @param state New state of the button
  78230. * @param changes Which properties on the state changed since last frame
  78231. */
  78232. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78233. var buttonName = this._mapping.buttons[buttonIdx];
  78234. if (!buttonName) {
  78235. return;
  78236. }
  78237. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  78238. this._updateTrackpad();
  78239. // Only emit events for buttons that we know how to map from index to name
  78240. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  78241. if (observable) {
  78242. observable.notifyObservers(state);
  78243. }
  78244. this._lerpButtonTransform(buttonName, state.value);
  78245. };
  78246. /**
  78247. * Moves the buttons on the controller mesh based on their current state
  78248. * @param buttonName the name of the button to move
  78249. * @param buttonValue the value of the button which determines the buttons new position
  78250. */
  78251. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  78252. // If there is no loaded mesh, there is nothing to transform.
  78253. if (!this._loadedMeshInfo) {
  78254. return;
  78255. }
  78256. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  78257. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  78258. return;
  78259. }
  78260. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  78261. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  78262. };
  78263. /**
  78264. * Moves the axis on the controller mesh based on its current state
  78265. * @param axis the index of the axis
  78266. * @param axisValue the value of the axis which determines the meshes new position
  78267. * @hidden
  78268. */
  78269. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  78270. if (!this._loadedMeshInfo) {
  78271. return;
  78272. }
  78273. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  78274. if (!meshInfo) {
  78275. return;
  78276. }
  78277. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  78278. return;
  78279. }
  78280. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  78281. var lerpValue = axisValue * 0.5 + 0.5;
  78282. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  78283. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  78284. };
  78285. /**
  78286. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78287. * @param scene scene in which to add meshes
  78288. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78289. */
  78290. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  78291. var _this = this;
  78292. if (forceDefault === void 0) { forceDefault = false; }
  78293. var path;
  78294. var filename;
  78295. // Checking if GLB loader is present
  78296. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  78297. // Determine the device specific folder based on the ID suffix
  78298. var device = 'default';
  78299. if (this.id && !forceDefault) {
  78300. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  78301. device = ((match && match[0]) || device);
  78302. }
  78303. // Hand
  78304. if (this.hand === 'left') {
  78305. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  78306. }
  78307. else { // Right is the default if no hand is specified
  78308. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  78309. }
  78310. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  78311. }
  78312. else {
  78313. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  78314. path = BABYLON.GenericController.MODEL_BASE_URL;
  78315. filename = BABYLON.GenericController.MODEL_FILENAME;
  78316. }
  78317. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  78318. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  78319. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  78320. if (!_this._loadedMeshInfo) {
  78321. return;
  78322. }
  78323. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  78324. _this.attachToMesh(_this._defaultModel);
  78325. if (meshLoaded) {
  78326. meshLoaded(_this._defaultModel);
  78327. }
  78328. }, null, function (scene, message) {
  78329. BABYLON.Tools.Log(message);
  78330. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  78331. if (!forceDefault) {
  78332. _this.initControllerMesh(scene, meshLoaded, true);
  78333. }
  78334. });
  78335. };
  78336. /**
  78337. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  78338. * can be transformed by button presses and axes values, based on this._mapping.
  78339. *
  78340. * @param scene scene in which the meshes exist
  78341. * @param meshes list of meshes that make up the controller model to process
  78342. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  78343. */
  78344. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  78345. var loadedMeshInfo = null;
  78346. // Create a new mesh to contain the glTF hierarchy
  78347. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  78348. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  78349. var childMesh = null;
  78350. for (var i = 0; i < meshes.length; i++) {
  78351. var mesh = meshes[i];
  78352. if (!mesh.parent) {
  78353. // Exclude controller meshes from picking results
  78354. mesh.isPickable = false;
  78355. // Handle root node, attach to the new parentMesh
  78356. childMesh = mesh;
  78357. break;
  78358. }
  78359. }
  78360. if (childMesh) {
  78361. childMesh.setParent(parentMesh);
  78362. // Create our mesh info. Note that this method will always return non-null.
  78363. loadedMeshInfo = this.createMeshInfo(parentMesh);
  78364. }
  78365. else {
  78366. BABYLON.Tools.Warn('Could not find root node in model file.');
  78367. }
  78368. return loadedMeshInfo;
  78369. };
  78370. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  78371. var loadedMeshInfo = new LoadedMeshInfo();
  78372. var i;
  78373. loadedMeshInfo.rootNode = rootNode;
  78374. // Reset the caches
  78375. loadedMeshInfo.buttonMeshes = {};
  78376. loadedMeshInfo.axisMeshes = {};
  78377. // Button Meshes
  78378. for (i = 0; i < this._mapping.buttons.length; i++) {
  78379. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  78380. if (!buttonMeshName) {
  78381. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  78382. continue;
  78383. }
  78384. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  78385. if (!buttonMesh) {
  78386. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  78387. continue;
  78388. }
  78389. var buttonMeshInfo = {
  78390. index: i,
  78391. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  78392. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  78393. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  78394. };
  78395. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  78396. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  78397. }
  78398. else {
  78399. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  78400. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  78401. '(VALUE: ' + !!buttonMeshInfo.value +
  78402. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  78403. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  78404. ')');
  78405. }
  78406. }
  78407. // Axis Meshes
  78408. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  78409. var axisMeshName = this._mapping.axisMeshNames[i];
  78410. if (!axisMeshName) {
  78411. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  78412. continue;
  78413. }
  78414. var axisMesh = getChildByName(rootNode, axisMeshName);
  78415. if (!axisMesh) {
  78416. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  78417. continue;
  78418. }
  78419. var axisMeshInfo = {
  78420. index: i,
  78421. value: getImmediateChildByName(axisMesh, 'VALUE'),
  78422. min: getImmediateChildByName(axisMesh, 'MIN'),
  78423. max: getImmediateChildByName(axisMesh, 'MAX')
  78424. };
  78425. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  78426. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  78427. }
  78428. else {
  78429. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  78430. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  78431. '(VALUE: ' + !!axisMeshInfo.value +
  78432. ', MIN: ' + !!axisMeshInfo.min +
  78433. ', MAX:' + !!axisMeshInfo.max +
  78434. ')');
  78435. }
  78436. }
  78437. // Pointing Ray
  78438. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  78439. if (!loadedMeshInfo.pointingPoseNode) {
  78440. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  78441. }
  78442. else {
  78443. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  78444. }
  78445. return loadedMeshInfo;
  78446. // Look through all children recursively. This will return null if no mesh exists with the given name.
  78447. function getChildByName(node, name) {
  78448. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  78449. }
  78450. // Look through only immediate children. This will return null if no mesh exists with the given name.
  78451. function getImmediateChildByName(node, name) {
  78452. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  78453. }
  78454. };
  78455. /**
  78456. * Gets the ray of the controller in the direction the controller is pointing
  78457. * @param length the length the resulting ray should be
  78458. * @returns a ray in the direction the controller is pointing
  78459. */
  78460. WindowsMotionController.prototype.getForwardRay = function (length) {
  78461. if (length === void 0) { length = 100; }
  78462. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  78463. return _super.prototype.getForwardRay.call(this, length);
  78464. }
  78465. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  78466. var origin = m.getTranslation();
  78467. var forward = new BABYLON.Vector3(0, 0, -1);
  78468. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78469. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78470. return new BABYLON.Ray(origin, direction, length);
  78471. };
  78472. /**
  78473. * Disposes of the controller
  78474. */
  78475. WindowsMotionController.prototype.dispose = function () {
  78476. _super.prototype.dispose.call(this);
  78477. this.onTrackpadChangedObservable.clear();
  78478. };
  78479. /**
  78480. * The base url used to load the left and right controller models
  78481. */
  78482. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  78483. /**
  78484. * The name of the left controller model file
  78485. */
  78486. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  78487. /**
  78488. * The name of the right controller model file
  78489. */
  78490. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  78491. /**
  78492. * The controller name prefix for this controller type
  78493. */
  78494. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  78495. /**
  78496. * The controller id pattern for this controller type
  78497. */
  78498. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  78499. return WindowsMotionController;
  78500. }(BABYLON.WebVRController));
  78501. BABYLON.WindowsMotionController = WindowsMotionController;
  78502. })(BABYLON || (BABYLON = {}));
  78503. //# sourceMappingURL=babylon.windowsMotionController.js.map
  78504. var BABYLON;
  78505. (function (BABYLON) {
  78506. /**
  78507. * Gear VR Controller
  78508. */
  78509. var GearVRController = /** @class */ (function (_super) {
  78510. __extends(GearVRController, _super);
  78511. /**
  78512. * Creates a new GearVRController from a gamepad
  78513. * @param vrGamepad the gamepad that the controller should be created from
  78514. */
  78515. function GearVRController(vrGamepad) {
  78516. var _this = _super.call(this, vrGamepad) || this;
  78517. _this._maxRotationDistFromHeadset = Math.PI / 5;
  78518. _this._draggedRoomRotation = 0;
  78519. _this._tmpVector = new BABYLON.Vector3();
  78520. _this._buttonIndexToObservableNameMap = [
  78521. 'onTrackpadChangedObservable',
  78522. 'onTriggerStateChangedObservable' // Trigger
  78523. ];
  78524. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  78525. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  78526. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  78527. return _this;
  78528. }
  78529. /**
  78530. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  78531. * @param poseData raw pose fromthe device
  78532. */
  78533. GearVRController.prototype.updateFromDevice = function (poseData) {
  78534. _super.prototype.updateFromDevice.call(this, poseData);
  78535. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  78536. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  78537. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  78538. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  78539. // Find the radian distance away that the headset is from the controllers rotation
  78540. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  78541. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  78542. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  78543. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  78544. this._draggedRoomRotation += rotationAmount;
  78545. // Rotate controller around headset
  78546. var sin = Math.sin(-rotationAmount);
  78547. var cos = Math.cos(-rotationAmount);
  78548. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  78549. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  78550. }
  78551. }
  78552. }
  78553. };
  78554. /**
  78555. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78556. * @param scene scene in which to add meshes
  78557. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78558. */
  78559. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78560. var _this = this;
  78561. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  78562. // Offset the controller so it will rotate around the users wrist
  78563. var mesh = new BABYLON.Mesh("", scene);
  78564. newMeshes[1].parent = mesh;
  78565. newMeshes[1].position.z = -0.15;
  78566. _this._defaultModel = mesh;
  78567. _this.attachToMesh(_this._defaultModel);
  78568. if (meshLoaded) {
  78569. meshLoaded(_this._defaultModel);
  78570. }
  78571. });
  78572. };
  78573. /**
  78574. * Called once for each button that changed state since the last frame
  78575. * @param buttonIdx Which button index changed
  78576. * @param state New state of the button
  78577. * @param changes Which properties on the state changed since last frame
  78578. */
  78579. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78580. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  78581. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  78582. // Only emit events for buttons that we know how to map from index to observable
  78583. var observable = this[observableName];
  78584. if (observable) {
  78585. observable.notifyObservers(state);
  78586. }
  78587. }
  78588. };
  78589. /**
  78590. * Base Url for the controller model.
  78591. */
  78592. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78593. /**
  78594. * File name for the controller model.
  78595. */
  78596. GearVRController.MODEL_FILENAME = 'generic.babylon';
  78597. /**
  78598. * Gamepad Id prefix used to identify this controller.
  78599. */
  78600. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  78601. return GearVRController;
  78602. }(BABYLON.WebVRController));
  78603. BABYLON.GearVRController = GearVRController;
  78604. })(BABYLON || (BABYLON = {}));
  78605. //# sourceMappingURL=babylon.gearVRController.js.map
  78606. var BABYLON;
  78607. (function (BABYLON) {
  78608. /**
  78609. * Google Daydream controller
  78610. */
  78611. var DaydreamController = /** @class */ (function (_super) {
  78612. __extends(DaydreamController, _super);
  78613. /**
  78614. * Creates a new DaydreamController from a gamepad
  78615. * @param vrGamepad the gamepad that the controller should be created from
  78616. */
  78617. function DaydreamController(vrGamepad) {
  78618. var _this = _super.call(this, vrGamepad) || this;
  78619. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  78620. return _this;
  78621. }
  78622. /**
  78623. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78624. * @param scene scene in which to add meshes
  78625. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78626. */
  78627. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78628. var _this = this;
  78629. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  78630. _this._defaultModel = newMeshes[1];
  78631. _this.attachToMesh(_this._defaultModel);
  78632. if (meshLoaded) {
  78633. meshLoaded(_this._defaultModel);
  78634. }
  78635. });
  78636. };
  78637. /**
  78638. * Called once for each button that changed state since the last frame
  78639. * @param buttonIdx Which button index changed
  78640. * @param state New state of the button
  78641. * @param changes Which properties on the state changed since last frame
  78642. */
  78643. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78644. // Daydream controller only has 1 GamepadButton (on the trackpad).
  78645. if (buttonIdx === 0) {
  78646. var observable = this.onTriggerStateChangedObservable;
  78647. if (observable) {
  78648. observable.notifyObservers(state);
  78649. }
  78650. }
  78651. else {
  78652. // If the app or home buttons are ever made available
  78653. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  78654. }
  78655. };
  78656. /**
  78657. * Base Url for the controller model.
  78658. */
  78659. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78660. /**
  78661. * File name for the controller model.
  78662. */
  78663. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  78664. /**
  78665. * Gamepad Id prefix used to identify Daydream Controller.
  78666. */
  78667. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  78668. return DaydreamController;
  78669. }(BABYLON.WebVRController));
  78670. BABYLON.DaydreamController = DaydreamController;
  78671. })(BABYLON || (BABYLON = {}));
  78672. //# sourceMappingURL=babylon.daydreamController.js.map
  78673. var BABYLON;
  78674. (function (BABYLON) {
  78675. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  78676. get: function () {
  78677. if (!this._gamepadManager) {
  78678. this._gamepadManager = new BABYLON.GamepadManager(this);
  78679. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  78680. if (!component) {
  78681. component = new GamepadSystemSceneComponent(this);
  78682. this._addComponent(component);
  78683. }
  78684. }
  78685. return this._gamepadManager;
  78686. },
  78687. enumerable: true,
  78688. configurable: true
  78689. });
  78690. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  78691. this.add(new BABYLON.FreeCameraGamepadInput());
  78692. return this;
  78693. };
  78694. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  78695. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  78696. return this;
  78697. };
  78698. /**
  78699. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  78700. */
  78701. var GamepadSystemSceneComponent = /** @class */ (function () {
  78702. /**
  78703. * Creates a new instance of the component for the given scene
  78704. * @param scene Defines the scene to register the component in
  78705. */
  78706. function GamepadSystemSceneComponent(scene) {
  78707. /**
  78708. * The component name helpfull to identify the component in the list of scene components.
  78709. */
  78710. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  78711. this.scene = scene;
  78712. }
  78713. /**
  78714. * Registers the component in a given scene
  78715. */
  78716. GamepadSystemSceneComponent.prototype.register = function () {
  78717. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  78718. };
  78719. /**
  78720. * Rebuilds the elements related to this component in case of
  78721. * context lost for instance.
  78722. */
  78723. GamepadSystemSceneComponent.prototype.rebuild = function () {
  78724. // Nothing to do for gamepads
  78725. };
  78726. /**
  78727. * Disposes the component and the associated ressources
  78728. */
  78729. GamepadSystemSceneComponent.prototype.dispose = function () {
  78730. var gamepadManager = this.scene._gamepadManager;
  78731. if (gamepadManager) {
  78732. gamepadManager.dispose();
  78733. this.scene._gamepadManager = null;
  78734. }
  78735. };
  78736. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  78737. var gamepadManager = this.scene._gamepadManager;
  78738. if (gamepadManager && gamepadManager._isMonitoring) {
  78739. gamepadManager._checkGamepadsStatus();
  78740. }
  78741. };
  78742. return GamepadSystemSceneComponent;
  78743. }());
  78744. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  78745. })(BABYLON || (BABYLON = {}));
  78746. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  78747. var BABYLON;
  78748. (function (BABYLON) {
  78749. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  78750. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  78751. });
  78752. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  78753. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  78754. });
  78755. /**
  78756. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  78757. * an arc rotate version arcFollowCamera are available.
  78758. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78759. */
  78760. var FollowCamera = /** @class */ (function (_super) {
  78761. __extends(FollowCamera, _super);
  78762. /**
  78763. * Instantiates the follow camera.
  78764. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78765. * @param name Define the name of the camera in the scene
  78766. * @param position Define the position of the camera
  78767. * @param scene Define the scene the camera belong to
  78768. * @param lockedTarget Define the target of the camera
  78769. */
  78770. function FollowCamera(name, position, scene, lockedTarget) {
  78771. if (lockedTarget === void 0) { lockedTarget = null; }
  78772. var _this = _super.call(this, name, position, scene) || this;
  78773. /**
  78774. * Distance the follow camera should follow an object at
  78775. */
  78776. _this.radius = 12;
  78777. /**
  78778. * Define a rotation offset between the camera and the object it follows
  78779. */
  78780. _this.rotationOffset = 0;
  78781. /**
  78782. * Define a height offset between the camera and the object it follows.
  78783. * It can help following an object from the top (like a car chaing a plane)
  78784. */
  78785. _this.heightOffset = 4;
  78786. /**
  78787. * Define how fast the camera can accelerate to follow it s target.
  78788. */
  78789. _this.cameraAcceleration = 0.05;
  78790. /**
  78791. * Define the speed limit of the camera following an object.
  78792. */
  78793. _this.maxCameraSpeed = 20;
  78794. _this.lockedTarget = lockedTarget;
  78795. return _this;
  78796. }
  78797. FollowCamera.prototype._follow = function (cameraTarget) {
  78798. if (!cameraTarget)
  78799. return;
  78800. var yRotation;
  78801. if (cameraTarget.rotationQuaternion) {
  78802. var rotMatrix = new BABYLON.Matrix();
  78803. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  78804. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  78805. }
  78806. else {
  78807. yRotation = cameraTarget.rotation.y;
  78808. }
  78809. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  78810. var targetPosition = cameraTarget.getAbsolutePosition();
  78811. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  78812. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  78813. var dx = targetX - this.position.x;
  78814. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  78815. var dz = (targetZ) - this.position.z;
  78816. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  78817. var vy = dy * this.cameraAcceleration;
  78818. var vz = dz * this.cameraAcceleration * 2;
  78819. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  78820. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78821. }
  78822. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  78823. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78824. }
  78825. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  78826. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78827. }
  78828. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  78829. this.setTarget(targetPosition);
  78830. };
  78831. /** @hidden */
  78832. FollowCamera.prototype._checkInputs = function () {
  78833. _super.prototype._checkInputs.call(this);
  78834. if (this.lockedTarget) {
  78835. this._follow(this.lockedTarget);
  78836. }
  78837. };
  78838. /**
  78839. * Gets the camera class name.
  78840. * @returns the class name
  78841. */
  78842. FollowCamera.prototype.getClassName = function () {
  78843. return "FollowCamera";
  78844. };
  78845. __decorate([
  78846. BABYLON.serialize()
  78847. ], FollowCamera.prototype, "radius", void 0);
  78848. __decorate([
  78849. BABYLON.serialize()
  78850. ], FollowCamera.prototype, "rotationOffset", void 0);
  78851. __decorate([
  78852. BABYLON.serialize()
  78853. ], FollowCamera.prototype, "heightOffset", void 0);
  78854. __decorate([
  78855. BABYLON.serialize()
  78856. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  78857. __decorate([
  78858. BABYLON.serialize()
  78859. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  78860. __decorate([
  78861. BABYLON.serializeAsMeshReference("lockedTargetId")
  78862. ], FollowCamera.prototype, "lockedTarget", void 0);
  78863. return FollowCamera;
  78864. }(BABYLON.TargetCamera));
  78865. BABYLON.FollowCamera = FollowCamera;
  78866. /**
  78867. * Arc Rotate version of the follow camera.
  78868. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  78869. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78870. */
  78871. var ArcFollowCamera = /** @class */ (function (_super) {
  78872. __extends(ArcFollowCamera, _super);
  78873. /**
  78874. * Instantiates a new ArcFollowCamera
  78875. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78876. * @param name Define the name of the camera
  78877. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  78878. * @param beta Define the rotation angle of the camera around the elevation axis
  78879. * @param radius Define the radius of the camera from its target point
  78880. * @param target Define the target of the camera
  78881. * @param scene Define the scene the camera belongs to
  78882. */
  78883. function ArcFollowCamera(name,
  78884. /** The longitudinal angle of the camera */
  78885. alpha,
  78886. /** The latitudinal angle of the camera */
  78887. beta,
  78888. /** The radius of the camera from its target */
  78889. radius,
  78890. /** Define the camera target (the messh it should follow) */
  78891. target, scene) {
  78892. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  78893. _this.alpha = alpha;
  78894. _this.beta = beta;
  78895. _this.radius = radius;
  78896. _this.target = target;
  78897. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  78898. _this._follow();
  78899. return _this;
  78900. }
  78901. ArcFollowCamera.prototype._follow = function () {
  78902. if (!this.target) {
  78903. return;
  78904. }
  78905. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  78906. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  78907. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  78908. var targetPosition = this.target.getAbsolutePosition();
  78909. this.position = targetPosition.add(this._cartesianCoordinates);
  78910. this.setTarget(targetPosition);
  78911. };
  78912. /** @hidden */
  78913. ArcFollowCamera.prototype._checkInputs = function () {
  78914. _super.prototype._checkInputs.call(this);
  78915. this._follow();
  78916. };
  78917. /**
  78918. * Returns the class name of the object.
  78919. * It is mostly used internally for serialization purposes.
  78920. */
  78921. ArcFollowCamera.prototype.getClassName = function () {
  78922. return "ArcFollowCamera";
  78923. };
  78924. return ArcFollowCamera;
  78925. }(BABYLON.TargetCamera));
  78926. BABYLON.ArcFollowCamera = ArcFollowCamera;
  78927. })(BABYLON || (BABYLON = {}));
  78928. //# sourceMappingURL=babylon.followCamera.js.map
  78929. var BABYLON;
  78930. (function (BABYLON) {
  78931. /**
  78932. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  78933. * which still works and will still be found in many Playgrounds.
  78934. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78935. */
  78936. var UniversalCamera = /** @class */ (function (_super) {
  78937. __extends(UniversalCamera, _super);
  78938. /**
  78939. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  78940. * which still works and will still be found in many Playgrounds.
  78941. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78942. * @param name Define the name of the camera in the scene
  78943. * @param position Define the start position of the camera in the scene
  78944. * @param scene Define the scene the camera belongs to
  78945. */
  78946. function UniversalCamera(name, position, scene) {
  78947. var _this = _super.call(this, name, position, scene) || this;
  78948. _this.inputs.addGamepad();
  78949. return _this;
  78950. }
  78951. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  78952. /**
  78953. * Defines the gamepad rotation sensiblity.
  78954. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78955. */
  78956. get: function () {
  78957. var gamepad = this.inputs.attached["gamepad"];
  78958. if (gamepad)
  78959. return gamepad.gamepadAngularSensibility;
  78960. return 0;
  78961. },
  78962. set: function (value) {
  78963. var gamepad = this.inputs.attached["gamepad"];
  78964. if (gamepad)
  78965. gamepad.gamepadAngularSensibility = value;
  78966. },
  78967. enumerable: true,
  78968. configurable: true
  78969. });
  78970. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  78971. /**
  78972. * Defines the gamepad move sensiblity.
  78973. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78974. */
  78975. get: function () {
  78976. var gamepad = this.inputs.attached["gamepad"];
  78977. if (gamepad)
  78978. return gamepad.gamepadMoveSensibility;
  78979. return 0;
  78980. },
  78981. set: function (value) {
  78982. var gamepad = this.inputs.attached["gamepad"];
  78983. if (gamepad)
  78984. gamepad.gamepadMoveSensibility = value;
  78985. },
  78986. enumerable: true,
  78987. configurable: true
  78988. });
  78989. /**
  78990. * Gets the current object class name.
  78991. * @return the class name
  78992. */
  78993. UniversalCamera.prototype.getClassName = function () {
  78994. return "UniversalCamera";
  78995. };
  78996. return UniversalCamera;
  78997. }(BABYLON.TouchCamera));
  78998. BABYLON.UniversalCamera = UniversalCamera;
  78999. })(BABYLON || (BABYLON = {}));
  79000. //# sourceMappingURL=babylon.universalCamera.js.map
  79001. var BABYLON;
  79002. (function (BABYLON) {
  79003. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  79004. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  79005. });
  79006. /**
  79007. * This represents a FPS type of camera. This is only here for back compat purpose.
  79008. * Please use the UniversalCamera instead as both are identical.
  79009. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79010. */
  79011. var GamepadCamera = /** @class */ (function (_super) {
  79012. __extends(GamepadCamera, _super);
  79013. /**
  79014. * Instantiates a new Gamepad Camera
  79015. * This represents a FPS type of camera. This is only here for back compat purpose.
  79016. * Please use the UniversalCamera instead as both are identical.
  79017. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79018. * @param name Define the name of the camera in the scene
  79019. * @param position Define the start position of the camera in the scene
  79020. * @param scene Define the scene the camera belongs to
  79021. */
  79022. function GamepadCamera(name, position, scene) {
  79023. return _super.call(this, name, position, scene) || this;
  79024. }
  79025. /**
  79026. * Gets the current object class name.
  79027. * @return the class name
  79028. */
  79029. GamepadCamera.prototype.getClassName = function () {
  79030. return "GamepadCamera";
  79031. };
  79032. return GamepadCamera;
  79033. }(BABYLON.UniversalCamera));
  79034. BABYLON.GamepadCamera = GamepadCamera;
  79035. })(BABYLON || (BABYLON = {}));
  79036. //# sourceMappingURL=babylon.gamepadCamera.js.map
  79037. var BABYLON;
  79038. (function (BABYLON) {
  79039. var PostProcessRenderPipelineManager = /** @class */ (function () {
  79040. function PostProcessRenderPipelineManager() {
  79041. this._renderPipelines = {};
  79042. }
  79043. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  79044. this._renderPipelines[renderPipeline._name] = renderPipeline;
  79045. };
  79046. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  79047. if (unique === void 0) { unique = false; }
  79048. var renderPipeline = this._renderPipelines[renderPipelineName];
  79049. if (!renderPipeline) {
  79050. return;
  79051. }
  79052. renderPipeline._attachCameras(cameras, unique);
  79053. };
  79054. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  79055. var renderPipeline = this._renderPipelines[renderPipelineName];
  79056. if (!renderPipeline) {
  79057. return;
  79058. }
  79059. renderPipeline._detachCameras(cameras);
  79060. };
  79061. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79062. var renderPipeline = this._renderPipelines[renderPipelineName];
  79063. if (!renderPipeline) {
  79064. return;
  79065. }
  79066. renderPipeline._enableEffect(renderEffectName, cameras);
  79067. };
  79068. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79069. var renderPipeline = this._renderPipelines[renderPipelineName];
  79070. if (!renderPipeline) {
  79071. return;
  79072. }
  79073. renderPipeline._disableEffect(renderEffectName, cameras);
  79074. };
  79075. PostProcessRenderPipelineManager.prototype.update = function () {
  79076. for (var renderPipelineName in this._renderPipelines) {
  79077. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79078. var pipeline = this._renderPipelines[renderPipelineName];
  79079. if (!pipeline.isSupported) {
  79080. pipeline.dispose();
  79081. delete this._renderPipelines[renderPipelineName];
  79082. }
  79083. else {
  79084. pipeline._update();
  79085. }
  79086. }
  79087. }
  79088. };
  79089. /** @hidden */
  79090. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  79091. for (var renderPipelineName in this._renderPipelines) {
  79092. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79093. var pipeline = this._renderPipelines[renderPipelineName];
  79094. pipeline._rebuild();
  79095. }
  79096. }
  79097. };
  79098. PostProcessRenderPipelineManager.prototype.dispose = function () {
  79099. for (var renderPipelineName in this._renderPipelines) {
  79100. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79101. var pipeline = this._renderPipelines[renderPipelineName];
  79102. pipeline.dispose();
  79103. }
  79104. }
  79105. };
  79106. return PostProcessRenderPipelineManager;
  79107. }());
  79108. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  79109. })(BABYLON || (BABYLON = {}));
  79110. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  79111. var BABYLON;
  79112. (function (BABYLON) {
  79113. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  79114. get: function () {
  79115. if (!this._postProcessRenderPipelineManager) {
  79116. // Register the G Buffer component to the scene.
  79117. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  79118. if (!component) {
  79119. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  79120. this._addComponent(component);
  79121. }
  79122. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  79123. }
  79124. return this._postProcessRenderPipelineManager;
  79125. },
  79126. enumerable: true,
  79127. configurable: true
  79128. });
  79129. /**
  79130. * Defines the Render Pipeline scene component responsible to rendering pipelines
  79131. */
  79132. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  79133. /**
  79134. * Creates a new instance of the component for the given scene
  79135. * @param scene Defines the scene to register the component in
  79136. */
  79137. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  79138. /**
  79139. * The component name helpfull to identify the component in the list of scene components.
  79140. */
  79141. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  79142. this.scene = scene;
  79143. }
  79144. /**
  79145. * Registers the component in a given scene
  79146. */
  79147. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  79148. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  79149. };
  79150. /**
  79151. * Rebuilds the elements related to this component in case of
  79152. * context lost for instance.
  79153. */
  79154. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  79155. if (this.scene._postProcessRenderPipelineManager) {
  79156. this.scene._postProcessRenderPipelineManager._rebuild();
  79157. }
  79158. };
  79159. /**
  79160. * Disposes the component and the associated ressources
  79161. */
  79162. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  79163. if (this.scene._postProcessRenderPipelineManager) {
  79164. this.scene._postProcessRenderPipelineManager.dispose();
  79165. }
  79166. };
  79167. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  79168. if (this.scene._postProcessRenderPipelineManager) {
  79169. this.scene._postProcessRenderPipelineManager.update();
  79170. }
  79171. };
  79172. return PostProcessRenderPipelineManagerSceneComponent;
  79173. }());
  79174. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  79175. })(BABYLON || (BABYLON = {}));
  79176. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  79177. var BABYLON;
  79178. (function (BABYLON) {
  79179. /**
  79180. * This represents a set of one or more post processes in Babylon.
  79181. * A post process can be used to apply a shader to a texture after it is rendered.
  79182. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  79183. */
  79184. var PostProcessRenderEffect = /** @class */ (function () {
  79185. /**
  79186. * Instantiates a post process render effect.
  79187. * A post process can be used to apply a shader to a texture after it is rendered.
  79188. * @param engine The engine the effect is tied to
  79189. * @param name The name of the effect
  79190. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  79191. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  79192. */
  79193. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  79194. this._name = name;
  79195. this._singleInstance = singleInstance || true;
  79196. this._getPostProcesses = getPostProcesses;
  79197. this._cameras = {};
  79198. this._indicesForCamera = {};
  79199. this._postProcesses = {};
  79200. }
  79201. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  79202. /**
  79203. * Checks if all the post processes in the effect are supported.
  79204. */
  79205. get: function () {
  79206. for (var index in this._postProcesses) {
  79207. if (this._postProcesses.hasOwnProperty(index)) {
  79208. var pps = this._postProcesses[index];
  79209. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  79210. if (!pps[ppIndex].isSupported) {
  79211. return false;
  79212. }
  79213. }
  79214. }
  79215. }
  79216. return true;
  79217. },
  79218. enumerable: true,
  79219. configurable: true
  79220. });
  79221. /**
  79222. * Updates the current state of the effect
  79223. * @hidden
  79224. */
  79225. PostProcessRenderEffect.prototype._update = function () {
  79226. };
  79227. /**
  79228. * Attaches the effect on cameras
  79229. * @param cameras The camera to attach to.
  79230. * @hidden
  79231. */
  79232. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  79233. var _this = this;
  79234. var cameraKey;
  79235. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79236. if (!cams) {
  79237. return;
  79238. }
  79239. for (var i = 0; i < cams.length; i++) {
  79240. var camera = cams[i];
  79241. var cameraName = camera.name;
  79242. if (this._singleInstance) {
  79243. cameraKey = 0;
  79244. }
  79245. else {
  79246. cameraKey = cameraName;
  79247. }
  79248. if (!this._postProcesses[cameraKey]) {
  79249. var postProcess = this._getPostProcesses();
  79250. if (postProcess) {
  79251. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  79252. }
  79253. }
  79254. if (!this._indicesForCamera[cameraName]) {
  79255. this._indicesForCamera[cameraName] = [];
  79256. }
  79257. this._postProcesses[cameraKey].forEach(function (postProcess) {
  79258. var index = camera.attachPostProcess(postProcess);
  79259. _this._indicesForCamera[cameraName].push(index);
  79260. });
  79261. if (!this._cameras[cameraName]) {
  79262. this._cameras[cameraName] = camera;
  79263. }
  79264. }
  79265. };
  79266. /**
  79267. * Detatches the effect on cameras
  79268. * @param cameras The camera to detatch from.
  79269. * @hidden
  79270. */
  79271. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  79272. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79273. if (!cams) {
  79274. return;
  79275. }
  79276. for (var i = 0; i < cams.length; i++) {
  79277. var camera = cams[i];
  79278. var cameraName = camera.name;
  79279. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79280. camera.detachPostProcess(postProcess);
  79281. });
  79282. if (this._cameras[cameraName]) {
  79283. //this._indicesForCamera.splice(index, 1);
  79284. this._cameras[cameraName] = null;
  79285. }
  79286. }
  79287. };
  79288. /**
  79289. * Enables the effect on given cameras
  79290. * @param cameras The camera to enable.
  79291. * @hidden
  79292. */
  79293. PostProcessRenderEffect.prototype._enable = function (cameras) {
  79294. var _this = this;
  79295. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79296. if (!cams) {
  79297. return;
  79298. }
  79299. for (var i = 0; i < cams.length; i++) {
  79300. var camera = cams[i];
  79301. var cameraName = camera.name;
  79302. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  79303. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  79304. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79305. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  79306. });
  79307. }
  79308. }
  79309. }
  79310. };
  79311. /**
  79312. * Disables the effect on the given cameras
  79313. * @param cameras The camera to disable.
  79314. * @hidden
  79315. */
  79316. PostProcessRenderEffect.prototype._disable = function (cameras) {
  79317. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79318. if (!cams) {
  79319. return;
  79320. }
  79321. for (var i = 0; i < cams.length; i++) {
  79322. var camera = cams[i];
  79323. var cameraName = camera.name;
  79324. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79325. camera.detachPostProcess(postProcess);
  79326. });
  79327. }
  79328. };
  79329. /**
  79330. * Gets a list of the post processes contained in the effect.
  79331. * @param camera The camera to get the post processes on.
  79332. * @returns The list of the post processes in the effect.
  79333. */
  79334. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  79335. if (this._singleInstance) {
  79336. return this._postProcesses[0];
  79337. }
  79338. else {
  79339. if (!camera) {
  79340. return null;
  79341. }
  79342. return this._postProcesses[camera.name];
  79343. }
  79344. };
  79345. return PostProcessRenderEffect;
  79346. }());
  79347. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  79348. })(BABYLON || (BABYLON = {}));
  79349. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  79350. var BABYLON;
  79351. (function (BABYLON) {
  79352. var PostProcessRenderPipeline = /** @class */ (function () {
  79353. function PostProcessRenderPipeline(engine, name) {
  79354. this.engine = engine;
  79355. this._name = name;
  79356. this._renderEffects = {};
  79357. this._renderEffectsForIsolatedPass = new Array();
  79358. this._cameras = [];
  79359. }
  79360. PostProcessRenderPipeline.prototype.getClassName = function () {
  79361. return "PostProcessRenderPipeline";
  79362. };
  79363. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  79364. get: function () {
  79365. for (var renderEffectName in this._renderEffects) {
  79366. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79367. if (!this._renderEffects[renderEffectName].isSupported) {
  79368. return false;
  79369. }
  79370. }
  79371. }
  79372. return true;
  79373. },
  79374. enumerable: true,
  79375. configurable: true
  79376. });
  79377. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  79378. this._renderEffects[renderEffect._name] = renderEffect;
  79379. };
  79380. // private
  79381. /** @hidden */
  79382. PostProcessRenderPipeline.prototype._rebuild = function () {
  79383. };
  79384. /** @hidden */
  79385. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  79386. var renderEffects = this._renderEffects[renderEffectName];
  79387. if (!renderEffects) {
  79388. return;
  79389. }
  79390. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  79391. };
  79392. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  79393. var renderEffects = this._renderEffects[renderEffectName];
  79394. if (!renderEffects) {
  79395. return;
  79396. }
  79397. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  79398. };
  79399. /** @hidden */
  79400. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  79401. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79402. if (!cams) {
  79403. return;
  79404. }
  79405. var indicesToDelete = [];
  79406. var i;
  79407. for (i = 0; i < cams.length; i++) {
  79408. var camera = cams[i];
  79409. var cameraName = camera.name;
  79410. if (this._cameras.indexOf(camera) === -1) {
  79411. this._cameras[cameraName] = camera;
  79412. }
  79413. else if (unique) {
  79414. indicesToDelete.push(i);
  79415. }
  79416. }
  79417. for (i = 0; i < indicesToDelete.length; i++) {
  79418. cameras.splice(indicesToDelete[i], 1);
  79419. }
  79420. for (var renderEffectName in this._renderEffects) {
  79421. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79422. this._renderEffects[renderEffectName]._attachCameras(cams);
  79423. }
  79424. }
  79425. };
  79426. /** @hidden */
  79427. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  79428. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79429. if (!cams) {
  79430. return;
  79431. }
  79432. for (var renderEffectName in this._renderEffects) {
  79433. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79434. this._renderEffects[renderEffectName]._detachCameras(cams);
  79435. }
  79436. }
  79437. for (var i = 0; i < cams.length; i++) {
  79438. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  79439. }
  79440. };
  79441. /** @hidden */
  79442. PostProcessRenderPipeline.prototype._update = function () {
  79443. for (var renderEffectName in this._renderEffects) {
  79444. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79445. this._renderEffects[renderEffectName]._update();
  79446. }
  79447. }
  79448. for (var i = 0; i < this._cameras.length; i++) {
  79449. var cameraName = this._cameras[i].name;
  79450. if (this._renderEffectsForIsolatedPass[cameraName]) {
  79451. this._renderEffectsForIsolatedPass[cameraName]._update();
  79452. }
  79453. }
  79454. };
  79455. /** @hidden */
  79456. PostProcessRenderPipeline.prototype._reset = function () {
  79457. this._renderEffects = {};
  79458. this._renderEffectsForIsolatedPass = new Array();
  79459. };
  79460. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  79461. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  79462. var effectKeys = Object.keys(this._renderEffects);
  79463. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  79464. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  79465. if (postProcesses) {
  79466. postProcesses[0].samples = sampleCount;
  79467. return true;
  79468. }
  79469. }
  79470. return false;
  79471. };
  79472. PostProcessRenderPipeline.prototype.dispose = function () {
  79473. // Must be implemented by children
  79474. };
  79475. __decorate([
  79476. BABYLON.serialize()
  79477. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  79478. return PostProcessRenderPipeline;
  79479. }());
  79480. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  79481. })(BABYLON || (BABYLON = {}));
  79482. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  79483. var BABYLON;
  79484. (function (BABYLON) {
  79485. /**
  79486. * This represents a depth renderer in Babylon.
  79487. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  79488. */
  79489. var DepthRenderer = /** @class */ (function () {
  79490. /**
  79491. * Instantiates a depth renderer
  79492. * @param scene The scene the renderer belongs to
  79493. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  79494. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  79495. */
  79496. function DepthRenderer(scene, type, camera) {
  79497. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  79498. if (camera === void 0) { camera = null; }
  79499. var _this = this;
  79500. /**
  79501. * Specifiess that the depth renderer will only be used within
  79502. * the camera it is created for.
  79503. * This can help forcing its rendering during the camera processing.
  79504. */
  79505. this.useOnlyInActiveCamera = false;
  79506. this._scene = scene;
  79507. // Register the G Buffer component to the scene.
  79508. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  79509. if (!component) {
  79510. component = new BABYLON.DepthRendererSceneComponent(scene);
  79511. scene._addComponent(component);
  79512. }
  79513. this._camera = camera;
  79514. var engine = scene.getEngine();
  79515. // Render target
  79516. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  79517. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79518. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79519. this._depthMap.refreshRate = 1;
  79520. this._depthMap.renderParticles = false;
  79521. this._depthMap.renderList = null;
  79522. // Camera to get depth map from to support multiple concurrent cameras
  79523. this._depthMap.activeCamera = this._camera;
  79524. this._depthMap.ignoreCameraViewport = true;
  79525. this._depthMap.useCameraPostProcesses = false;
  79526. // set default depth value to 1.0 (far away)
  79527. this._depthMap.onClearObservable.add(function (engine) {
  79528. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  79529. });
  79530. // Custom render function
  79531. var renderSubMesh = function (subMesh) {
  79532. var mesh = subMesh.getRenderingMesh();
  79533. var scene = _this._scene;
  79534. var engine = scene.getEngine();
  79535. var material = subMesh.getMaterial();
  79536. if (!material) {
  79537. return;
  79538. }
  79539. // Culling and reverse (right handed system)
  79540. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79541. // Managing instances
  79542. var batch = mesh._getInstancesRenderList(subMesh._id);
  79543. if (batch.mustReturn) {
  79544. return;
  79545. }
  79546. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79547. var camera = _this._camera || scene.activeCamera;
  79548. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  79549. engine.enableEffect(_this._effect);
  79550. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79551. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79552. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  79553. // Alpha test
  79554. if (material && material.needAlphaTesting()) {
  79555. var alphaTexture = material.getAlphaTestTexture();
  79556. if (alphaTexture) {
  79557. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79558. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79559. }
  79560. }
  79561. // Bones
  79562. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79563. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79564. }
  79565. // Draw
  79566. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79567. }
  79568. };
  79569. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79570. var index;
  79571. if (depthOnlySubMeshes.length) {
  79572. engine.setColorWrite(false);
  79573. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79574. renderSubMesh(depthOnlySubMeshes.data[index]);
  79575. }
  79576. engine.setColorWrite(true);
  79577. }
  79578. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79579. renderSubMesh(opaqueSubMeshes.data[index]);
  79580. }
  79581. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79582. renderSubMesh(alphaTestSubMeshes.data[index]);
  79583. }
  79584. };
  79585. }
  79586. /**
  79587. * Creates the depth rendering effect and checks if the effect is ready.
  79588. * @param subMesh The submesh to be used to render the depth map of
  79589. * @param useInstances If multiple world instances should be used
  79590. * @returns if the depth renderer is ready to render the depth map
  79591. */
  79592. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  79593. var material = subMesh.getMaterial();
  79594. if (material.disableDepthWrite) {
  79595. return false;
  79596. }
  79597. var defines = [];
  79598. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79599. var mesh = subMesh.getMesh();
  79600. // Alpha test
  79601. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  79602. defines.push("#define ALPHATEST");
  79603. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79604. attribs.push(BABYLON.VertexBuffer.UVKind);
  79605. defines.push("#define UV1");
  79606. }
  79607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79608. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79609. defines.push("#define UV2");
  79610. }
  79611. }
  79612. // Bones
  79613. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79614. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79615. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79616. if (mesh.numBoneInfluencers > 4) {
  79617. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79618. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79619. }
  79620. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79621. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79622. }
  79623. else {
  79624. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79625. }
  79626. // Instances
  79627. if (useInstances) {
  79628. defines.push("#define INSTANCES");
  79629. attribs.push("world0");
  79630. attribs.push("world1");
  79631. attribs.push("world2");
  79632. attribs.push("world3");
  79633. }
  79634. // Get correct effect
  79635. var join = defines.join("\n");
  79636. if (this._cachedDefines !== join) {
  79637. this._cachedDefines = join;
  79638. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  79639. }
  79640. return this._effect.isReady();
  79641. };
  79642. /**
  79643. * Gets the texture which the depth map will be written to.
  79644. * @returns The depth map texture
  79645. */
  79646. DepthRenderer.prototype.getDepthMap = function () {
  79647. return this._depthMap;
  79648. };
  79649. /**
  79650. * Disposes of the depth renderer.
  79651. */
  79652. DepthRenderer.prototype.dispose = function () {
  79653. this._depthMap.dispose();
  79654. };
  79655. return DepthRenderer;
  79656. }());
  79657. BABYLON.DepthRenderer = DepthRenderer;
  79658. })(BABYLON || (BABYLON = {}));
  79659. //# sourceMappingURL=babylon.depthRenderer.js.map
  79660. var BABYLON;
  79661. (function (BABYLON) {
  79662. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  79663. camera = camera || this.activeCamera;
  79664. if (!camera) {
  79665. throw "No camera available to enable depth renderer";
  79666. }
  79667. if (!this._depthRenderer) {
  79668. this._depthRenderer = {};
  79669. }
  79670. if (!this._depthRenderer[camera.id]) {
  79671. var textureType = 0;
  79672. if (this.getEngine().getCaps().textureHalfFloatRender) {
  79673. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79674. }
  79675. else if (this.getEngine().getCaps().textureFloatRender) {
  79676. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79677. }
  79678. else {
  79679. throw "Depth renderer does not support int texture type";
  79680. }
  79681. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  79682. }
  79683. return this._depthRenderer[camera.id];
  79684. };
  79685. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  79686. camera = camera || this.activeCamera;
  79687. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  79688. return;
  79689. }
  79690. this._depthRenderer[camera.id].dispose();
  79691. delete this._depthRenderer[camera.id];
  79692. };
  79693. /**
  79694. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  79695. * in several rendering techniques.
  79696. */
  79697. var DepthRendererSceneComponent = /** @class */ (function () {
  79698. /**
  79699. * Creates a new instance of the component for the given scene
  79700. * @param scene Defines the scene to register the component in
  79701. */
  79702. function DepthRendererSceneComponent(scene) {
  79703. /**
  79704. * The component name helpfull to identify the component in the list of scene components.
  79705. */
  79706. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  79707. this.scene = scene;
  79708. }
  79709. /**
  79710. * Registers the component in a given scene
  79711. */
  79712. DepthRendererSceneComponent.prototype.register = function () {
  79713. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  79714. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  79715. };
  79716. /**
  79717. * Rebuilds the elements related to this component in case of
  79718. * context lost for instance.
  79719. */
  79720. DepthRendererSceneComponent.prototype.rebuild = function () {
  79721. // Nothing to do for this component
  79722. };
  79723. /**
  79724. * Disposes the component and the associated ressources
  79725. */
  79726. DepthRendererSceneComponent.prototype.dispose = function () {
  79727. for (var key in this.scene._depthRenderer) {
  79728. this.scene._depthRenderer[key].dispose();
  79729. }
  79730. };
  79731. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  79732. if (this.scene._depthRenderer) {
  79733. for (var key in this.scene._depthRenderer) {
  79734. var depthRenderer = this.scene._depthRenderer[key];
  79735. if (!depthRenderer.useOnlyInActiveCamera) {
  79736. renderTargets.push(depthRenderer.getDepthMap());
  79737. }
  79738. }
  79739. }
  79740. };
  79741. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  79742. if (this.scene._depthRenderer) {
  79743. for (var key in this.scene._depthRenderer) {
  79744. var depthRenderer = this.scene._depthRenderer[key];
  79745. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  79746. renderTargets.push(depthRenderer.getDepthMap());
  79747. }
  79748. }
  79749. }
  79750. };
  79751. return DepthRendererSceneComponent;
  79752. }());
  79753. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  79754. })(BABYLON || (BABYLON = {}));
  79755. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  79756. var BABYLON;
  79757. (function (BABYLON) {
  79758. /**
  79759. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  79760. */
  79761. var GeometryBufferRenderer = /** @class */ (function () {
  79762. /**
  79763. * Creates a new G Buffer for the scene
  79764. * @param scene The scene the buffer belongs to
  79765. * @param ratio How big is the buffer related to the main canvas.
  79766. */
  79767. function GeometryBufferRenderer(scene, ratio) {
  79768. if (ratio === void 0) { ratio = 1; }
  79769. this._enablePosition = false;
  79770. this._scene = scene;
  79771. this._ratio = ratio;
  79772. // Register the G Buffer component to the scene.
  79773. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  79774. if (!component) {
  79775. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  79776. scene._addComponent(component);
  79777. }
  79778. // Render target
  79779. this._createRenderTargets();
  79780. }
  79781. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  79782. /**
  79783. * Set the render list (meshes to be rendered) used in the G buffer.
  79784. */
  79785. set: function (meshes) {
  79786. this._multiRenderTarget.renderList = meshes;
  79787. },
  79788. enumerable: true,
  79789. configurable: true
  79790. });
  79791. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  79792. /**
  79793. * Gets wether or not G buffer are supported by the running hardware.
  79794. * This requires draw buffer supports
  79795. */
  79796. get: function () {
  79797. return this._multiRenderTarget.isSupported;
  79798. },
  79799. enumerable: true,
  79800. configurable: true
  79801. });
  79802. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  79803. /**
  79804. * Gets wether or not position are enabled for the G buffer.
  79805. */
  79806. get: function () {
  79807. return this._enablePosition;
  79808. },
  79809. /**
  79810. * Sets wether or not position are enabled for the G buffer.
  79811. */
  79812. set: function (enable) {
  79813. this._enablePosition = enable;
  79814. this.dispose();
  79815. this._createRenderTargets();
  79816. },
  79817. enumerable: true,
  79818. configurable: true
  79819. });
  79820. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  79821. /**
  79822. * Gets the scene associated with the buffer.
  79823. */
  79824. get: function () {
  79825. return this._scene;
  79826. },
  79827. enumerable: true,
  79828. configurable: true
  79829. });
  79830. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  79831. /**
  79832. * Gets the ratio used by the buffer during its creation.
  79833. * How big is the buffer related to the main canvas.
  79834. */
  79835. get: function () {
  79836. return this._ratio;
  79837. },
  79838. enumerable: true,
  79839. configurable: true
  79840. });
  79841. /**
  79842. * Checks wether everything is ready to render a submesh to the G buffer.
  79843. * @param subMesh the submesh to check readiness for
  79844. * @param useInstances is the mesh drawn using instance or not
  79845. * @returns true if ready otherwise false
  79846. */
  79847. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  79848. var material = subMesh.getMaterial();
  79849. if (material && material.disableDepthWrite) {
  79850. return false;
  79851. }
  79852. var defines = [];
  79853. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79854. var mesh = subMesh.getMesh();
  79855. // Alpha test
  79856. if (material && material.needAlphaTesting()) {
  79857. defines.push("#define ALPHATEST");
  79858. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79859. attribs.push(BABYLON.VertexBuffer.UVKind);
  79860. defines.push("#define UV1");
  79861. }
  79862. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79863. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79864. defines.push("#define UV2");
  79865. }
  79866. }
  79867. // Buffers
  79868. if (this._enablePosition) {
  79869. defines.push("#define POSITION");
  79870. }
  79871. // Bones
  79872. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79873. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79874. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79875. if (mesh.numBoneInfluencers > 4) {
  79876. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79877. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79878. }
  79879. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79880. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79881. }
  79882. else {
  79883. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79884. }
  79885. // Instances
  79886. if (useInstances) {
  79887. defines.push("#define INSTANCES");
  79888. attribs.push("world0");
  79889. attribs.push("world1");
  79890. attribs.push("world2");
  79891. attribs.push("world3");
  79892. }
  79893. // Get correct effect
  79894. var join = defines.join("\n");
  79895. if (this._cachedDefines !== join) {
  79896. this._cachedDefines = join;
  79897. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  79898. }
  79899. return this._effect.isReady();
  79900. };
  79901. /**
  79902. * Gets the current underlying G Buffer.
  79903. * @returns the buffer
  79904. */
  79905. GeometryBufferRenderer.prototype.getGBuffer = function () {
  79906. return this._multiRenderTarget;
  79907. };
  79908. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  79909. /**
  79910. * Gets the number of samples used to render the buffer (anti aliasing).
  79911. */
  79912. get: function () {
  79913. return this._multiRenderTarget.samples;
  79914. },
  79915. /**
  79916. * Sets the number of samples used to render the buffer (anti aliasing).
  79917. */
  79918. set: function (value) {
  79919. this._multiRenderTarget.samples = value;
  79920. },
  79921. enumerable: true,
  79922. configurable: true
  79923. });
  79924. /**
  79925. * Disposes the renderer and frees up associated resources.
  79926. */
  79927. GeometryBufferRenderer.prototype.dispose = function () {
  79928. this.getGBuffer().dispose();
  79929. };
  79930. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  79931. var _this = this;
  79932. var engine = this._scene.getEngine();
  79933. var count = this._enablePosition ? 3 : 2;
  79934. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  79935. if (!this.isSupported) {
  79936. return;
  79937. }
  79938. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79939. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79940. this._multiRenderTarget.refreshRate = 1;
  79941. this._multiRenderTarget.renderParticles = false;
  79942. this._multiRenderTarget.renderList = null;
  79943. // set default depth value to 1.0 (far away)
  79944. this._multiRenderTarget.onClearObservable.add(function (engine) {
  79945. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  79946. });
  79947. // Custom render function
  79948. var renderSubMesh = function (subMesh) {
  79949. var mesh = subMesh.getRenderingMesh();
  79950. var scene = _this._scene;
  79951. var engine = scene.getEngine();
  79952. var material = subMesh.getMaterial();
  79953. if (!material) {
  79954. return;
  79955. }
  79956. // Culling
  79957. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79958. // Managing instances
  79959. var batch = mesh._getInstancesRenderList(subMesh._id);
  79960. if (batch.mustReturn) {
  79961. return;
  79962. }
  79963. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79964. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  79965. engine.enableEffect(_this._effect);
  79966. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79967. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79968. _this._effect.setMatrix("view", scene.getViewMatrix());
  79969. // Alpha test
  79970. if (material && material.needAlphaTesting()) {
  79971. var alphaTexture = material.getAlphaTestTexture();
  79972. if (alphaTexture) {
  79973. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79974. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79975. }
  79976. }
  79977. // Bones
  79978. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79979. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79980. }
  79981. // Draw
  79982. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79983. }
  79984. };
  79985. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79986. var index;
  79987. if (depthOnlySubMeshes.length) {
  79988. engine.setColorWrite(false);
  79989. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79990. renderSubMesh(depthOnlySubMeshes.data[index]);
  79991. }
  79992. engine.setColorWrite(true);
  79993. }
  79994. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79995. renderSubMesh(opaqueSubMeshes.data[index]);
  79996. }
  79997. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79998. renderSubMesh(alphaTestSubMeshes.data[index]);
  79999. }
  80000. };
  80001. };
  80002. return GeometryBufferRenderer;
  80003. }());
  80004. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  80005. })(BABYLON || (BABYLON = {}));
  80006. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  80007. var BABYLON;
  80008. (function (BABYLON) {
  80009. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  80010. get: function () {
  80011. this._geometryBufferRenderer;
  80012. },
  80013. set: function (value) {
  80014. if (value && value.isSupported) {
  80015. this._geometryBufferRenderer = value;
  80016. }
  80017. ;
  80018. },
  80019. enumerable: true,
  80020. configurable: true
  80021. });
  80022. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  80023. if (ratio === void 0) { ratio = 1; }
  80024. if (this._geometryBufferRenderer) {
  80025. return this._geometryBufferRenderer;
  80026. }
  80027. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  80028. if (!this._geometryBufferRenderer.isSupported) {
  80029. this._geometryBufferRenderer = null;
  80030. }
  80031. return this._geometryBufferRenderer;
  80032. };
  80033. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  80034. if (!this._geometryBufferRenderer) {
  80035. return;
  80036. }
  80037. this._geometryBufferRenderer.dispose();
  80038. this._geometryBufferRenderer = null;
  80039. };
  80040. /**
  80041. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  80042. * in several rendering techniques.
  80043. */
  80044. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  80045. /**
  80046. * Creates a new instance of the component for the given scene
  80047. * @param scene Defines the scene to register the component in
  80048. */
  80049. function GeometryBufferRendererSceneComponent(scene) {
  80050. /**
  80051. * The component name helpful to identify the component in the list of scene components.
  80052. */
  80053. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  80054. this.scene = scene;
  80055. }
  80056. /**
  80057. * Registers the component in a given scene
  80058. */
  80059. GeometryBufferRendererSceneComponent.prototype.register = function () {
  80060. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  80061. };
  80062. /**
  80063. * Rebuilds the elements related to this component in case of
  80064. * context lost for instance.
  80065. */
  80066. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  80067. // Nothing to do for this component
  80068. };
  80069. /**
  80070. * Disposes the component and the associated ressources
  80071. */
  80072. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  80073. // Nothing to do for this component
  80074. };
  80075. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80076. if (this.scene._geometryBufferRenderer) {
  80077. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  80078. }
  80079. };
  80080. return GeometryBufferRendererSceneComponent;
  80081. }());
  80082. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  80083. })(BABYLON || (BABYLON = {}));
  80084. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  80085. var BABYLON;
  80086. (function (BABYLON) {
  80087. var SSAORenderingPipeline = /** @class */ (function (_super) {
  80088. __extends(SSAORenderingPipeline, _super);
  80089. /**
  80090. * @constructor
  80091. * @param {string} name - The rendering pipeline name
  80092. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80093. * @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 }
  80094. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80095. */
  80096. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  80097. var _this = _super.call(this, scene.getEngine(), name) || this;
  80098. // Members
  80099. /**
  80100. * The PassPostProcess id in the pipeline that contains the original scene color
  80101. */
  80102. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80103. /**
  80104. * The SSAO PostProcess id in the pipeline
  80105. */
  80106. _this.SSAORenderEffect = "SSAORenderEffect";
  80107. /**
  80108. * The horizontal blur PostProcess id in the pipeline
  80109. */
  80110. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80111. /**
  80112. * The vertical blur PostProcess id in the pipeline
  80113. */
  80114. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80115. /**
  80116. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80117. */
  80118. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80119. /**
  80120. * The output strength of the SSAO post-process. Default value is 1.0.
  80121. */
  80122. _this.totalStrength = 1.0;
  80123. /**
  80124. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  80125. */
  80126. _this.radius = 0.0001;
  80127. /**
  80128. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  80129. * Must not be equal to fallOff and superior to fallOff.
  80130. * Default value is 0.975
  80131. */
  80132. _this.area = 0.0075;
  80133. /**
  80134. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  80135. * Must not be equal to area and inferior to area.
  80136. * Default value is 0.0
  80137. */
  80138. _this.fallOff = 0.000001;
  80139. /**
  80140. * The base color of the SSAO post-process
  80141. * The final result is "base + ssao" between [0, 1]
  80142. */
  80143. _this.base = 0.5;
  80144. _this._firstUpdate = true;
  80145. _this._scene = scene;
  80146. // Set up assets
  80147. _this._createRandomTexture();
  80148. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  80149. var ssaoRatio = ratio.ssaoRatio || ratio;
  80150. var combineRatio = ratio.combineRatio || ratio;
  80151. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  80152. _this._createSSAOPostProcess(ssaoRatio);
  80153. _this._createBlurPostProcess(ssaoRatio);
  80154. _this._createSSAOCombinePostProcess(combineRatio);
  80155. // Set up pipeline
  80156. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  80157. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  80158. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  80159. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  80160. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  80161. // Finish
  80162. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80163. if (cameras)
  80164. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80165. return _this;
  80166. }
  80167. // Public Methods
  80168. /**
  80169. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  80170. */
  80171. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  80172. if (disableDepthRender === void 0) { disableDepthRender = false; }
  80173. for (var i = 0; i < this._scene.cameras.length; i++) {
  80174. var camera = this._scene.cameras[i];
  80175. this._originalColorPostProcess.dispose(camera);
  80176. this._ssaoPostProcess.dispose(camera);
  80177. this._blurHPostProcess.dispose(camera);
  80178. this._blurVPostProcess.dispose(camera);
  80179. this._ssaoCombinePostProcess.dispose(camera);
  80180. }
  80181. this._randomTexture.dispose();
  80182. if (disableDepthRender)
  80183. this._scene.disableDepthRenderer();
  80184. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80185. _super.prototype.dispose.call(this);
  80186. };
  80187. // Private Methods
  80188. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  80189. var _this = this;
  80190. var size = 16;
  80191. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80192. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80193. this._blurHPostProcess.onActivateObservable.add(function () {
  80194. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  80195. _this._blurHPostProcess.kernel = size * dw;
  80196. });
  80197. this._blurVPostProcess.onActivateObservable.add(function () {
  80198. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  80199. _this._blurVPostProcess.kernel = size * dw;
  80200. });
  80201. };
  80202. /** @hidden */
  80203. SSAORenderingPipeline.prototype._rebuild = function () {
  80204. this._firstUpdate = true;
  80205. _super.prototype._rebuild.call(this);
  80206. };
  80207. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  80208. var _this = this;
  80209. var numSamples = 16;
  80210. var sampleSphere = [
  80211. 0.5381, 0.1856, -0.4319,
  80212. 0.1379, 0.2486, 0.4430,
  80213. 0.3371, 0.5679, -0.0057,
  80214. -0.6999, -0.0451, -0.0019,
  80215. 0.0689, -0.1598, -0.8547,
  80216. 0.0560, 0.0069, -0.1843,
  80217. -0.0146, 0.1402, 0.0762,
  80218. 0.0100, -0.1924, -0.0344,
  80219. -0.3577, -0.5301, -0.4358,
  80220. -0.3169, 0.1063, 0.0158,
  80221. 0.0103, -0.5869, 0.0046,
  80222. -0.0897, -0.4940, 0.3287,
  80223. 0.7119, -0.0154, -0.0918,
  80224. -0.0533, 0.0596, -0.5411,
  80225. 0.0352, -0.0631, 0.5460,
  80226. -0.4776, 0.2847, -0.0271
  80227. ];
  80228. var samplesFactor = 1.0 / numSamples;
  80229. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  80230. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  80231. "area", "fallOff", "base", "range", "viewport"
  80232. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  80233. this._ssaoPostProcess.onApply = function (effect) {
  80234. if (_this._firstUpdate) {
  80235. effect.setArray3("sampleSphere", sampleSphere);
  80236. effect.setFloat("samplesFactor", samplesFactor);
  80237. effect.setFloat("randTextureTiles", 4.0);
  80238. }
  80239. effect.setFloat("totalStrength", _this.totalStrength);
  80240. effect.setFloat("radius", _this.radius);
  80241. effect.setFloat("area", _this.area);
  80242. effect.setFloat("fallOff", _this.fallOff);
  80243. effect.setFloat("base", _this.base);
  80244. effect.setTexture("textureSampler", _this._depthTexture);
  80245. effect.setTexture("randomSampler", _this._randomTexture);
  80246. };
  80247. };
  80248. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  80249. var _this = this;
  80250. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80251. this._ssaoCombinePostProcess.onApply = function (effect) {
  80252. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  80253. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  80254. };
  80255. };
  80256. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  80257. var size = 512;
  80258. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80259. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80260. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80261. var context = this._randomTexture.getContext();
  80262. var rand = function (min, max) {
  80263. return Math.random() * (max - min) + min;
  80264. };
  80265. var randVector = BABYLON.Vector3.Zero();
  80266. for (var x = 0; x < size; x++) {
  80267. for (var y = 0; y < size; y++) {
  80268. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  80269. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  80270. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  80271. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  80272. context.fillRect(x, y, 1, 1);
  80273. }
  80274. }
  80275. this._randomTexture.update(false);
  80276. };
  80277. __decorate([
  80278. BABYLON.serialize()
  80279. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  80280. __decorate([
  80281. BABYLON.serialize()
  80282. ], SSAORenderingPipeline.prototype, "radius", void 0);
  80283. __decorate([
  80284. BABYLON.serialize()
  80285. ], SSAORenderingPipeline.prototype, "area", void 0);
  80286. __decorate([
  80287. BABYLON.serialize()
  80288. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  80289. __decorate([
  80290. BABYLON.serialize()
  80291. ], SSAORenderingPipeline.prototype, "base", void 0);
  80292. return SSAORenderingPipeline;
  80293. }(BABYLON.PostProcessRenderPipeline));
  80294. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  80295. })(BABYLON || (BABYLON = {}));
  80296. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  80297. var BABYLON;
  80298. (function (BABYLON) {
  80299. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  80300. __extends(SSAO2RenderingPipeline, _super);
  80301. /**
  80302. * @constructor
  80303. * @param {string} name - The rendering pipeline name
  80304. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80305. * @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 }
  80306. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80307. */
  80308. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  80309. var _this = _super.call(this, scene.getEngine(), name) || this;
  80310. // Members
  80311. /**
  80312. * The PassPostProcess id in the pipeline that contains the original scene color
  80313. */
  80314. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80315. /**
  80316. * The SSAO PostProcess id in the pipeline
  80317. */
  80318. _this.SSAORenderEffect = "SSAORenderEffect";
  80319. /**
  80320. * The horizontal blur PostProcess id in the pipeline
  80321. */
  80322. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80323. /**
  80324. * The vertical blur PostProcess id in the pipeline
  80325. */
  80326. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80327. /**
  80328. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80329. */
  80330. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80331. /**
  80332. * The output strength of the SSAO post-process. Default value is 1.0.
  80333. */
  80334. _this.totalStrength = 1.0;
  80335. /**
  80336. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  80337. */
  80338. _this.maxZ = 100.0;
  80339. /**
  80340. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  80341. */
  80342. _this.minZAspect = 0.2;
  80343. _this._samples = 8;
  80344. _this._textureSamples = 1;
  80345. /**
  80346. * Are we using bilateral blur ?
  80347. */
  80348. _this._expensiveBlur = true;
  80349. /**
  80350. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  80351. */
  80352. _this.radius = 2.0;
  80353. /**
  80354. * The base color of the SSAO post-process
  80355. * The final result is "base + ssao" between [0, 1]
  80356. */
  80357. _this.base = 0;
  80358. _this._firstUpdate = true;
  80359. _this._bits = new Uint32Array(1);
  80360. _this._scene = scene;
  80361. _this._ratio = ratio;
  80362. if (!_this.isSupported) {
  80363. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  80364. return _this;
  80365. }
  80366. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  80367. var blurRatio = _this._ratio.blurRatio || ratio;
  80368. // Set up assets
  80369. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  80370. _this._createRandomTexture();
  80371. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  80372. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  80373. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  80374. _this._originalColorPostProcess.samples = _this.textureSamples;
  80375. _this._createSSAOPostProcess(1.0);
  80376. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  80377. _this._createSSAOCombinePostProcess(blurRatio);
  80378. // Set up pipeline
  80379. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  80380. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  80381. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  80382. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  80383. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  80384. // Finish
  80385. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80386. if (cameras)
  80387. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80388. return _this;
  80389. }
  80390. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  80391. get: function () {
  80392. return this._samples;
  80393. },
  80394. /**
  80395. * Number of samples used for the SSAO calculations. Default value is 8
  80396. */
  80397. set: function (n) {
  80398. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  80399. this._samples = n;
  80400. this._sampleSphere = this._generateHemisphere();
  80401. this._firstUpdate = true;
  80402. },
  80403. enumerable: true,
  80404. configurable: true
  80405. });
  80406. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  80407. get: function () {
  80408. return this._textureSamples;
  80409. },
  80410. /**
  80411. * Number of samples to use for antialiasing
  80412. */
  80413. set: function (n) {
  80414. this._textureSamples = n;
  80415. this._originalColorPostProcess.samples = n;
  80416. this._blurHPostProcess.samples = n;
  80417. this._blurVPostProcess.samples = n;
  80418. this._ssaoPostProcess.samples = n;
  80419. this._ssaoCombinePostProcess.samples = n;
  80420. },
  80421. enumerable: true,
  80422. configurable: true
  80423. });
  80424. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  80425. get: function () {
  80426. return this._expensiveBlur;
  80427. },
  80428. set: function (b) {
  80429. 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"]);
  80430. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  80431. this._expensiveBlur = b;
  80432. this._firstUpdate = true;
  80433. },
  80434. enumerable: true,
  80435. configurable: true
  80436. });
  80437. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  80438. /**
  80439. * Support test.
  80440. */
  80441. get: function () {
  80442. var engine = BABYLON.Engine.LastCreatedEngine;
  80443. if (!engine) {
  80444. return false;
  80445. }
  80446. return engine.getCaps().drawBuffersExtension;
  80447. },
  80448. enumerable: true,
  80449. configurable: true
  80450. });
  80451. // Public Methods
  80452. /**
  80453. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  80454. */
  80455. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  80456. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  80457. for (var i = 0; i < this._scene.cameras.length; i++) {
  80458. var camera = this._scene.cameras[i];
  80459. this._originalColorPostProcess.dispose(camera);
  80460. this._ssaoPostProcess.dispose(camera);
  80461. this._blurHPostProcess.dispose(camera);
  80462. this._blurVPostProcess.dispose(camera);
  80463. this._ssaoCombinePostProcess.dispose(camera);
  80464. }
  80465. this._randomTexture.dispose();
  80466. if (disableGeometryBufferRenderer)
  80467. this._scene.disableGeometryBufferRenderer();
  80468. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80469. _super.prototype.dispose.call(this);
  80470. };
  80471. // Private Methods
  80472. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  80473. var _this = this;
  80474. this._samplerOffsets = [];
  80475. var expensive = this.expensiveBlur;
  80476. for (var i = -8; i < 8; i++) {
  80477. this._samplerOffsets.push(i * 2 + 0.5);
  80478. }
  80479. 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");
  80480. this._blurHPostProcess.onApply = function (effect) {
  80481. if (!_this._scene.activeCamera) {
  80482. return;
  80483. }
  80484. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  80485. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80486. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80487. effect.setFloat("radius", _this.radius);
  80488. effect.setTexture("depthSampler", _this._depthTexture);
  80489. if (_this._firstUpdate) {
  80490. effect.setArray("samplerOffsets", _this._samplerOffsets);
  80491. }
  80492. };
  80493. 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");
  80494. this._blurVPostProcess.onApply = function (effect) {
  80495. if (!_this._scene.activeCamera) {
  80496. return;
  80497. }
  80498. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  80499. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80500. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80501. effect.setFloat("radius", _this.radius);
  80502. effect.setTexture("depthSampler", _this._depthTexture);
  80503. if (_this._firstUpdate) {
  80504. effect.setArray("samplerOffsets", _this._samplerOffsets);
  80505. _this._firstUpdate = false;
  80506. }
  80507. };
  80508. this._blurHPostProcess.samples = this.textureSamples;
  80509. this._blurVPostProcess.samples = this.textureSamples;
  80510. };
  80511. /** @hidden */
  80512. SSAO2RenderingPipeline.prototype._rebuild = function () {
  80513. this._firstUpdate = true;
  80514. _super.prototype._rebuild.call(this);
  80515. };
  80516. //Van der Corput radical inverse
  80517. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  80518. this._bits[0] = i;
  80519. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  80520. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  80521. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  80522. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  80523. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  80524. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  80525. };
  80526. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  80527. return [i / n, this._radicalInverse_VdC(i)];
  80528. };
  80529. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  80530. var phi = v * 2.0 * Math.PI;
  80531. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  80532. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  80533. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  80534. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  80535. };
  80536. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  80537. var numSamples = this.samples;
  80538. var result = [];
  80539. var vector;
  80540. var i = 0;
  80541. while (i < numSamples) {
  80542. if (numSamples < 16) {
  80543. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  80544. }
  80545. else {
  80546. var rand = this._hammersley(i, numSamples);
  80547. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  80548. }
  80549. result.push(vector.x, vector.y, vector.z);
  80550. i++;
  80551. }
  80552. return result;
  80553. };
  80554. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  80555. var _this = this;
  80556. var numSamples = this.samples;
  80557. this._sampleSphere = this._generateHemisphere();
  80558. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  80559. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  80560. "base", "range", "projection", "near", "far", "texelSize",
  80561. "xViewport", "yViewport", "maxZ", "minZAspect"
  80562. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  80563. this._ssaoPostProcess.onApply = function (effect) {
  80564. if (_this._firstUpdate) {
  80565. effect.setArray3("sampleSphere", _this._sampleSphere);
  80566. effect.setFloat("randTextureTiles", 32.0);
  80567. }
  80568. if (!_this._scene.activeCamera) {
  80569. return;
  80570. }
  80571. effect.setFloat("samplesFactor", 1 / _this.samples);
  80572. effect.setFloat("totalStrength", _this.totalStrength);
  80573. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  80574. effect.setFloat("radius", _this.radius);
  80575. effect.setFloat("maxZ", _this.maxZ);
  80576. effect.setFloat("minZAspect", _this.minZAspect);
  80577. effect.setFloat("base", _this.base);
  80578. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80579. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80580. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  80581. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  80582. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  80583. effect.setTexture("textureSampler", _this._depthTexture);
  80584. effect.setTexture("normalSampler", _this._normalTexture);
  80585. effect.setTexture("randomSampler", _this._randomTexture);
  80586. };
  80587. this._ssaoPostProcess.samples = this.textureSamples;
  80588. };
  80589. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  80590. var _this = this;
  80591. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80592. this._ssaoCombinePostProcess.onApply = function (effect) {
  80593. var viewport = _this._scene.activeCamera.viewport;
  80594. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  80595. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  80596. };
  80597. this._ssaoCombinePostProcess.samples = this.textureSamples;
  80598. };
  80599. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  80600. var size = 128;
  80601. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80602. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80603. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80604. var context = this._randomTexture.getContext();
  80605. var rand = function (min, max) {
  80606. return Math.random() * (max - min) + min;
  80607. };
  80608. var randVector = BABYLON.Vector3.Zero();
  80609. for (var x = 0; x < size; x++) {
  80610. for (var y = 0; y < size; y++) {
  80611. randVector.x = rand(0.0, 1.0);
  80612. randVector.y = rand(0.0, 1.0);
  80613. randVector.z = 0.0;
  80614. randVector.normalize();
  80615. randVector.scaleInPlace(255);
  80616. randVector.x = Math.floor(randVector.x);
  80617. randVector.y = Math.floor(randVector.y);
  80618. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  80619. context.fillRect(x, y, 1, 1);
  80620. }
  80621. }
  80622. this._randomTexture.update(false);
  80623. };
  80624. /**
  80625. * Serialize the rendering pipeline (Used when exporting)
  80626. * @returns the serialized object
  80627. */
  80628. SSAO2RenderingPipeline.prototype.serialize = function () {
  80629. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80630. serializationObject.customType = "SSAO2RenderingPipeline";
  80631. return serializationObject;
  80632. };
  80633. /**
  80634. * Parse the serialized pipeline
  80635. * @param source Source pipeline.
  80636. * @param scene The scene to load the pipeline to.
  80637. * @param rootUrl The URL of the serialized pipeline.
  80638. * @returns An instantiated pipeline from the serialized object.
  80639. */
  80640. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  80641. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  80642. };
  80643. __decorate([
  80644. BABYLON.serialize()
  80645. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  80646. __decorate([
  80647. BABYLON.serialize()
  80648. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  80649. __decorate([
  80650. BABYLON.serialize()
  80651. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  80652. __decorate([
  80653. BABYLON.serialize("samples")
  80654. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  80655. __decorate([
  80656. BABYLON.serialize("textureSamples")
  80657. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  80658. __decorate([
  80659. BABYLON.serialize()
  80660. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  80661. __decorate([
  80662. BABYLON.serialize("expensiveBlur")
  80663. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  80664. __decorate([
  80665. BABYLON.serialize()
  80666. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  80667. __decorate([
  80668. BABYLON.serialize()
  80669. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  80670. return SSAO2RenderingPipeline;
  80671. }(BABYLON.PostProcessRenderPipeline));
  80672. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  80673. })(BABYLON || (BABYLON = {}));
  80674. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  80675. // BABYLON.JS Chromatic Aberration GLSL Shader
  80676. // Author: Olivier Guyot
  80677. // Separates very slightly R, G and B colors on the edges of the screen
  80678. // Inspired by Francois Tarlier & Martins Upitis
  80679. var BABYLON;
  80680. (function (BABYLON) {
  80681. var LensRenderingPipeline = /** @class */ (function (_super) {
  80682. __extends(LensRenderingPipeline, _super);
  80683. /**
  80684. * @constructor
  80685. *
  80686. * Effect parameters are as follow:
  80687. * {
  80688. * chromatic_aberration: number; // from 0 to x (1 for realism)
  80689. * edge_blur: number; // from 0 to x (1 for realism)
  80690. * distortion: number; // from 0 to x (1 for realism)
  80691. * grain_amount: number; // from 0 to 1
  80692. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  80693. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  80694. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  80695. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  80696. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  80697. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  80698. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  80699. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  80700. * }
  80701. * Note: if an effect parameter is unset, effect is disabled
  80702. *
  80703. * @param {string} name - The rendering pipeline name
  80704. * @param {object} parameters - An object containing all parameters (see above)
  80705. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80706. * @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)
  80707. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80708. */
  80709. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  80710. if (ratio === void 0) { ratio = 1.0; }
  80711. var _this = _super.call(this, scene.getEngine(), name) || this;
  80712. // Lens effects can be of the following:
  80713. // - chromatic aberration (slight shift of RGB colors)
  80714. // - blur on the edge of the lens
  80715. // - lens distortion
  80716. // - depth-of-field blur & highlights enhancing
  80717. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  80718. // - grain effect (noise or custom texture)
  80719. // Two additional texture samplers are needed:
  80720. // - depth map (for depth-of-field)
  80721. // - grain texture
  80722. /**
  80723. * The chromatic aberration PostProcess id in the pipeline
  80724. */
  80725. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  80726. /**
  80727. * The highlights enhancing PostProcess id in the pipeline
  80728. */
  80729. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  80730. /**
  80731. * The depth-of-field PostProcess id in the pipeline
  80732. */
  80733. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  80734. _this._scene = scene;
  80735. // Fetch texture samplers
  80736. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  80737. if (parameters.grain_texture) {
  80738. _this._grainTexture = parameters.grain_texture;
  80739. }
  80740. else {
  80741. _this._createGrainTexture();
  80742. }
  80743. // save parameters
  80744. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  80745. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  80746. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  80747. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  80748. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  80749. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  80750. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  80751. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  80752. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  80753. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  80754. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  80755. // Create effects
  80756. _this._createChromaticAberrationPostProcess(ratio);
  80757. _this._createHighlightsPostProcess(ratio);
  80758. _this._createDepthOfFieldPostProcess(ratio / 4);
  80759. // Set up pipeline
  80760. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  80761. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  80762. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  80763. if (_this._highlightsGain === -1) {
  80764. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  80765. }
  80766. // Finish
  80767. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80768. if (cameras) {
  80769. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80770. }
  80771. return _this;
  80772. }
  80773. // public methods (self explanatory)
  80774. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  80775. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  80776. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  80777. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  80778. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  80779. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  80780. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  80781. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  80782. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  80783. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  80784. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  80785. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  80786. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  80787. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  80788. };
  80789. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  80790. this._highlightsPostProcess.updateEffect();
  80791. };
  80792. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  80793. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  80794. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  80795. this._highlightsGain = amount;
  80796. };
  80797. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  80798. if (this._highlightsGain === -1) {
  80799. this._highlightsGain = 1.0;
  80800. }
  80801. this._highlightsThreshold = amount;
  80802. };
  80803. LensRenderingPipeline.prototype.disableHighlights = function () {
  80804. this._highlightsGain = -1;
  80805. };
  80806. /**
  80807. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  80808. */
  80809. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  80810. if (disableDepthRender === void 0) { disableDepthRender = false; }
  80811. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80812. this._chromaticAberrationPostProcess = null;
  80813. this._highlightsPostProcess = null;
  80814. this._depthOfFieldPostProcess = null;
  80815. this._grainTexture.dispose();
  80816. if (disableDepthRender)
  80817. this._scene.disableDepthRenderer();
  80818. };
  80819. // colors shifting and distortion
  80820. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  80821. var _this = this;
  80822. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  80823. [], // samplers
  80824. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80825. this._chromaticAberrationPostProcess.onApply = function (effect) {
  80826. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  80827. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  80828. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  80829. effect.setFloat('radialIntensity', 1);
  80830. effect.setFloat2('direction', 17, 17);
  80831. effect.setFloat2('centerPosition', 0.5, 0.5);
  80832. };
  80833. };
  80834. // highlights enhancing
  80835. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  80836. var _this = this;
  80837. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  80838. [], // samplers
  80839. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  80840. this._highlightsPostProcess.onApply = function (effect) {
  80841. effect.setFloat('gain', _this._highlightsGain);
  80842. effect.setFloat('threshold', _this._highlightsThreshold);
  80843. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  80844. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  80845. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  80846. };
  80847. };
  80848. // colors shifting and distortion
  80849. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  80850. var _this = this;
  80851. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  80852. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  80853. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  80854. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80855. this._depthOfFieldPostProcess.onApply = function (effect) {
  80856. effect.setTexture("depthSampler", _this._depthTexture);
  80857. effect.setTexture("grainSampler", _this._grainTexture);
  80858. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  80859. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  80860. effect.setFloat('grain_amount', _this._grainAmount);
  80861. effect.setBool('blur_noise', _this._blurNoise);
  80862. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  80863. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  80864. effect.setFloat('distortion', _this._distortion);
  80865. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  80866. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  80867. effect.setFloat('aperture', _this._dofAperture);
  80868. effect.setFloat('darken', _this._dofDarken);
  80869. effect.setFloat('edge_blur', _this._edgeBlur);
  80870. effect.setBool('highlights', (_this._highlightsGain !== -1));
  80871. if (_this._scene.activeCamera) {
  80872. effect.setFloat('near', _this._scene.activeCamera.minZ);
  80873. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  80874. }
  80875. };
  80876. };
  80877. // creates a black and white random noise texture, 512x512
  80878. LensRenderingPipeline.prototype._createGrainTexture = function () {
  80879. var size = 512;
  80880. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80881. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80882. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80883. var context = this._grainTexture.getContext();
  80884. var rand = function (min, max) {
  80885. return Math.random() * (max - min) + min;
  80886. };
  80887. var value;
  80888. for (var x = 0; x < size; x++) {
  80889. for (var y = 0; y < size; y++) {
  80890. value = Math.floor(rand(0.42, 0.58) * 255);
  80891. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  80892. context.fillRect(x, y, 1, 1);
  80893. }
  80894. }
  80895. this._grainTexture.update(false);
  80896. };
  80897. return LensRenderingPipeline;
  80898. }(BABYLON.PostProcessRenderPipeline));
  80899. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  80900. })(BABYLON || (BABYLON = {}));
  80901. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  80902. var BABYLON;
  80903. (function (BABYLON) {
  80904. var StandardRenderingPipeline = /** @class */ (function (_super) {
  80905. __extends(StandardRenderingPipeline, _super);
  80906. /**
  80907. * @constructor
  80908. * @param {string} name - The rendering pipeline name
  80909. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80910. * @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)
  80911. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  80912. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80913. */
  80914. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  80915. if (originalPostProcess === void 0) { originalPostProcess = null; }
  80916. var _this = _super.call(this, scene.getEngine(), name) || this;
  80917. /**
  80918. * Post-process used to down scale an image x4
  80919. */
  80920. _this.downSampleX4PostProcess = null;
  80921. /**
  80922. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  80923. */
  80924. _this.brightPassPostProcess = null;
  80925. /**
  80926. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  80927. */
  80928. _this.blurHPostProcesses = [];
  80929. /**
  80930. * Post-process array storing all the vertical blur post-processes used by the pipeline
  80931. */
  80932. _this.blurVPostProcesses = [];
  80933. /**
  80934. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  80935. */
  80936. _this.textureAdderPostProcess = null;
  80937. /**
  80938. * Post-process used to create volumetric lighting effect
  80939. */
  80940. _this.volumetricLightPostProcess = null;
  80941. /**
  80942. * Post-process used to smooth the previous volumetric light post-process on the X axis
  80943. */
  80944. _this.volumetricLightSmoothXPostProcess = null;
  80945. /**
  80946. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  80947. */
  80948. _this.volumetricLightSmoothYPostProcess = null;
  80949. /**
  80950. * Post-process used to merge the volumetric light effect and the real scene color
  80951. */
  80952. _this.volumetricLightMergePostProces = null;
  80953. /**
  80954. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  80955. */
  80956. _this.volumetricLightFinalPostProcess = null;
  80957. /**
  80958. * Base post-process used to calculate the average luminance of the final image for HDR
  80959. */
  80960. _this.luminancePostProcess = null;
  80961. /**
  80962. * Post-processes used to create down sample post-processes in order to get
  80963. * the average luminance of the final image for HDR
  80964. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  80965. */
  80966. _this.luminanceDownSamplePostProcesses = [];
  80967. /**
  80968. * Post-process used to create a HDR effect (light adaptation)
  80969. */
  80970. _this.hdrPostProcess = null;
  80971. /**
  80972. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  80973. */
  80974. _this.textureAdderFinalPostProcess = null;
  80975. /**
  80976. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  80977. */
  80978. _this.lensFlareFinalPostProcess = null;
  80979. /**
  80980. * Post-process used to merge the final HDR post-process and the real scene color
  80981. */
  80982. _this.hdrFinalPostProcess = null;
  80983. /**
  80984. * Post-process used to create a lens flare effect
  80985. */
  80986. _this.lensFlarePostProcess = null;
  80987. /**
  80988. * Post-process that merges the result of the lens flare post-process and the real scene color
  80989. */
  80990. _this.lensFlareComposePostProcess = null;
  80991. /**
  80992. * Post-process used to create a motion blur effect
  80993. */
  80994. _this.motionBlurPostProcess = null;
  80995. /**
  80996. * Post-process used to create a depth of field effect
  80997. */
  80998. _this.depthOfFieldPostProcess = null;
  80999. /**
  81000. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  81001. */
  81002. _this.fxaaPostProcess = null;
  81003. // Values
  81004. /**
  81005. * Represents the brightness threshold in order to configure the illuminated surfaces
  81006. */
  81007. _this.brightThreshold = 1.0;
  81008. /**
  81009. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  81010. */
  81011. _this.blurWidth = 512.0;
  81012. /**
  81013. * Sets if the blur for highlighted surfaces must be only horizontal
  81014. */
  81015. _this.horizontalBlur = false;
  81016. /**
  81017. * Sets the overall exposure used by the pipeline
  81018. */
  81019. _this.exposure = 1.0;
  81020. /**
  81021. * Texture used typically to simulate "dirty" on camera lens
  81022. */
  81023. _this.lensTexture = null;
  81024. /**
  81025. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  81026. */
  81027. _this.volumetricLightCoefficient = 0.2;
  81028. /**
  81029. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  81030. */
  81031. _this.volumetricLightPower = 4.0;
  81032. /**
  81033. * Used the set the blur intensity to smooth the volumetric lights
  81034. */
  81035. _this.volumetricLightBlurScale = 64.0;
  81036. /**
  81037. * Light (spot or directional) used to generate the volumetric lights rays
  81038. * The source light must have a shadow generate so the pipeline can get its
  81039. * depth map
  81040. */
  81041. _this.sourceLight = null;
  81042. /**
  81043. * For eye adaptation, represents the minimum luminance the eye can see
  81044. */
  81045. _this.hdrMinimumLuminance = 1.0;
  81046. /**
  81047. * For eye adaptation, represents the decrease luminance speed
  81048. */
  81049. _this.hdrDecreaseRate = 0.5;
  81050. /**
  81051. * For eye adaptation, represents the increase luminance speed
  81052. */
  81053. _this.hdrIncreaseRate = 0.5;
  81054. /**
  81055. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  81056. */
  81057. _this.lensColorTexture = null;
  81058. /**
  81059. * The overall strengh for the lens flare effect
  81060. */
  81061. _this.lensFlareStrength = 20.0;
  81062. /**
  81063. * Dispersion coefficient for lens flare ghosts
  81064. */
  81065. _this.lensFlareGhostDispersal = 1.4;
  81066. /**
  81067. * Main lens flare halo width
  81068. */
  81069. _this.lensFlareHaloWidth = 0.7;
  81070. /**
  81071. * Based on the lens distortion effect, defines how much the lens flare result
  81072. * is distorted
  81073. */
  81074. _this.lensFlareDistortionStrength = 16.0;
  81075. /**
  81076. * Lens star texture must be used to simulate rays on the flares and is available
  81077. * in the documentation
  81078. */
  81079. _this.lensStarTexture = null;
  81080. /**
  81081. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  81082. * flare effect by taking account of the dirt texture
  81083. */
  81084. _this.lensFlareDirtTexture = null;
  81085. /**
  81086. * Represents the focal length for the depth of field effect
  81087. */
  81088. _this.depthOfFieldDistance = 10.0;
  81089. /**
  81090. * Represents the blur intensity for the blurred part of the depth of field effect
  81091. */
  81092. _this.depthOfFieldBlurWidth = 64.0;
  81093. /**
  81094. * For motion blur, defines how much the image is blurred by the movement
  81095. */
  81096. _this.motionStrength = 1.0;
  81097. /**
  81098. * List of animations for the pipeline (IAnimatable implementation)
  81099. */
  81100. _this.animations = [];
  81101. _this._currentDepthOfFieldSource = null;
  81102. _this._hdrCurrentLuminance = 1.0;
  81103. // Getters and setters
  81104. _this._bloomEnabled = false;
  81105. _this._depthOfFieldEnabled = false;
  81106. _this._vlsEnabled = false;
  81107. _this._lensFlareEnabled = false;
  81108. _this._hdrEnabled = false;
  81109. _this._motionBlurEnabled = false;
  81110. _this._fxaaEnabled = false;
  81111. _this._motionBlurSamples = 64.0;
  81112. _this._volumetricLightStepsCount = 50.0;
  81113. _this._samples = 1;
  81114. _this._cameras = cameras || [];
  81115. // Initialize
  81116. _this._scene = scene;
  81117. _this._basePostProcess = originalPostProcess;
  81118. _this._ratio = ratio;
  81119. // Misc
  81120. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81121. // Finish
  81122. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81123. _this._buildPipeline();
  81124. return _this;
  81125. }
  81126. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  81127. /**
  81128. * Specifies if the bloom pipeline is enabled
  81129. */
  81130. get: function () {
  81131. return this._bloomEnabled;
  81132. },
  81133. set: function (enabled) {
  81134. if (this._bloomEnabled === enabled) {
  81135. return;
  81136. }
  81137. this._bloomEnabled = enabled;
  81138. this._buildPipeline();
  81139. },
  81140. enumerable: true,
  81141. configurable: true
  81142. });
  81143. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  81144. /**
  81145. * Specifies if the depth of field pipeline is enabed
  81146. */
  81147. get: function () {
  81148. return this._depthOfFieldEnabled;
  81149. },
  81150. set: function (enabled) {
  81151. if (this._depthOfFieldEnabled === enabled) {
  81152. return;
  81153. }
  81154. this._depthOfFieldEnabled = enabled;
  81155. this._buildPipeline();
  81156. },
  81157. enumerable: true,
  81158. configurable: true
  81159. });
  81160. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  81161. /**
  81162. * Specifies if the lens flare pipeline is enabed
  81163. */
  81164. get: function () {
  81165. return this._lensFlareEnabled;
  81166. },
  81167. set: function (enabled) {
  81168. if (this._lensFlareEnabled === enabled) {
  81169. return;
  81170. }
  81171. this._lensFlareEnabled = enabled;
  81172. this._buildPipeline();
  81173. },
  81174. enumerable: true,
  81175. configurable: true
  81176. });
  81177. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  81178. /**
  81179. * Specifies if the HDR pipeline is enabled
  81180. */
  81181. get: function () {
  81182. return this._hdrEnabled;
  81183. },
  81184. set: function (enabled) {
  81185. if (this._hdrEnabled === enabled) {
  81186. return;
  81187. }
  81188. this._hdrEnabled = enabled;
  81189. this._buildPipeline();
  81190. },
  81191. enumerable: true,
  81192. configurable: true
  81193. });
  81194. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  81195. /**
  81196. * Specifies if the volumetric lights scattering effect is enabled
  81197. */
  81198. get: function () {
  81199. return this._vlsEnabled;
  81200. },
  81201. set: function (enabled) {
  81202. if (this._vlsEnabled === enabled) {
  81203. return;
  81204. }
  81205. if (enabled) {
  81206. var geometry = this._scene.enableGeometryBufferRenderer();
  81207. if (!geometry) {
  81208. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  81209. return;
  81210. }
  81211. }
  81212. this._vlsEnabled = enabled;
  81213. this._buildPipeline();
  81214. },
  81215. enumerable: true,
  81216. configurable: true
  81217. });
  81218. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  81219. /**
  81220. * Specifies if the motion blur effect is enabled
  81221. */
  81222. get: function () {
  81223. return this._motionBlurEnabled;
  81224. },
  81225. set: function (enabled) {
  81226. if (this._motionBlurEnabled === enabled) {
  81227. return;
  81228. }
  81229. this._motionBlurEnabled = enabled;
  81230. this._buildPipeline();
  81231. },
  81232. enumerable: true,
  81233. configurable: true
  81234. });
  81235. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  81236. /**
  81237. * Specifies if anti-aliasing is enabled
  81238. */
  81239. get: function () {
  81240. return this._fxaaEnabled;
  81241. },
  81242. set: function (enabled) {
  81243. if (this._fxaaEnabled === enabled) {
  81244. return;
  81245. }
  81246. this._fxaaEnabled = enabled;
  81247. this._buildPipeline();
  81248. },
  81249. enumerable: true,
  81250. configurable: true
  81251. });
  81252. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  81253. /**
  81254. * Specifies the number of steps used to calculate the volumetric lights
  81255. * Typically in interval [50, 200]
  81256. */
  81257. get: function () {
  81258. return this._volumetricLightStepsCount;
  81259. },
  81260. set: function (count) {
  81261. if (this.volumetricLightPostProcess) {
  81262. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  81263. }
  81264. this._volumetricLightStepsCount = count;
  81265. },
  81266. enumerable: true,
  81267. configurable: true
  81268. });
  81269. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  81270. /**
  81271. * Specifies the number of samples used for the motion blur effect
  81272. * Typically in interval [16, 64]
  81273. */
  81274. get: function () {
  81275. return this._motionBlurSamples;
  81276. },
  81277. set: function (samples) {
  81278. if (this.motionBlurPostProcess) {
  81279. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  81280. }
  81281. this._motionBlurSamples = samples;
  81282. },
  81283. enumerable: true,
  81284. configurable: true
  81285. });
  81286. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  81287. /**
  81288. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81289. */
  81290. get: function () {
  81291. return this._samples;
  81292. },
  81293. set: function (sampleCount) {
  81294. if (this._samples === sampleCount) {
  81295. return;
  81296. }
  81297. this._samples = sampleCount;
  81298. this._buildPipeline();
  81299. },
  81300. enumerable: true,
  81301. configurable: true
  81302. });
  81303. StandardRenderingPipeline.prototype._buildPipeline = function () {
  81304. var _this = this;
  81305. var ratio = this._ratio;
  81306. var scene = this._scene;
  81307. this._disposePostProcesses();
  81308. this._reset();
  81309. // Create pass post-process
  81310. if (!this._basePostProcess) {
  81311. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  81312. this.originalPostProcess.onApply = function (effect) {
  81313. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  81314. };
  81315. }
  81316. else {
  81317. this.originalPostProcess = this._basePostProcess;
  81318. }
  81319. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  81320. this._currentDepthOfFieldSource = this.originalPostProcess;
  81321. if (this._bloomEnabled) {
  81322. // Create down sample X4 post-process
  81323. this._createDownSampleX4PostProcess(scene, ratio / 2);
  81324. // Create bright pass post-process
  81325. this._createBrightPassPostProcess(scene, ratio / 2);
  81326. // Create gaussian blur post-processes (down sampling blurs)
  81327. this._createBlurPostProcesses(scene, ratio / 4, 1);
  81328. // Create texture adder post-process
  81329. this._createTextureAdderPostProcess(scene, ratio);
  81330. // Create depth-of-field source post-process
  81331. 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);
  81332. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  81333. }
  81334. if (this._vlsEnabled) {
  81335. // Create volumetric light
  81336. this._createVolumetricLightPostProcess(scene, ratio);
  81337. // Create volumetric light final post-process
  81338. 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);
  81339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  81340. }
  81341. if (this._lensFlareEnabled) {
  81342. // Create lens flare post-process
  81343. this._createLensFlarePostProcess(scene, ratio);
  81344. // Create depth-of-field source post-process post lens-flare and disable it now
  81345. 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);
  81346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  81347. }
  81348. if (this._hdrEnabled) {
  81349. // Create luminance
  81350. this._createLuminancePostProcesses(scene, this._floatTextureType);
  81351. // Create HDR
  81352. this._createHdrPostProcess(scene, ratio);
  81353. // Create depth-of-field source post-process post hdr and disable it now
  81354. 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);
  81355. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  81356. }
  81357. if (this._depthOfFieldEnabled) {
  81358. // Create gaussian blur used by depth-of-field
  81359. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  81360. // Create depth-of-field post-process
  81361. this._createDepthOfFieldPostProcess(scene, ratio);
  81362. }
  81363. if (this._motionBlurEnabled) {
  81364. // Create motion blur post-process
  81365. this._createMotionBlurPostProcess(scene, ratio);
  81366. }
  81367. if (this._fxaaEnabled) {
  81368. // Create fxaa post-process
  81369. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81370. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  81371. }
  81372. if (this._cameras !== null) {
  81373. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81374. }
  81375. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  81376. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81377. }
  81378. };
  81379. // Down Sample X4 Post-Processs
  81380. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  81381. var _this = this;
  81382. var downSampleX4Offsets = new Array(32);
  81383. 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);
  81384. this.downSampleX4PostProcess.onApply = function (effect) {
  81385. var id = 0;
  81386. var width = _this.downSampleX4PostProcess.width;
  81387. var height = _this.downSampleX4PostProcess.height;
  81388. for (var i = -2; i < 2; i++) {
  81389. for (var j = -2; j < 2; j++) {
  81390. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  81391. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  81392. id += 2;
  81393. }
  81394. }
  81395. effect.setArray2("dsOffsets", downSampleX4Offsets);
  81396. };
  81397. // Add to pipeline
  81398. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  81399. };
  81400. // Brightpass Post-Process
  81401. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  81402. var _this = this;
  81403. var brightOffsets = new Array(8);
  81404. 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);
  81405. this.brightPassPostProcess.onApply = function (effect) {
  81406. var sU = (1.0 / _this.brightPassPostProcess.width);
  81407. var sV = (1.0 / _this.brightPassPostProcess.height);
  81408. brightOffsets[0] = -0.5 * sU;
  81409. brightOffsets[1] = 0.5 * sV;
  81410. brightOffsets[2] = 0.5 * sU;
  81411. brightOffsets[3] = 0.5 * sV;
  81412. brightOffsets[4] = -0.5 * sU;
  81413. brightOffsets[5] = -0.5 * sV;
  81414. brightOffsets[6] = 0.5 * sU;
  81415. brightOffsets[7] = -0.5 * sV;
  81416. effect.setArray2("dsOffsets", brightOffsets);
  81417. effect.setFloat("brightThreshold", _this.brightThreshold);
  81418. };
  81419. // Add to pipeline
  81420. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  81421. };
  81422. // Create blur H&V post-processes
  81423. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  81424. var _this = this;
  81425. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  81426. var engine = scene.getEngine();
  81427. 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);
  81428. 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);
  81429. blurX.onActivateObservable.add(function () {
  81430. var dw = blurX.width / engine.getRenderWidth();
  81431. blurX.kernel = _this[blurWidthKey] * dw;
  81432. });
  81433. blurY.onActivateObservable.add(function () {
  81434. var dw = blurY.height / engine.getRenderHeight();
  81435. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  81436. });
  81437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  81438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  81439. this.blurHPostProcesses.push(blurX);
  81440. this.blurVPostProcesses.push(blurY);
  81441. };
  81442. // Create texture adder post-process
  81443. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  81444. var _this = this;
  81445. 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);
  81446. this.textureAdderPostProcess.onApply = function (effect) {
  81447. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  81448. effect.setTexture("lensSampler", _this.lensTexture);
  81449. effect.setFloat("exposure", _this.exposure);
  81450. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  81451. };
  81452. // Add to pipeline
  81453. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  81454. };
  81455. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  81456. var _this = this;
  81457. var geometryRenderer = scene.enableGeometryBufferRenderer();
  81458. geometryRenderer.enablePosition = true;
  81459. var geometry = geometryRenderer.getGBuffer();
  81460. // Base post-process
  81461. 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));
  81462. var depthValues = BABYLON.Vector2.Zero();
  81463. this.volumetricLightPostProcess.onApply = function (effect) {
  81464. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  81465. var generator = _this.sourceLight.getShadowGenerator();
  81466. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  81467. effect.setTexture("positionSampler", geometry.textures[2]);
  81468. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  81469. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  81470. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  81471. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  81472. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  81473. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  81474. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  81475. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  81476. effect.setVector2("depthValues", depthValues);
  81477. }
  81478. };
  81479. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  81480. // Smooth
  81481. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  81482. // Merge
  81483. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  81484. this.volumetricLightMergePostProces.onApply = function (effect) {
  81485. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  81486. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  81487. };
  81488. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  81489. };
  81490. // Create luminance
  81491. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  81492. var _this = this;
  81493. // Create luminance
  81494. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  81495. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  81496. var offsets = [];
  81497. this.luminancePostProcess.onApply = function (effect) {
  81498. var sU = (1.0 / _this.luminancePostProcess.width);
  81499. var sV = (1.0 / _this.luminancePostProcess.height);
  81500. offsets[0] = -0.5 * sU;
  81501. offsets[1] = 0.5 * sV;
  81502. offsets[2] = 0.5 * sU;
  81503. offsets[3] = 0.5 * sV;
  81504. offsets[4] = -0.5 * sU;
  81505. offsets[5] = -0.5 * sV;
  81506. offsets[6] = 0.5 * sU;
  81507. offsets[7] = -0.5 * sV;
  81508. effect.setArray2("lumOffsets", offsets);
  81509. };
  81510. // Add to pipeline
  81511. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  81512. // Create down sample luminance
  81513. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  81514. var size = Math.pow(3, i);
  81515. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  81516. if (i === 0) {
  81517. defines += "#define FINAL_DOWN_SAMPLER";
  81518. }
  81519. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  81520. this.luminanceDownSamplePostProcesses.push(postProcess);
  81521. }
  81522. // Create callbacks and add effects
  81523. var lastLuminance = this.luminancePostProcess;
  81524. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  81525. var downSampleOffsets = new Array(18);
  81526. pp.onApply = function (effect) {
  81527. if (!lastLuminance) {
  81528. return;
  81529. }
  81530. var id = 0;
  81531. for (var x = -1; x < 2; x++) {
  81532. for (var y = -1; y < 2; y++) {
  81533. downSampleOffsets[id] = x / lastLuminance.width;
  81534. downSampleOffsets[id + 1] = y / lastLuminance.height;
  81535. id += 2;
  81536. }
  81537. }
  81538. effect.setArray2("dsOffsets", downSampleOffsets);
  81539. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  81540. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  81541. lastLuminance = _this.luminancePostProcess;
  81542. }
  81543. else {
  81544. lastLuminance = pp;
  81545. }
  81546. };
  81547. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  81548. pp.onAfterRender = function (effect) {
  81549. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  81550. 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);
  81551. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  81552. };
  81553. }
  81554. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  81555. });
  81556. };
  81557. // Create HDR post-process
  81558. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  81559. var _this = this;
  81560. 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);
  81561. var outputLiminance = 1;
  81562. var time = 0;
  81563. var lastTime = 0;
  81564. this.hdrPostProcess.onApply = function (effect) {
  81565. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  81566. time += scene.getEngine().getDeltaTime();
  81567. if (outputLiminance < 0) {
  81568. outputLiminance = _this._hdrCurrentLuminance;
  81569. }
  81570. else {
  81571. var dt = (lastTime - time) / 1000.0;
  81572. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  81573. outputLiminance += _this.hdrDecreaseRate * dt;
  81574. }
  81575. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  81576. outputLiminance -= _this.hdrIncreaseRate * dt;
  81577. }
  81578. else {
  81579. outputLiminance = _this._hdrCurrentLuminance;
  81580. }
  81581. }
  81582. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  81583. effect.setFloat("averageLuminance", outputLiminance);
  81584. lastTime = time;
  81585. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  81586. };
  81587. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  81588. };
  81589. // Create lens flare post-process
  81590. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  81591. var _this = this;
  81592. 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);
  81593. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  81594. this._createBlurPostProcesses(scene, ratio / 4, 2);
  81595. 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);
  81596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  81597. var resolution = new BABYLON.Vector2(0, 0);
  81598. // Lens flare
  81599. this.lensFlarePostProcess.onApply = function (effect) {
  81600. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  81601. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  81602. effect.setFloat("strength", _this.lensFlareStrength);
  81603. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  81604. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  81605. // Shift
  81606. resolution.x = _this.lensFlarePostProcess.width;
  81607. resolution.y = _this.lensFlarePostProcess.height;
  81608. effect.setVector2("resolution", resolution);
  81609. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  81610. };
  81611. // Compose
  81612. 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);
  81613. 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);
  81614. this.lensFlareComposePostProcess.onApply = function (effect) {
  81615. if (!_this._scene.activeCamera) {
  81616. return;
  81617. }
  81618. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  81619. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  81620. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  81621. // Lens start rotation matrix
  81622. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  81623. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  81624. 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));
  81625. camRot *= 4.0;
  81626. 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);
  81627. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  81628. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  81629. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  81630. };
  81631. };
  81632. // Create depth-of-field post-process
  81633. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  81634. var _this = this;
  81635. 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);
  81636. this.depthOfFieldPostProcess.onApply = function (effect) {
  81637. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  81638. effect.setTexture("depthSampler", _this._getDepthTexture());
  81639. effect.setFloat("distance", _this.depthOfFieldDistance);
  81640. };
  81641. // Add to pipeline
  81642. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  81643. };
  81644. // Create motion blur post-process
  81645. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  81646. var _this = this;
  81647. 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);
  81648. var motionScale = 0;
  81649. var prevViewProjection = BABYLON.Matrix.Identity();
  81650. var invViewProjection = BABYLON.Matrix.Identity();
  81651. var viewProjection = BABYLON.Matrix.Identity();
  81652. var screenSize = BABYLON.Vector2.Zero();
  81653. this.motionBlurPostProcess.onApply = function (effect) {
  81654. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  81655. viewProjection.invertToRef(invViewProjection);
  81656. effect.setMatrix("inverseViewProjection", invViewProjection);
  81657. effect.setMatrix("prevViewProjection", prevViewProjection);
  81658. prevViewProjection = viewProjection;
  81659. screenSize.x = _this.motionBlurPostProcess.width;
  81660. screenSize.y = _this.motionBlurPostProcess.height;
  81661. effect.setVector2("screenSize", screenSize);
  81662. motionScale = scene.getEngine().getFps() / 60.0;
  81663. effect.setFloat("motionScale", motionScale);
  81664. effect.setFloat("motionStrength", _this.motionStrength);
  81665. effect.setTexture("depthSampler", _this._getDepthTexture());
  81666. };
  81667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  81668. };
  81669. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  81670. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  81671. var renderer = this._scene.enableGeometryBufferRenderer();
  81672. return renderer.getGBuffer().textures[0];
  81673. }
  81674. return this._scene.enableDepthRenderer().getDepthMap();
  81675. };
  81676. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  81677. for (var i = 0; i < this._cameras.length; i++) {
  81678. var camera = this._cameras[i];
  81679. if (this.originalPostProcess) {
  81680. this.originalPostProcess.dispose(camera);
  81681. }
  81682. if (this.downSampleX4PostProcess) {
  81683. this.downSampleX4PostProcess.dispose(camera);
  81684. }
  81685. if (this.brightPassPostProcess) {
  81686. this.brightPassPostProcess.dispose(camera);
  81687. }
  81688. if (this.textureAdderPostProcess) {
  81689. this.textureAdderPostProcess.dispose(camera);
  81690. }
  81691. if (this.textureAdderFinalPostProcess) {
  81692. this.textureAdderFinalPostProcess.dispose(camera);
  81693. }
  81694. if (this.volumetricLightPostProcess) {
  81695. this.volumetricLightPostProcess.dispose(camera);
  81696. }
  81697. if (this.volumetricLightSmoothXPostProcess) {
  81698. this.volumetricLightSmoothXPostProcess.dispose(camera);
  81699. }
  81700. if (this.volumetricLightSmoothYPostProcess) {
  81701. this.volumetricLightSmoothYPostProcess.dispose(camera);
  81702. }
  81703. if (this.volumetricLightMergePostProces) {
  81704. this.volumetricLightMergePostProces.dispose(camera);
  81705. }
  81706. if (this.volumetricLightFinalPostProcess) {
  81707. this.volumetricLightFinalPostProcess.dispose(camera);
  81708. }
  81709. if (this.lensFlarePostProcess) {
  81710. this.lensFlarePostProcess.dispose(camera);
  81711. }
  81712. if (this.lensFlareComposePostProcess) {
  81713. this.lensFlareComposePostProcess.dispose(camera);
  81714. }
  81715. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  81716. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  81717. }
  81718. if (this.luminancePostProcess) {
  81719. this.luminancePostProcess.dispose(camera);
  81720. }
  81721. if (this.hdrPostProcess) {
  81722. this.hdrPostProcess.dispose(camera);
  81723. }
  81724. if (this.hdrFinalPostProcess) {
  81725. this.hdrFinalPostProcess.dispose(camera);
  81726. }
  81727. if (this.depthOfFieldPostProcess) {
  81728. this.depthOfFieldPostProcess.dispose(camera);
  81729. }
  81730. if (this.motionBlurPostProcess) {
  81731. this.motionBlurPostProcess.dispose(camera);
  81732. }
  81733. if (this.fxaaPostProcess) {
  81734. this.fxaaPostProcess.dispose(camera);
  81735. }
  81736. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  81737. this.blurHPostProcesses[j].dispose(camera);
  81738. }
  81739. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  81740. this.blurVPostProcesses[j].dispose(camera);
  81741. }
  81742. }
  81743. this.originalPostProcess = null;
  81744. this.downSampleX4PostProcess = null;
  81745. this.brightPassPostProcess = null;
  81746. this.textureAdderPostProcess = null;
  81747. this.textureAdderFinalPostProcess = null;
  81748. this.volumetricLightPostProcess = null;
  81749. this.volumetricLightSmoothXPostProcess = null;
  81750. this.volumetricLightSmoothYPostProcess = null;
  81751. this.volumetricLightMergePostProces = null;
  81752. this.volumetricLightFinalPostProcess = null;
  81753. this.lensFlarePostProcess = null;
  81754. this.lensFlareComposePostProcess = null;
  81755. this.luminancePostProcess = null;
  81756. this.hdrPostProcess = null;
  81757. this.hdrFinalPostProcess = null;
  81758. this.depthOfFieldPostProcess = null;
  81759. this.motionBlurPostProcess = null;
  81760. this.fxaaPostProcess = null;
  81761. this.luminanceDownSamplePostProcesses = [];
  81762. this.blurHPostProcesses = [];
  81763. this.blurVPostProcesses = [];
  81764. };
  81765. /**
  81766. * Dispose of the pipeline and stop all post processes
  81767. */
  81768. StandardRenderingPipeline.prototype.dispose = function () {
  81769. this._disposePostProcesses();
  81770. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81771. _super.prototype.dispose.call(this);
  81772. };
  81773. /**
  81774. * Serialize the rendering pipeline (Used when exporting)
  81775. * @returns the serialized object
  81776. */
  81777. StandardRenderingPipeline.prototype.serialize = function () {
  81778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81779. if (this.sourceLight) {
  81780. serializationObject.sourceLightId = this.sourceLight.id;
  81781. }
  81782. serializationObject.customType = "StandardRenderingPipeline";
  81783. return serializationObject;
  81784. };
  81785. /**
  81786. * Parse the serialized pipeline
  81787. * @param source Source pipeline.
  81788. * @param scene The scene to load the pipeline to.
  81789. * @param rootUrl The URL of the serialized pipeline.
  81790. * @returns An instantiated pipeline from the serialized object.
  81791. */
  81792. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81793. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81794. if (source.sourceLightId) {
  81795. p.sourceLight = scene.getLightByID(source.sourceLightId);
  81796. }
  81797. return p;
  81798. };
  81799. // Luminance steps
  81800. StandardRenderingPipeline.LuminanceSteps = 6;
  81801. __decorate([
  81802. BABYLON.serialize()
  81803. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  81804. __decorate([
  81805. BABYLON.serialize()
  81806. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  81807. __decorate([
  81808. BABYLON.serialize()
  81809. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  81810. __decorate([
  81811. BABYLON.serialize()
  81812. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  81813. __decorate([
  81814. BABYLON.serializeAsTexture("lensTexture")
  81815. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  81816. __decorate([
  81817. BABYLON.serialize()
  81818. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  81819. __decorate([
  81820. BABYLON.serialize()
  81821. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  81822. __decorate([
  81823. BABYLON.serialize()
  81824. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  81825. __decorate([
  81826. BABYLON.serialize()
  81827. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  81828. __decorate([
  81829. BABYLON.serialize()
  81830. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  81831. __decorate([
  81832. BABYLON.serialize()
  81833. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  81834. __decorate([
  81835. BABYLON.serializeAsTexture("lensColorTexture")
  81836. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  81837. __decorate([
  81838. BABYLON.serialize()
  81839. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  81840. __decorate([
  81841. BABYLON.serialize()
  81842. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  81843. __decorate([
  81844. BABYLON.serialize()
  81845. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  81846. __decorate([
  81847. BABYLON.serialize()
  81848. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  81849. __decorate([
  81850. BABYLON.serializeAsTexture("lensStarTexture")
  81851. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  81852. __decorate([
  81853. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  81854. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  81855. __decorate([
  81856. BABYLON.serialize()
  81857. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  81858. __decorate([
  81859. BABYLON.serialize()
  81860. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  81861. __decorate([
  81862. BABYLON.serialize()
  81863. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  81864. __decorate([
  81865. BABYLON.serialize()
  81866. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  81867. __decorate([
  81868. BABYLON.serialize()
  81869. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  81870. __decorate([
  81871. BABYLON.serialize()
  81872. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  81873. __decorate([
  81874. BABYLON.serialize()
  81875. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  81876. __decorate([
  81877. BABYLON.serialize()
  81878. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  81879. __decorate([
  81880. BABYLON.serialize()
  81881. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  81882. __decorate([
  81883. BABYLON.serialize()
  81884. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  81885. __decorate([
  81886. BABYLON.serialize()
  81887. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  81888. __decorate([
  81889. BABYLON.serialize()
  81890. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  81891. __decorate([
  81892. BABYLON.serialize()
  81893. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  81894. __decorate([
  81895. BABYLON.serialize()
  81896. ], StandardRenderingPipeline.prototype, "samples", null);
  81897. return StandardRenderingPipeline;
  81898. }(BABYLON.PostProcessRenderPipeline));
  81899. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  81900. })(BABYLON || (BABYLON = {}));
  81901. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  81902. var BABYLON;
  81903. (function (BABYLON) {
  81904. var FxaaPostProcess = /** @class */ (function (_super) {
  81905. __extends(FxaaPostProcess, _super);
  81906. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  81907. if (camera === void 0) { camera = null; }
  81908. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81909. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  81910. var defines = _this._getDefines();
  81911. _this.updateEffect(defines);
  81912. _this.onApplyObservable.add(function (effect) {
  81913. var texelSize = _this.texelSize;
  81914. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  81915. });
  81916. return _this;
  81917. }
  81918. FxaaPostProcess.prototype._getDefines = function () {
  81919. var engine = this.getEngine();
  81920. if (!engine) {
  81921. return null;
  81922. }
  81923. var glInfo = engine.getGlInfo();
  81924. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  81925. return "#define MALI 1\n";
  81926. }
  81927. return null;
  81928. };
  81929. return FxaaPostProcess;
  81930. }(BABYLON.PostProcess));
  81931. BABYLON.FxaaPostProcess = FxaaPostProcess;
  81932. })(BABYLON || (BABYLON = {}));
  81933. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  81934. var BABYLON;
  81935. (function (BABYLON) {
  81936. /**
  81937. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  81938. */
  81939. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  81940. __extends(ChromaticAberrationPostProcess, _super);
  81941. /**
  81942. * Creates a new instance ChromaticAberrationPostProcess
  81943. * @param name The name of the effect.
  81944. * @param screenWidth The width of the screen to apply the effect on.
  81945. * @param screenHeight The height of the screen to apply the effect on.
  81946. * @param options The required width/height ratio to downsize to before computing the render pass.
  81947. * @param camera The camera to apply the render pass to.
  81948. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81949. * @param engine The engine which the post process will be applied. (default: current engine)
  81950. * @param reusable If the post process can be reused on the same frame. (default: false)
  81951. * @param textureType Type of textures used when performing the post process. (default: 0)
  81952. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  81953. */
  81954. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81955. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81956. if (blockCompilation === void 0) { blockCompilation = false; }
  81957. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81958. /**
  81959. * The amount of seperation of rgb channels (default: 30)
  81960. */
  81961. _this.aberrationAmount = 30;
  81962. /**
  81963. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  81964. */
  81965. _this.radialIntensity = 0;
  81966. /**
  81967. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  81968. */
  81969. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  81970. /**
  81971. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  81972. */
  81973. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  81974. _this.onApplyObservable.add(function (effect) {
  81975. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  81976. effect.setFloat('screen_width', screenWidth);
  81977. effect.setFloat('screen_height', screenHeight);
  81978. effect.setFloat('radialIntensity', _this.radialIntensity);
  81979. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  81980. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  81981. });
  81982. return _this;
  81983. }
  81984. return ChromaticAberrationPostProcess;
  81985. }(BABYLON.PostProcess));
  81986. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  81987. })(BABYLON || (BABYLON = {}));
  81988. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  81989. var BABYLON;
  81990. (function (BABYLON) {
  81991. /**
  81992. * The GrainPostProcess adds noise to the image at mid luminance levels
  81993. */
  81994. var GrainPostProcess = /** @class */ (function (_super) {
  81995. __extends(GrainPostProcess, _super);
  81996. /**
  81997. * Creates a new instance of @see GrainPostProcess
  81998. * @param name The name of the effect.
  81999. * @param options The required width/height ratio to downsize to before computing the render pass.
  82000. * @param camera The camera to apply the render pass to.
  82001. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82002. * @param engine The engine which the post process will be applied. (default: current engine)
  82003. * @param reusable If the post process can be reused on the same frame. (default: false)
  82004. * @param textureType Type of textures used when performing the post process. (default: 0)
  82005. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82006. */
  82007. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82008. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82009. if (blockCompilation === void 0) { blockCompilation = false; }
  82010. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82011. /**
  82012. * The intensity of the grain added (default: 30)
  82013. */
  82014. _this.intensity = 30;
  82015. /**
  82016. * If the grain should be randomized on every frame
  82017. */
  82018. _this.animated = false;
  82019. _this.onApplyObservable.add(function (effect) {
  82020. effect.setFloat('intensity', _this.intensity);
  82021. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  82022. });
  82023. return _this;
  82024. }
  82025. return GrainPostProcess;
  82026. }(BABYLON.PostProcess));
  82027. BABYLON.GrainPostProcess = GrainPostProcess;
  82028. })(BABYLON || (BABYLON = {}));
  82029. //# sourceMappingURL=babylon.grainPostProcess.js.map
  82030. var BABYLON;
  82031. (function (BABYLON) {
  82032. /**
  82033. * The SharpenPostProcess applies a sharpen kernel to every pixel
  82034. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82035. */
  82036. var SharpenPostProcess = /** @class */ (function (_super) {
  82037. __extends(SharpenPostProcess, _super);
  82038. /**
  82039. * Creates a new instance ConvolutionPostProcess
  82040. * @param name The name of the effect.
  82041. * @param options The required width/height ratio to downsize to before computing the render pass.
  82042. * @param camera The camera to apply the render pass to.
  82043. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82044. * @param engine The engine which the post process will be applied. (default: current engine)
  82045. * @param reusable If the post process can be reused on the same frame. (default: false)
  82046. * @param textureType Type of textures used when performing the post process. (default: 0)
  82047. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82048. */
  82049. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82050. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82051. if (blockCompilation === void 0) { blockCompilation = false; }
  82052. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82053. /**
  82054. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  82055. */
  82056. _this.colorAmount = 1.0;
  82057. /**
  82058. * How much sharpness should be applied (default: 0.3)
  82059. */
  82060. _this.edgeAmount = 0.3;
  82061. _this.onApply = function (effect) {
  82062. effect.setFloat2("screenSize", _this.width, _this.height);
  82063. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  82064. };
  82065. return _this;
  82066. }
  82067. return SharpenPostProcess;
  82068. }(BABYLON.PostProcess));
  82069. BABYLON.SharpenPostProcess = SharpenPostProcess;
  82070. })(BABYLON || (BABYLON = {}));
  82071. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  82072. var BABYLON;
  82073. (function (BABYLON) {
  82074. /**
  82075. * The Blur Post Process which blurs an image based on a kernel and direction.
  82076. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  82077. */
  82078. var BlurPostProcess = /** @class */ (function (_super) {
  82079. __extends(BlurPostProcess, _super);
  82080. /**
  82081. * Creates a new instance BlurPostProcess
  82082. * @param name The name of the effect.
  82083. * @param direction The direction in which to blur the image.
  82084. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  82085. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  82086. * @param camera The camera to apply the render pass to.
  82087. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82088. * @param engine The engine which the post process will be applied. (default: current engine)
  82089. * @param reusable If the post process can be reused on the same frame. (default: false)
  82090. * @param textureType Type of textures used when performing the post process. (default: 0)
  82091. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82092. */
  82093. function BlurPostProcess(name,
  82094. /** The direction in which to blur the image. */
  82095. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  82096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82097. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82098. if (defines === void 0) { defines = ""; }
  82099. if (blockCompilation === void 0) { blockCompilation = false; }
  82100. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  82101. _this.direction = direction;
  82102. _this.blockCompilation = blockCompilation;
  82103. _this._packedFloat = false;
  82104. _this._staticDefines = "";
  82105. _this._staticDefines = defines;
  82106. _this.onApplyObservable.add(function (effect) {
  82107. if (_this._outputTexture) {
  82108. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  82109. }
  82110. else {
  82111. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  82112. }
  82113. });
  82114. _this.kernel = kernel;
  82115. return _this;
  82116. }
  82117. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  82118. /**
  82119. * Gets the length in pixels of the blur sample region
  82120. */
  82121. get: function () {
  82122. return this._idealKernel;
  82123. },
  82124. /**
  82125. * Sets the length in pixels of the blur sample region
  82126. */
  82127. set: function (v) {
  82128. if (this._idealKernel === v) {
  82129. return;
  82130. }
  82131. v = Math.max(v, 1);
  82132. this._idealKernel = v;
  82133. this._kernel = this._nearestBestKernel(v);
  82134. if (!this.blockCompilation) {
  82135. this._updateParameters();
  82136. }
  82137. },
  82138. enumerable: true,
  82139. configurable: true
  82140. });
  82141. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  82142. /**
  82143. * Gets wether or not the blur is unpacking/repacking floats
  82144. */
  82145. get: function () {
  82146. return this._packedFloat;
  82147. },
  82148. /**
  82149. * Sets wether or not the blur needs to unpack/repack floats
  82150. */
  82151. set: function (v) {
  82152. if (this._packedFloat === v) {
  82153. return;
  82154. }
  82155. this._packedFloat = v;
  82156. if (!this.blockCompilation) {
  82157. this._updateParameters();
  82158. }
  82159. },
  82160. enumerable: true,
  82161. configurable: true
  82162. });
  82163. /**
  82164. * Updates the effect with the current post process compile time values and recompiles the shader.
  82165. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  82166. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  82167. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  82168. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  82169. * @param onCompiled Called when the shader has been compiled.
  82170. * @param onError Called if there is an error when compiling a shader.
  82171. */
  82172. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  82173. if (defines === void 0) { defines = null; }
  82174. if (uniforms === void 0) { uniforms = null; }
  82175. if (samplers === void 0) { samplers = null; }
  82176. this._updateParameters(onCompiled, onError);
  82177. };
  82178. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  82179. // Generate sampling offsets and weights
  82180. var N = this._kernel;
  82181. var centerIndex = (N - 1) / 2;
  82182. // Generate Gaussian sampling weights over kernel
  82183. var offsets = [];
  82184. var weights = [];
  82185. var totalWeight = 0;
  82186. for (var i = 0; i < N; i++) {
  82187. var u = i / (N - 1);
  82188. var w = this._gaussianWeight(u * 2.0 - 1);
  82189. offsets[i] = (i - centerIndex);
  82190. weights[i] = w;
  82191. totalWeight += w;
  82192. }
  82193. // Normalize weights
  82194. for (var i = 0; i < weights.length; i++) {
  82195. weights[i] /= totalWeight;
  82196. }
  82197. // Optimize: combine samples to take advantage of hardware linear sampling
  82198. // Walk from left to center, combining pairs (symmetrically)
  82199. var linearSamplingWeights = [];
  82200. var linearSamplingOffsets = [];
  82201. var linearSamplingMap = [];
  82202. for (var i = 0; i <= centerIndex; i += 2) {
  82203. var j = Math.min(i + 1, Math.floor(centerIndex));
  82204. var singleCenterSample = i === j;
  82205. if (singleCenterSample) {
  82206. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  82207. }
  82208. else {
  82209. var sharedCell = j === centerIndex;
  82210. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  82211. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  82212. if (offsetLinear === 0) {
  82213. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  82214. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  82215. }
  82216. else {
  82217. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  82218. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  82219. }
  82220. }
  82221. }
  82222. for (var i = 0; i < linearSamplingMap.length; i++) {
  82223. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  82224. linearSamplingWeights[i] = linearSamplingMap[i].w;
  82225. }
  82226. // Replace with optimized
  82227. offsets = linearSamplingOffsets;
  82228. weights = linearSamplingWeights;
  82229. // Generate shaders
  82230. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  82231. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  82232. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  82233. var defines = "";
  82234. defines += this._staticDefines;
  82235. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  82236. if (this._staticDefines.indexOf("DOF") != -1) {
  82237. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  82238. varyingCount--;
  82239. }
  82240. for (var i = 0; i < varyingCount; i++) {
  82241. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  82242. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  82243. }
  82244. var depCount = 0;
  82245. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  82246. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  82247. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  82248. depCount++;
  82249. }
  82250. if (this.packedFloat) {
  82251. defines += "#define PACKEDFLOAT 1";
  82252. }
  82253. this.blockCompilation = false;
  82254. _super.prototype.updateEffect.call(this, defines, null, null, {
  82255. varyingCount: varyingCount,
  82256. depCount: depCount
  82257. }, onCompiled, onError);
  82258. };
  82259. /**
  82260. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  82261. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  82262. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  82263. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  82264. * The gaps between physical kernels are compensated for in the weighting of the samples
  82265. * @param idealKernel Ideal blur kernel.
  82266. * @return Nearest best kernel.
  82267. */
  82268. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  82269. var v = Math.round(idealKernel);
  82270. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  82271. var k = _a[_i];
  82272. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  82273. return Math.max(k, 3);
  82274. }
  82275. }
  82276. return Math.max(v, 3);
  82277. };
  82278. /**
  82279. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  82280. * @param x The point on the Gaussian distribution to sample.
  82281. * @return the value of the Gaussian function at x.
  82282. */
  82283. BlurPostProcess.prototype._gaussianWeight = function (x) {
  82284. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  82285. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  82286. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  82287. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  82288. // truncated at around 1.3% of peak strength.
  82289. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  82290. var sigma = (1 / 3);
  82291. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  82292. var exponent = -((x * x) / (2.0 * sigma * sigma));
  82293. var weight = (1.0 / denominator) * Math.exp(exponent);
  82294. return weight;
  82295. };
  82296. /**
  82297. * Generates a string that can be used as a floating point number in GLSL.
  82298. * @param x Value to print.
  82299. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  82300. * @return GLSL float string.
  82301. */
  82302. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  82303. if (decimalFigures === void 0) { decimalFigures = 8; }
  82304. return x.toFixed(decimalFigures).replace(/0+$/, '');
  82305. };
  82306. return BlurPostProcess;
  82307. }(BABYLON.PostProcess));
  82308. BABYLON.BlurPostProcess = BlurPostProcess;
  82309. })(BABYLON || (BABYLON = {}));
  82310. //# sourceMappingURL=babylon.blurPostProcess.js.map
  82311. var BABYLON;
  82312. (function (BABYLON) {
  82313. /**
  82314. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  82315. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  82316. * based on samples that have a large difference in distance than the center pixel.
  82317. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  82318. */
  82319. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  82320. __extends(DepthOfFieldBlurPostProcess, _super);
  82321. /**
  82322. * Creates a new instance CircleOfConfusionPostProcess
  82323. * @param name The name of the effect.
  82324. * @param scene The scene the effect belongs to.
  82325. * @param direction The direction the blur should be applied.
  82326. * @param kernel The size of the kernel used to blur.
  82327. * @param options The required width/height ratio to downsize to before computing the render pass.
  82328. * @param camera The camera to apply the render pass to.
  82329. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  82330. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  82331. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82332. * @param engine The engine which the post process will be applied. (default: current engine)
  82333. * @param reusable If the post process can be reused on the same frame. (default: false)
  82334. * @param textureType Type of textures used when performing the post process. (default: 0)
  82335. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82336. */
  82337. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  82338. if (imageToBlur === void 0) { imageToBlur = null; }
  82339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82340. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82341. if (blockCompilation === void 0) { blockCompilation = false; }
  82342. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  82343. _this.direction = direction;
  82344. _this.onApplyObservable.add(function (effect) {
  82345. if (imageToBlur != null) {
  82346. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  82347. }
  82348. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  82349. if (scene.activeCamera) {
  82350. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  82351. }
  82352. });
  82353. return _this;
  82354. }
  82355. return DepthOfFieldBlurPostProcess;
  82356. }(BABYLON.BlurPostProcess));
  82357. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  82358. })(BABYLON || (BABYLON = {}));
  82359. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  82360. var BABYLON;
  82361. (function (BABYLON) {
  82362. /**
  82363. * Options to be set when merging outputs from the default pipeline.
  82364. */
  82365. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  82366. function DepthOfFieldMergePostProcessOptions() {
  82367. }
  82368. return DepthOfFieldMergePostProcessOptions;
  82369. }());
  82370. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  82371. /**
  82372. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  82373. */
  82374. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  82375. __extends(DepthOfFieldMergePostProcess, _super);
  82376. /**
  82377. * Creates a new instance of DepthOfFieldMergePostProcess
  82378. * @param name The name of the effect.
  82379. * @param originalFromInput Post process which's input will be used for the merge.
  82380. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  82381. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  82382. * @param options The required width/height ratio to downsize to before computing the render pass.
  82383. * @param camera The camera to apply the render pass to.
  82384. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82385. * @param engine The engine which the post process will be applied. (default: current engine)
  82386. * @param reusable If the post process can be reused on the same frame. (default: false)
  82387. * @param textureType Type of textures used when performing the post process. (default: 0)
  82388. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82389. */
  82390. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82391. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82392. if (blockCompilation === void 0) { blockCompilation = false; }
  82393. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  82394. _this.blurSteps = blurSteps;
  82395. _this.onApplyObservable.add(function (effect) {
  82396. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  82397. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  82398. blurSteps.forEach(function (step, index) {
  82399. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  82400. });
  82401. });
  82402. if (!blockCompilation) {
  82403. _this.updateEffect();
  82404. }
  82405. return _this;
  82406. }
  82407. /**
  82408. * Updates the effect with the current post process compile time values and recompiles the shader.
  82409. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  82410. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  82411. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  82412. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  82413. * @param onCompiled Called when the shader has been compiled.
  82414. * @param onError Called if there is an error when compiling a shader.
  82415. */
  82416. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  82417. if (defines === void 0) { defines = null; }
  82418. if (uniforms === void 0) { uniforms = null; }
  82419. if (samplers === void 0) { samplers = null; }
  82420. if (!defines) {
  82421. defines = "";
  82422. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  82423. }
  82424. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  82425. };
  82426. return DepthOfFieldMergePostProcess;
  82427. }(BABYLON.PostProcess));
  82428. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  82429. })(BABYLON || (BABYLON = {}));
  82430. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  82431. var BABYLON;
  82432. (function (BABYLON) {
  82433. /**
  82434. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  82435. */
  82436. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  82437. __extends(CircleOfConfusionPostProcess, _super);
  82438. /**
  82439. * Creates a new instance CircleOfConfusionPostProcess
  82440. * @param name The name of the effect.
  82441. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  82442. * @param options The required width/height ratio to downsize to before computing the render pass.
  82443. * @param camera The camera to apply the render pass to.
  82444. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82445. * @param engine The engine which the post process will be applied. (default: current engine)
  82446. * @param reusable If the post process can be reused on the same frame. (default: false)
  82447. * @param textureType Type of textures used when performing the post process. (default: 0)
  82448. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82449. */
  82450. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82451. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82452. if (blockCompilation === void 0) { blockCompilation = false; }
  82453. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82454. /**
  82455. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  82456. */
  82457. _this.lensSize = 50;
  82458. /**
  82459. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  82460. */
  82461. _this.fStop = 1.4;
  82462. /**
  82463. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  82464. */
  82465. _this.focusDistance = 2000;
  82466. /**
  82467. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  82468. */
  82469. _this.focalLength = 50;
  82470. _this._depthTexture = null;
  82471. _this._depthTexture = depthTexture;
  82472. _this.onApplyObservable.add(function (effect) {
  82473. if (!_this._depthTexture) {
  82474. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  82475. return;
  82476. }
  82477. effect.setTexture("depthSampler", _this._depthTexture);
  82478. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  82479. var aperture = _this.lensSize / _this.fStop;
  82480. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  82481. effect.setFloat('focusDistance', _this.focusDistance);
  82482. effect.setFloat('cocPrecalculation', cocPrecalculation);
  82483. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  82484. });
  82485. return _this;
  82486. }
  82487. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  82488. /**
  82489. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  82490. */
  82491. set: function (value) {
  82492. this._depthTexture = value;
  82493. },
  82494. enumerable: true,
  82495. configurable: true
  82496. });
  82497. return CircleOfConfusionPostProcess;
  82498. }(BABYLON.PostProcess));
  82499. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  82500. })(BABYLON || (BABYLON = {}));
  82501. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  82502. var BABYLON;
  82503. (function (BABYLON) {
  82504. /**
  82505. * Specifies the level of max blur that should be applied when using the depth of field effect
  82506. */
  82507. var DepthOfFieldEffectBlurLevel;
  82508. (function (DepthOfFieldEffectBlurLevel) {
  82509. /**
  82510. * Subtle blur
  82511. */
  82512. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  82513. /**
  82514. * Medium blur
  82515. */
  82516. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  82517. /**
  82518. * Large blur
  82519. */
  82520. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  82521. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  82522. ;
  82523. /**
  82524. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  82525. */
  82526. var DepthOfFieldEffect = /** @class */ (function (_super) {
  82527. __extends(DepthOfFieldEffect, _super);
  82528. /**
  82529. * Creates a new instance DepthOfFieldEffect
  82530. * @param scene The scene the effect belongs to.
  82531. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  82532. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  82533. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82534. */
  82535. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  82536. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  82537. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  82538. if (blockCompilation === void 0) { blockCompilation = false; }
  82539. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  82540. return _this._effects;
  82541. }, true) || this;
  82542. /**
  82543. * @hidden Internal post processes in depth of field effect
  82544. */
  82545. _this._effects = [];
  82546. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  82547. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82548. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  82549. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  82550. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  82551. _this._depthOfFieldBlurY = [];
  82552. _this._depthOfFieldBlurX = [];
  82553. var blurCount = 1;
  82554. var kernelSize = 15;
  82555. switch (blurLevel) {
  82556. case DepthOfFieldEffectBlurLevel.High: {
  82557. blurCount = 3;
  82558. kernelSize = 51;
  82559. break;
  82560. }
  82561. case DepthOfFieldEffectBlurLevel.Medium: {
  82562. blurCount = 2;
  82563. kernelSize = 31;
  82564. break;
  82565. }
  82566. default: {
  82567. kernelSize = 15;
  82568. blurCount = 1;
  82569. break;
  82570. }
  82571. }
  82572. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  82573. var ratio = 1.0;
  82574. for (var i = 0; i < blurCount; i++) {
  82575. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82576. blurY.autoClear = false;
  82577. ratio = 0.75 / Math.pow(2, i);
  82578. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82579. blurX.autoClear = false;
  82580. _this._depthOfFieldBlurY.push(blurY);
  82581. _this._depthOfFieldBlurX.push(blurX);
  82582. }
  82583. // Set all post processes on the effect.
  82584. _this._effects = [_this._circleOfConfusion];
  82585. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  82586. _this._effects.push(_this._depthOfFieldBlurY[i]);
  82587. _this._effects.push(_this._depthOfFieldBlurX[i]);
  82588. }
  82589. // Merge blurred images with original image based on circleOfConfusion
  82590. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82591. _this._dofMerge.autoClear = false;
  82592. _this._effects.push(_this._dofMerge);
  82593. return _this;
  82594. }
  82595. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  82596. get: function () {
  82597. return this._circleOfConfusion.focalLength;
  82598. },
  82599. /**
  82600. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  82601. */
  82602. set: function (value) {
  82603. this._circleOfConfusion.focalLength = value;
  82604. },
  82605. enumerable: true,
  82606. configurable: true
  82607. });
  82608. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  82609. get: function () {
  82610. return this._circleOfConfusion.fStop;
  82611. },
  82612. /**
  82613. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  82614. */
  82615. set: function (value) {
  82616. this._circleOfConfusion.fStop = value;
  82617. },
  82618. enumerable: true,
  82619. configurable: true
  82620. });
  82621. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  82622. get: function () {
  82623. return this._circleOfConfusion.focusDistance;
  82624. },
  82625. /**
  82626. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  82627. */
  82628. set: function (value) {
  82629. this._circleOfConfusion.focusDistance = value;
  82630. },
  82631. enumerable: true,
  82632. configurable: true
  82633. });
  82634. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  82635. get: function () {
  82636. return this._circleOfConfusion.lensSize;
  82637. },
  82638. /**
  82639. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  82640. */
  82641. set: function (value) {
  82642. this._circleOfConfusion.lensSize = value;
  82643. },
  82644. enumerable: true,
  82645. configurable: true
  82646. });
  82647. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  82648. /**
  82649. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  82650. */
  82651. set: function (value) {
  82652. this._circleOfConfusion.depthTexture = value;
  82653. },
  82654. enumerable: true,
  82655. configurable: true
  82656. });
  82657. /**
  82658. * Disposes each of the internal effects for a given camera.
  82659. * @param camera The camera to dispose the effect on.
  82660. */
  82661. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  82662. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82663. this._effects[effectIndex].dispose(camera);
  82664. }
  82665. };
  82666. /**
  82667. * @hidden Internal
  82668. */
  82669. DepthOfFieldEffect.prototype._updateEffects = function () {
  82670. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82671. this._effects[effectIndex].updateEffect();
  82672. }
  82673. };
  82674. /**
  82675. * Internal
  82676. * @returns if all the contained post processes are ready.
  82677. * @hidden
  82678. */
  82679. DepthOfFieldEffect.prototype._isReady = function () {
  82680. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82681. if (!this._effects[effectIndex].isReady()) {
  82682. return false;
  82683. }
  82684. }
  82685. return true;
  82686. };
  82687. return DepthOfFieldEffect;
  82688. }(BABYLON.PostProcessRenderEffect));
  82689. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  82690. })(BABYLON || (BABYLON = {}));
  82691. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  82692. var BABYLON;
  82693. (function (BABYLON) {
  82694. /**
  82695. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  82696. */
  82697. var BloomMergePostProcess = /** @class */ (function (_super) {
  82698. __extends(BloomMergePostProcess, _super);
  82699. /**
  82700. * Creates a new instance of @see BloomMergePostProcess
  82701. * @param name The name of the effect.
  82702. * @param originalFromInput Post process which's input will be used for the merge.
  82703. * @param blurred Blurred highlights post process which's output will be used.
  82704. * @param weight Weight of the bloom to be added to the original input.
  82705. * @param options The required width/height ratio to downsize to before computing the render pass.
  82706. * @param camera The camera to apply the render pass to.
  82707. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82708. * @param engine The engine which the post process will be applied. (default: current engine)
  82709. * @param reusable If the post process can be reused on the same frame. (default: false)
  82710. * @param textureType Type of textures used when performing the post process. (default: 0)
  82711. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82712. */
  82713. function BloomMergePostProcess(name, originalFromInput, blurred,
  82714. /** Weight of the bloom to be added to the original input. */
  82715. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82716. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82717. if (blockCompilation === void 0) { blockCompilation = false; }
  82718. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  82719. _this.weight = weight;
  82720. _this.onApplyObservable.add(function (effect) {
  82721. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  82722. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  82723. effect.setFloat("bloomWeight", _this.weight);
  82724. });
  82725. if (!blockCompilation) {
  82726. _this.updateEffect();
  82727. }
  82728. return _this;
  82729. }
  82730. return BloomMergePostProcess;
  82731. }(BABYLON.PostProcess));
  82732. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  82733. })(BABYLON || (BABYLON = {}));
  82734. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  82735. var BABYLON;
  82736. (function (BABYLON) {
  82737. /**
  82738. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  82739. */
  82740. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  82741. __extends(ExtractHighlightsPostProcess, _super);
  82742. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82743. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82744. if (blockCompilation === void 0) { blockCompilation = false; }
  82745. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82746. /**
  82747. * The luminance threshold, pixels below this value will be set to black.
  82748. */
  82749. _this.threshold = 0.9;
  82750. /** @hidden */
  82751. _this._exposure = 1;
  82752. /**
  82753. * Post process which has the input texture to be used when performing highlight extraction
  82754. * @hidden
  82755. */
  82756. _this._inputPostProcess = null;
  82757. _this.onApplyObservable.add(function (effect) {
  82758. if (_this._inputPostProcess) {
  82759. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  82760. }
  82761. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  82762. effect.setFloat('exposure', _this._exposure);
  82763. });
  82764. return _this;
  82765. }
  82766. return ExtractHighlightsPostProcess;
  82767. }(BABYLON.PostProcess));
  82768. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  82769. })(BABYLON || (BABYLON = {}));
  82770. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  82771. var BABYLON;
  82772. (function (BABYLON) {
  82773. /**
  82774. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  82775. */
  82776. var BloomEffect = /** @class */ (function (_super) {
  82777. __extends(BloomEffect, _super);
  82778. /**
  82779. * Creates a new instance of @see BloomEffect
  82780. * @param scene The scene the effect belongs to.
  82781. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  82782. * @param bloomKernel The size of the kernel to be used when applying the blur.
  82783. * @param bloomWeight The the strength of bloom.
  82784. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  82785. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  82786. */
  82787. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  82788. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  82789. if (blockCompilation === void 0) { blockCompilation = false; }
  82790. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  82791. return _this._effects;
  82792. }, true) || this;
  82793. _this.bloomScale = bloomScale;
  82794. /**
  82795. * @hidden Internal
  82796. */
  82797. _this._effects = [];
  82798. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82799. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  82800. _this._blurX.alwaysForcePOT = true;
  82801. _this._blurX.autoClear = false;
  82802. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  82803. _this._blurY.alwaysForcePOT = true;
  82804. _this._blurY.autoClear = false;
  82805. _this.kernel = bloomKernel;
  82806. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  82807. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82808. _this._merge.autoClear = false;
  82809. _this._effects.push(_this._merge);
  82810. return _this;
  82811. }
  82812. Object.defineProperty(BloomEffect.prototype, "threshold", {
  82813. /**
  82814. * The luminance threshold to find bright areas of the image to bloom.
  82815. */
  82816. get: function () {
  82817. return this._downscale.threshold;
  82818. },
  82819. set: function (value) {
  82820. this._downscale.threshold = value;
  82821. },
  82822. enumerable: true,
  82823. configurable: true
  82824. });
  82825. Object.defineProperty(BloomEffect.prototype, "weight", {
  82826. /**
  82827. * The strength of the bloom.
  82828. */
  82829. get: function () {
  82830. return this._merge.weight;
  82831. },
  82832. set: function (value) {
  82833. this._merge.weight = value;
  82834. },
  82835. enumerable: true,
  82836. configurable: true
  82837. });
  82838. Object.defineProperty(BloomEffect.prototype, "kernel", {
  82839. /**
  82840. * Specifies the size of the bloom blur kernel, relative to the final output size
  82841. */
  82842. get: function () {
  82843. return this._blurX.kernel / this.bloomScale;
  82844. },
  82845. set: function (value) {
  82846. this._blurX.kernel = value * this.bloomScale;
  82847. this._blurY.kernel = value * this.bloomScale;
  82848. },
  82849. enumerable: true,
  82850. configurable: true
  82851. });
  82852. /**
  82853. * Disposes each of the internal effects for a given camera.
  82854. * @param camera The camera to dispose the effect on.
  82855. */
  82856. BloomEffect.prototype.disposeEffects = function (camera) {
  82857. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82858. this._effects[effectIndex].dispose(camera);
  82859. }
  82860. };
  82861. /**
  82862. * @hidden Internal
  82863. */
  82864. BloomEffect.prototype._updateEffects = function () {
  82865. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82866. this._effects[effectIndex].updateEffect();
  82867. }
  82868. };
  82869. /**
  82870. * Internal
  82871. * @returns if all the contained post processes are ready.
  82872. * @hidden
  82873. */
  82874. BloomEffect.prototype._isReady = function () {
  82875. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82876. if (!this._effects[effectIndex].isReady()) {
  82877. return false;
  82878. }
  82879. }
  82880. return true;
  82881. };
  82882. return BloomEffect;
  82883. }(BABYLON.PostProcessRenderEffect));
  82884. BABYLON.BloomEffect = BloomEffect;
  82885. })(BABYLON || (BABYLON = {}));
  82886. //# sourceMappingURL=babylon.bloomEffect.js.map
  82887. var BABYLON;
  82888. (function (BABYLON) {
  82889. /**
  82890. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  82891. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  82892. */
  82893. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  82894. __extends(DefaultRenderingPipeline, _super);
  82895. /**
  82896. * @constructor
  82897. * @param {string} name - The rendering pipeline name (default: "")
  82898. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  82899. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  82900. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  82901. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  82902. */
  82903. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  82904. if (name === void 0) { name = ""; }
  82905. if (hdr === void 0) { hdr = true; }
  82906. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  82907. if (automaticBuild === void 0) { automaticBuild = true; }
  82908. var _this = _super.call(this, scene.getEngine(), name) || this;
  82909. _this._camerasToBeAttached = [];
  82910. /**
  82911. * ID of the sharpen post process,
  82912. */
  82913. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  82914. /**
  82915. * ID of the image processing post process;
  82916. */
  82917. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  82918. /**
  82919. * ID of the Fast Approximate Anti-Aliasing post process;
  82920. */
  82921. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  82922. /**
  82923. * ID of the chromatic aberration post process,
  82924. */
  82925. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  82926. /**
  82927. * ID of the grain post process
  82928. */
  82929. _this.GrainPostProcessId = "GrainPostProcessEffect";
  82930. /**
  82931. * Glow post process which adds a glow to emmisive areas of the image
  82932. */
  82933. _this._glowLayer = null;
  82934. /**
  82935. * Animations which can be used to tweak settings over a period of time
  82936. */
  82937. _this.animations = [];
  82938. _this._imageProcessingConfigurationObserver = null;
  82939. // Values
  82940. _this._sharpenEnabled = false;
  82941. _this._bloomEnabled = false;
  82942. _this._depthOfFieldEnabled = false;
  82943. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  82944. _this._fxaaEnabled = false;
  82945. _this._imageProcessingEnabled = true;
  82946. _this._bloomScale = 0.5;
  82947. _this._chromaticAberrationEnabled = false;
  82948. _this._grainEnabled = false;
  82949. _this._buildAllowed = true;
  82950. _this._resizeObserver = null;
  82951. _this._hardwareScaleLevel = 1.0;
  82952. _this._bloomKernel = 64;
  82953. /**
  82954. * Specifies the weight of the bloom in the final rendering
  82955. */
  82956. _this._bloomWeight = 0.15;
  82957. /**
  82958. * Specifies the luma threshold for the area that will be blurred by the bloom
  82959. */
  82960. _this._bloomThreshold = 0.9;
  82961. _this._samples = 1;
  82962. _this._hasCleared = false;
  82963. _this._prevPostProcess = null;
  82964. _this._prevPrevPostProcess = null;
  82965. _this._depthOfFieldSceneObserver = null;
  82966. _this._cameras = cameras || scene.cameras;
  82967. _this._cameras = _this._cameras.slice();
  82968. _this._camerasToBeAttached = _this._cameras.slice();
  82969. _this._buildAllowed = automaticBuild;
  82970. // Initialize
  82971. _this._scene = scene;
  82972. var caps = _this._scene.getEngine().getCaps();
  82973. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  82974. // Misc
  82975. if (_this._hdr) {
  82976. if (caps.textureHalfFloatRender) {
  82977. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82978. }
  82979. else if (caps.textureFloatRender) {
  82980. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82981. }
  82982. }
  82983. else {
  82984. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82985. }
  82986. // Attach
  82987. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82988. var engine = _this._scene.getEngine();
  82989. // Create post processes before hand so they can be modified before enabled.
  82990. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  82991. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  82992. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  82993. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  82994. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  82995. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  82996. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  82997. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  82998. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  82999. _this._resizeObserver = engine.onResizeObservable.add(function () {
  83000. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  83001. _this.bloomKernel = _this.bloomKernel;
  83002. });
  83003. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  83004. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  83005. });
  83006. _this._buildPipeline();
  83007. return _this;
  83008. }
  83009. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  83010. get: function () {
  83011. return this._sharpenEnabled;
  83012. },
  83013. /**
  83014. * Enable or disable the sharpen process from the pipeline
  83015. */
  83016. set: function (enabled) {
  83017. if (this._sharpenEnabled === enabled) {
  83018. return;
  83019. }
  83020. this._sharpenEnabled = enabled;
  83021. this._buildPipeline();
  83022. },
  83023. enumerable: true,
  83024. configurable: true
  83025. });
  83026. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  83027. /**
  83028. * Specifies the size of the bloom blur kernel, relative to the final output size
  83029. */
  83030. get: function () {
  83031. return this._bloomKernel;
  83032. },
  83033. set: function (value) {
  83034. this._bloomKernel = value;
  83035. this.bloom.kernel = value / this._hardwareScaleLevel;
  83036. },
  83037. enumerable: true,
  83038. configurable: true
  83039. });
  83040. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  83041. get: function () {
  83042. return this._bloomWeight;
  83043. },
  83044. /**
  83045. * The strength of the bloom.
  83046. */
  83047. set: function (value) {
  83048. if (this._bloomWeight === value) {
  83049. return;
  83050. }
  83051. this.bloom.weight = value;
  83052. this._bloomWeight = value;
  83053. },
  83054. enumerable: true,
  83055. configurable: true
  83056. });
  83057. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  83058. get: function () {
  83059. return this._bloomThreshold;
  83060. },
  83061. /**
  83062. * The strength of the bloom.
  83063. */
  83064. set: function (value) {
  83065. if (this._bloomThreshold === value) {
  83066. return;
  83067. }
  83068. this.bloom.threshold = value;
  83069. this._bloomThreshold = value;
  83070. },
  83071. enumerable: true,
  83072. configurable: true
  83073. });
  83074. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  83075. get: function () {
  83076. return this._bloomScale;
  83077. },
  83078. /**
  83079. * The scale of the bloom, lower value will provide better performance.
  83080. */
  83081. set: function (value) {
  83082. if (this._bloomScale === value) {
  83083. return;
  83084. }
  83085. this._bloomScale = value;
  83086. // recreate bloom and dispose old as this setting is not dynamic
  83087. this._rebuildBloom();
  83088. this._buildPipeline();
  83089. },
  83090. enumerable: true,
  83091. configurable: true
  83092. });
  83093. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  83094. get: function () {
  83095. return this._bloomEnabled;
  83096. },
  83097. /**
  83098. * Enable or disable the bloom from the pipeline
  83099. */
  83100. set: function (enabled) {
  83101. if (this._bloomEnabled === enabled) {
  83102. return;
  83103. }
  83104. this._bloomEnabled = enabled;
  83105. this._buildPipeline();
  83106. },
  83107. enumerable: true,
  83108. configurable: true
  83109. });
  83110. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  83111. // recreate bloom and dispose old as this setting is not dynamic
  83112. var oldBloom = this.bloom;
  83113. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  83114. this.bloom.threshold = oldBloom.threshold;
  83115. for (var i = 0; i < this._cameras.length; i++) {
  83116. oldBloom.disposeEffects(this._cameras[i]);
  83117. }
  83118. };
  83119. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  83120. /**
  83121. * If the depth of field is enabled.
  83122. */
  83123. get: function () {
  83124. return this._depthOfFieldEnabled;
  83125. },
  83126. set: function (enabled) {
  83127. if (this._depthOfFieldEnabled === enabled) {
  83128. return;
  83129. }
  83130. this._depthOfFieldEnabled = enabled;
  83131. this._buildPipeline();
  83132. },
  83133. enumerable: true,
  83134. configurable: true
  83135. });
  83136. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  83137. /**
  83138. * Blur level of the depth of field effect. (Higher blur will effect performance)
  83139. */
  83140. get: function () {
  83141. return this._depthOfFieldBlurLevel;
  83142. },
  83143. set: function (value) {
  83144. if (this._depthOfFieldBlurLevel === value) {
  83145. return;
  83146. }
  83147. this._depthOfFieldBlurLevel = value;
  83148. // recreate dof and dispose old as this setting is not dynamic
  83149. var oldDof = this.depthOfField;
  83150. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  83151. this.depthOfField.focalLength = oldDof.focalLength;
  83152. this.depthOfField.focusDistance = oldDof.focusDistance;
  83153. this.depthOfField.fStop = oldDof.fStop;
  83154. this.depthOfField.lensSize = oldDof.lensSize;
  83155. for (var i = 0; i < this._cameras.length; i++) {
  83156. oldDof.disposeEffects(this._cameras[i]);
  83157. }
  83158. this._buildPipeline();
  83159. },
  83160. enumerable: true,
  83161. configurable: true
  83162. });
  83163. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  83164. get: function () {
  83165. return this._fxaaEnabled;
  83166. },
  83167. /**
  83168. * If the anti aliasing is enabled.
  83169. */
  83170. set: function (enabled) {
  83171. if (this._fxaaEnabled === enabled) {
  83172. return;
  83173. }
  83174. this._fxaaEnabled = enabled;
  83175. this._buildPipeline();
  83176. },
  83177. enumerable: true,
  83178. configurable: true
  83179. });
  83180. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  83181. get: function () {
  83182. return this._samples;
  83183. },
  83184. /**
  83185. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  83186. */
  83187. set: function (sampleCount) {
  83188. if (this._samples === sampleCount) {
  83189. return;
  83190. }
  83191. this._samples = sampleCount;
  83192. this._buildPipeline();
  83193. },
  83194. enumerable: true,
  83195. configurable: true
  83196. });
  83197. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  83198. get: function () {
  83199. return this._imageProcessingEnabled;
  83200. },
  83201. /**
  83202. * If image processing is enabled.
  83203. */
  83204. set: function (enabled) {
  83205. if (this._imageProcessingEnabled === enabled) {
  83206. return;
  83207. }
  83208. this._imageProcessingEnabled = enabled;
  83209. this._buildPipeline();
  83210. },
  83211. enumerable: true,
  83212. configurable: true
  83213. });
  83214. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  83215. get: function () {
  83216. return this._glowLayer == null;
  83217. },
  83218. /**
  83219. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  83220. */
  83221. set: function (enabled) {
  83222. if (enabled && !this._glowLayer) {
  83223. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  83224. }
  83225. else if (!enabled && this._glowLayer) {
  83226. this._glowLayer.dispose();
  83227. this._glowLayer = null;
  83228. }
  83229. },
  83230. enumerable: true,
  83231. configurable: true
  83232. });
  83233. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  83234. get: function () {
  83235. return this._chromaticAberrationEnabled;
  83236. },
  83237. /**
  83238. * Enable or disable the chromaticAberration process from the pipeline
  83239. */
  83240. set: function (enabled) {
  83241. if (this._chromaticAberrationEnabled === enabled) {
  83242. return;
  83243. }
  83244. this._chromaticAberrationEnabled = enabled;
  83245. this._buildPipeline();
  83246. },
  83247. enumerable: true,
  83248. configurable: true
  83249. });
  83250. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  83251. get: function () {
  83252. return this._grainEnabled;
  83253. },
  83254. /**
  83255. * Enable or disable the grain process from the pipeline
  83256. */
  83257. set: function (enabled) {
  83258. if (this._grainEnabled === enabled) {
  83259. return;
  83260. }
  83261. this._grainEnabled = enabled;
  83262. this._buildPipeline();
  83263. },
  83264. enumerable: true,
  83265. configurable: true
  83266. });
  83267. /**
  83268. * Force the compilation of the entire pipeline.
  83269. */
  83270. DefaultRenderingPipeline.prototype.prepare = function () {
  83271. var previousState = this._buildAllowed;
  83272. this._buildAllowed = true;
  83273. this._buildPipeline();
  83274. this._buildAllowed = previousState;
  83275. };
  83276. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  83277. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  83278. if (this._hasCleared) {
  83279. postProcess.autoClear = false;
  83280. }
  83281. else {
  83282. postProcess.autoClear = true;
  83283. this._scene.autoClear = false;
  83284. this._hasCleared = true;
  83285. }
  83286. if (!skipTextureSharing) {
  83287. if (this._prevPrevPostProcess) {
  83288. postProcess.shareOutputWith(this._prevPrevPostProcess);
  83289. }
  83290. else {
  83291. postProcess.useOwnOutput();
  83292. }
  83293. if (this._prevPostProcess) {
  83294. this._prevPrevPostProcess = this._prevPostProcess;
  83295. }
  83296. this._prevPostProcess = postProcess;
  83297. }
  83298. };
  83299. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  83300. var _this = this;
  83301. if (!this._buildAllowed) {
  83302. return;
  83303. }
  83304. this._scene.autoClear = true;
  83305. var engine = this._scene.getEngine();
  83306. this._disposePostProcesses();
  83307. if (this._cameras !== null) {
  83308. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83309. // get back cameras to be used to reattach pipeline
  83310. this._cameras = this._camerasToBeAttached.slice();
  83311. }
  83312. this._reset();
  83313. this._prevPostProcess = null;
  83314. this._prevPrevPostProcess = null;
  83315. this._hasCleared = false;
  83316. if (this.depthOfFieldEnabled) {
  83317. // Multi camera suport
  83318. if (this._cameras.length > 1) {
  83319. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  83320. var camera = _a[_i];
  83321. var depthRenderer = this._scene.enableDepthRenderer(camera);
  83322. depthRenderer.useOnlyInActiveCamera = true;
  83323. }
  83324. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  83325. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  83326. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  83327. }
  83328. });
  83329. }
  83330. else {
  83331. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83332. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  83333. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  83334. }
  83335. if (!this.depthOfField._isReady()) {
  83336. this.depthOfField._updateEffects();
  83337. }
  83338. this.addEffect(this.depthOfField);
  83339. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  83340. }
  83341. else {
  83342. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83343. }
  83344. if (this.bloomEnabled) {
  83345. if (!this.bloom._isReady()) {
  83346. this.bloom._updateEffects();
  83347. }
  83348. this.addEffect(this.bloom);
  83349. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  83350. }
  83351. if (this._imageProcessingEnabled) {
  83352. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  83353. if (this._hdr) {
  83354. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  83355. this._setAutoClearAndTextureSharing(this.imageProcessing);
  83356. }
  83357. else {
  83358. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  83359. }
  83360. }
  83361. if (this.sharpenEnabled) {
  83362. if (!this.sharpen.isReady()) {
  83363. this.sharpen.updateEffect();
  83364. }
  83365. this.addEffect(this._sharpenEffect);
  83366. this._setAutoClearAndTextureSharing(this.sharpen);
  83367. }
  83368. if (this.grainEnabled) {
  83369. if (!this.grain.isReady()) {
  83370. this.grain.updateEffect();
  83371. }
  83372. this.addEffect(this._grainEffect);
  83373. this._setAutoClearAndTextureSharing(this.grain);
  83374. }
  83375. if (this.chromaticAberrationEnabled) {
  83376. if (!this.chromaticAberration.isReady()) {
  83377. this.chromaticAberration.updateEffect();
  83378. }
  83379. this.addEffect(this._chromaticAberrationEffect);
  83380. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  83381. }
  83382. if (this.fxaaEnabled) {
  83383. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  83384. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  83385. this._setAutoClearAndTextureSharing(this.fxaa, true);
  83386. }
  83387. if (this._cameras !== null) {
  83388. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  83389. }
  83390. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  83391. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  83392. }
  83393. };
  83394. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  83395. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  83396. for (var i = 0; i < this._cameras.length; i++) {
  83397. var camera = this._cameras[i];
  83398. if (this.imageProcessing) {
  83399. this.imageProcessing.dispose(camera);
  83400. }
  83401. if (this.fxaa) {
  83402. this.fxaa.dispose(camera);
  83403. }
  83404. // These are created in the constructor and should not be disposed on every pipeline change
  83405. if (disposeNonRecreated) {
  83406. if (this.sharpen) {
  83407. this.sharpen.dispose(camera);
  83408. }
  83409. if (this.depthOfField) {
  83410. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83411. this.depthOfField.disposeEffects(camera);
  83412. }
  83413. if (this.bloom) {
  83414. this.bloom.disposeEffects(camera);
  83415. }
  83416. if (this.chromaticAberration) {
  83417. this.chromaticAberration.dispose(camera);
  83418. }
  83419. if (this.grain) {
  83420. this.grain.dispose(camera);
  83421. }
  83422. if (this._glowLayer) {
  83423. this._glowLayer.dispose();
  83424. }
  83425. }
  83426. }
  83427. this.imageProcessing = null;
  83428. this.fxaa = null;
  83429. if (disposeNonRecreated) {
  83430. this.sharpen = null;
  83431. this._sharpenEffect = null;
  83432. this.depthOfField = null;
  83433. this.bloom = null;
  83434. this.chromaticAberration = null;
  83435. this._chromaticAberrationEffect = null;
  83436. this.grain = null;
  83437. this._grainEffect = null;
  83438. this._glowLayer = null;
  83439. }
  83440. };
  83441. /**
  83442. * Adds a camera to the pipeline
  83443. * @param camera the camera to be added
  83444. */
  83445. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  83446. this._camerasToBeAttached.push(camera);
  83447. this._buildPipeline();
  83448. };
  83449. /**
  83450. * Removes a camera from the pipeline
  83451. * @param camera the camera to remove
  83452. */
  83453. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  83454. var index = this._camerasToBeAttached.indexOf(camera);
  83455. this._camerasToBeAttached.splice(index, 1);
  83456. this._buildPipeline();
  83457. };
  83458. /**
  83459. * Dispose of the pipeline and stop all post processes
  83460. */
  83461. DefaultRenderingPipeline.prototype.dispose = function () {
  83462. this._disposePostProcesses(true);
  83463. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83464. this._scene.autoClear = true;
  83465. if (this._resizeObserver) {
  83466. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  83467. this._resizeObserver = null;
  83468. }
  83469. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  83470. _super.prototype.dispose.call(this);
  83471. };
  83472. /**
  83473. * Serialize the rendering pipeline (Used when exporting)
  83474. * @returns the serialized object
  83475. */
  83476. DefaultRenderingPipeline.prototype.serialize = function () {
  83477. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83478. serializationObject.customType = "DefaultRenderingPipeline";
  83479. return serializationObject;
  83480. };
  83481. /**
  83482. * Parse the serialized pipeline
  83483. * @param source Source pipeline.
  83484. * @param scene The scene to load the pipeline to.
  83485. * @param rootUrl The URL of the serialized pipeline.
  83486. * @returns An instantiated pipeline from the serialized object.
  83487. */
  83488. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  83489. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  83490. };
  83491. __decorate([
  83492. BABYLON.serialize()
  83493. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  83494. __decorate([
  83495. BABYLON.serialize()
  83496. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  83497. __decorate([
  83498. BABYLON.serialize()
  83499. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  83500. __decorate([
  83501. BABYLON.serialize()
  83502. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  83503. __decorate([
  83504. BABYLON.serialize()
  83505. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  83506. __decorate([
  83507. BABYLON.serialize()
  83508. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  83509. __decorate([
  83510. BABYLON.serialize()
  83511. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  83512. __decorate([
  83513. BABYLON.serialize()
  83514. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  83515. __decorate([
  83516. BABYLON.serialize()
  83517. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  83518. __decorate([
  83519. BABYLON.serialize()
  83520. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  83521. __decorate([
  83522. BABYLON.serialize()
  83523. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  83524. __decorate([
  83525. BABYLON.serialize()
  83526. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  83527. __decorate([
  83528. BABYLON.serialize()
  83529. ], DefaultRenderingPipeline.prototype, "samples", null);
  83530. __decorate([
  83531. BABYLON.serialize()
  83532. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  83533. __decorate([
  83534. BABYLON.serialize()
  83535. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  83536. __decorate([
  83537. BABYLON.serialize()
  83538. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  83539. __decorate([
  83540. BABYLON.serialize()
  83541. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  83542. return DefaultRenderingPipeline;
  83543. }(BABYLON.PostProcessRenderPipeline));
  83544. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  83545. })(BABYLON || (BABYLON = {}));
  83546. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  83547. var BABYLON;
  83548. (function (BABYLON) {
  83549. /**
  83550. * @hidden
  83551. */
  83552. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  83553. __extends(ImageProcessingConfigurationDefines, _super);
  83554. function ImageProcessingConfigurationDefines() {
  83555. var _this = _super.call(this) || this;
  83556. _this.IMAGEPROCESSING = false;
  83557. _this.VIGNETTE = false;
  83558. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83559. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83560. _this.TONEMAPPING = false;
  83561. _this.TONEMAPPING_ACES = false;
  83562. _this.CONTRAST = false;
  83563. _this.COLORCURVES = false;
  83564. _this.COLORGRADING = false;
  83565. _this.COLORGRADING3D = false;
  83566. _this.SAMPLER3DGREENDEPTH = false;
  83567. _this.SAMPLER3DBGRMAP = false;
  83568. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83569. _this.EXPOSURE = false;
  83570. _this.rebuild();
  83571. return _this;
  83572. }
  83573. return ImageProcessingConfigurationDefines;
  83574. }(BABYLON.MaterialDefines));
  83575. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  83576. /**
  83577. * This groups together the common properties used for image processing either in direct forward pass
  83578. * or through post processing effect depending on the use of the image processing pipeline in your scene
  83579. * or not.
  83580. */
  83581. var ImageProcessingConfiguration = /** @class */ (function () {
  83582. function ImageProcessingConfiguration() {
  83583. /**
  83584. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  83585. */
  83586. this.colorCurves = new BABYLON.ColorCurves();
  83587. this._colorCurvesEnabled = false;
  83588. this._colorGradingEnabled = false;
  83589. this._colorGradingWithGreenDepth = true;
  83590. this._colorGradingBGR = true;
  83591. /** @hidden */
  83592. this._exposure = 1.0;
  83593. this._toneMappingEnabled = false;
  83594. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  83595. this._contrast = 1.0;
  83596. /**
  83597. * Vignette stretch size.
  83598. */
  83599. this.vignetteStretch = 0;
  83600. /**
  83601. * Vignette centre X Offset.
  83602. */
  83603. this.vignetteCentreX = 0;
  83604. /**
  83605. * Vignette centre Y Offset.
  83606. */
  83607. this.vignetteCentreY = 0;
  83608. /**
  83609. * Vignette weight or intensity of the vignette effect.
  83610. */
  83611. this.vignetteWeight = 1.5;
  83612. /**
  83613. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83614. * if vignetteEnabled is set to true.
  83615. */
  83616. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83617. /**
  83618. * Camera field of view used by the Vignette effect.
  83619. */
  83620. this.vignetteCameraFov = 0.5;
  83621. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  83622. this._vignetteEnabled = false;
  83623. this._applyByPostProcess = false;
  83624. this._isEnabled = true;
  83625. /**
  83626. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  83627. */
  83628. this.onUpdateParameters = new BABYLON.Observable();
  83629. }
  83630. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  83631. /**
  83632. * Gets wether the color curves effect is enabled.
  83633. */
  83634. get: function () {
  83635. return this._colorCurvesEnabled;
  83636. },
  83637. /**
  83638. * Sets wether the color curves effect is enabled.
  83639. */
  83640. set: function (value) {
  83641. if (this._colorCurvesEnabled === value) {
  83642. return;
  83643. }
  83644. this._colorCurvesEnabled = value;
  83645. this._updateParameters();
  83646. },
  83647. enumerable: true,
  83648. configurable: true
  83649. });
  83650. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  83651. /**
  83652. * Gets wether the color grading effect is enabled.
  83653. */
  83654. get: function () {
  83655. return this._colorGradingEnabled;
  83656. },
  83657. /**
  83658. * Sets wether the color grading effect is enabled.
  83659. */
  83660. set: function (value) {
  83661. if (this._colorGradingEnabled === value) {
  83662. return;
  83663. }
  83664. this._colorGradingEnabled = value;
  83665. this._updateParameters();
  83666. },
  83667. enumerable: true,
  83668. configurable: true
  83669. });
  83670. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  83671. /**
  83672. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  83673. */
  83674. get: function () {
  83675. return this._colorGradingWithGreenDepth;
  83676. },
  83677. /**
  83678. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  83679. */
  83680. set: function (value) {
  83681. if (this._colorGradingWithGreenDepth === value) {
  83682. return;
  83683. }
  83684. this._colorGradingWithGreenDepth = value;
  83685. this._updateParameters();
  83686. },
  83687. enumerable: true,
  83688. configurable: true
  83689. });
  83690. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  83691. /**
  83692. * Gets wether the color grading texture contains BGR values.
  83693. */
  83694. get: function () {
  83695. return this._colorGradingBGR;
  83696. },
  83697. /**
  83698. * Sets wether the color grading texture contains BGR values.
  83699. */
  83700. set: function (value) {
  83701. if (this._colorGradingBGR === value) {
  83702. return;
  83703. }
  83704. this._colorGradingBGR = value;
  83705. this._updateParameters();
  83706. },
  83707. enumerable: true,
  83708. configurable: true
  83709. });
  83710. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  83711. /**
  83712. * Gets the Exposure used in the effect.
  83713. */
  83714. get: function () {
  83715. return this._exposure;
  83716. },
  83717. /**
  83718. * Sets the Exposure used in the effect.
  83719. */
  83720. set: function (value) {
  83721. if (this._exposure === value) {
  83722. return;
  83723. }
  83724. this._exposure = value;
  83725. this._updateParameters();
  83726. },
  83727. enumerable: true,
  83728. configurable: true
  83729. });
  83730. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  83731. /**
  83732. * Gets wether the tone mapping effect is enabled.
  83733. */
  83734. get: function () {
  83735. return this._toneMappingEnabled;
  83736. },
  83737. /**
  83738. * Sets wether the tone mapping effect is enabled.
  83739. */
  83740. set: function (value) {
  83741. if (this._toneMappingEnabled === value) {
  83742. return;
  83743. }
  83744. this._toneMappingEnabled = value;
  83745. this._updateParameters();
  83746. },
  83747. enumerable: true,
  83748. configurable: true
  83749. });
  83750. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  83751. /**
  83752. * Gets the type of tone mapping effect.
  83753. */
  83754. get: function () {
  83755. return this._toneMappingType;
  83756. },
  83757. /**
  83758. * Sets the type of tone mapping effect used in BabylonJS.
  83759. */
  83760. set: function (value) {
  83761. if (this._toneMappingType === value) {
  83762. return;
  83763. }
  83764. this._toneMappingType = value;
  83765. this._updateParameters();
  83766. },
  83767. enumerable: true,
  83768. configurable: true
  83769. });
  83770. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  83771. /**
  83772. * Gets the contrast used in the effect.
  83773. */
  83774. get: function () {
  83775. return this._contrast;
  83776. },
  83777. /**
  83778. * Sets the contrast used in the effect.
  83779. */
  83780. set: function (value) {
  83781. if (this._contrast === value) {
  83782. return;
  83783. }
  83784. this._contrast = value;
  83785. this._updateParameters();
  83786. },
  83787. enumerable: true,
  83788. configurable: true
  83789. });
  83790. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  83791. /**
  83792. * Gets the vignette blend mode allowing different kind of effect.
  83793. */
  83794. get: function () {
  83795. return this._vignetteBlendMode;
  83796. },
  83797. /**
  83798. * Sets the vignette blend mode allowing different kind of effect.
  83799. */
  83800. set: function (value) {
  83801. if (this._vignetteBlendMode === value) {
  83802. return;
  83803. }
  83804. this._vignetteBlendMode = value;
  83805. this._updateParameters();
  83806. },
  83807. enumerable: true,
  83808. configurable: true
  83809. });
  83810. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  83811. /**
  83812. * Gets wether the vignette effect is enabled.
  83813. */
  83814. get: function () {
  83815. return this._vignetteEnabled;
  83816. },
  83817. /**
  83818. * Sets wether the vignette effect is enabled.
  83819. */
  83820. set: function (value) {
  83821. if (this._vignetteEnabled === value) {
  83822. return;
  83823. }
  83824. this._vignetteEnabled = value;
  83825. this._updateParameters();
  83826. },
  83827. enumerable: true,
  83828. configurable: true
  83829. });
  83830. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  83831. /**
  83832. * Gets wether the image processing is applied through a post process or not.
  83833. */
  83834. get: function () {
  83835. return this._applyByPostProcess;
  83836. },
  83837. /**
  83838. * Sets wether the image processing is applied through a post process or not.
  83839. */
  83840. set: function (value) {
  83841. if (this._applyByPostProcess === value) {
  83842. return;
  83843. }
  83844. this._applyByPostProcess = value;
  83845. this._updateParameters();
  83846. },
  83847. enumerable: true,
  83848. configurable: true
  83849. });
  83850. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  83851. /**
  83852. * Gets wether the image processing is enabled or not.
  83853. */
  83854. get: function () {
  83855. return this._isEnabled;
  83856. },
  83857. /**
  83858. * Sets wether the image processing is enabled or not.
  83859. */
  83860. set: function (value) {
  83861. if (this._isEnabled === value) {
  83862. return;
  83863. }
  83864. this._isEnabled = value;
  83865. this._updateParameters();
  83866. },
  83867. enumerable: true,
  83868. configurable: true
  83869. });
  83870. /**
  83871. * Method called each time the image processing information changes requires to recompile the effect.
  83872. */
  83873. ImageProcessingConfiguration.prototype._updateParameters = function () {
  83874. this.onUpdateParameters.notifyObservers(this);
  83875. };
  83876. ImageProcessingConfiguration.prototype.getClassName = function () {
  83877. return "ImageProcessingConfiguration";
  83878. };
  83879. /**
  83880. * Prepare the list of uniforms associated with the Image Processing effects.
  83881. * @param uniformsList The list of uniforms used in the effect
  83882. * @param defines the list of defines currently in use
  83883. */
  83884. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  83885. if (defines.EXPOSURE) {
  83886. uniforms.push("exposureLinear");
  83887. }
  83888. if (defines.CONTRAST) {
  83889. uniforms.push("contrast");
  83890. }
  83891. if (defines.COLORGRADING) {
  83892. uniforms.push("colorTransformSettings");
  83893. }
  83894. if (defines.VIGNETTE) {
  83895. uniforms.push("vInverseScreenSize");
  83896. uniforms.push("vignetteSettings1");
  83897. uniforms.push("vignetteSettings2");
  83898. }
  83899. if (defines.COLORCURVES) {
  83900. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  83901. }
  83902. };
  83903. /**
  83904. * Prepare the list of samplers associated with the Image Processing effects.
  83905. * @param uniformsList The list of uniforms used in the effect
  83906. * @param defines the list of defines currently in use
  83907. */
  83908. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  83909. if (defines.COLORGRADING) {
  83910. samplersList.push("txColorTransform");
  83911. }
  83912. };
  83913. /**
  83914. * Prepare the list of defines associated to the shader.
  83915. * @param defines the list of defines to complete
  83916. */
  83917. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  83918. if (forPostProcess === void 0) { forPostProcess = false; }
  83919. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  83920. defines.VIGNETTE = false;
  83921. defines.TONEMAPPING = false;
  83922. defines.TONEMAPPING_ACES = false;
  83923. defines.CONTRAST = false;
  83924. defines.EXPOSURE = false;
  83925. defines.COLORCURVES = false;
  83926. defines.COLORGRADING = false;
  83927. defines.COLORGRADING3D = false;
  83928. defines.IMAGEPROCESSING = false;
  83929. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  83930. return;
  83931. }
  83932. defines.VIGNETTE = this.vignetteEnabled;
  83933. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  83934. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  83935. defines.TONEMAPPING = this.toneMappingEnabled;
  83936. switch (this._toneMappingType) {
  83937. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  83938. defines.TONEMAPPING_ACES = true;
  83939. break;
  83940. }
  83941. defines.CONTRAST = (this.contrast !== 1.0);
  83942. defines.EXPOSURE = (this.exposure !== 1.0);
  83943. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  83944. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  83945. if (defines.COLORGRADING) {
  83946. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  83947. }
  83948. else {
  83949. defines.COLORGRADING3D = false;
  83950. }
  83951. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  83952. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  83953. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  83954. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  83955. };
  83956. /**
  83957. * Returns true if all the image processing information are ready.
  83958. */
  83959. ImageProcessingConfiguration.prototype.isReady = function () {
  83960. // Color Grading texure can not be none blocking.
  83961. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  83962. };
  83963. /**
  83964. * Binds the image processing to the shader.
  83965. * @param effect The effect to bind to
  83966. */
  83967. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  83968. if (aspectRatio === void 0) { aspectRatio = 1; }
  83969. // Color Curves
  83970. if (this._colorCurvesEnabled && this.colorCurves) {
  83971. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  83972. }
  83973. // Vignette
  83974. if (this._vignetteEnabled) {
  83975. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  83976. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  83977. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  83978. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  83979. var vignetteScaleX = vignetteScaleY * aspectRatio;
  83980. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  83981. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  83982. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  83983. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  83984. var vignettePower = -2.0 * this.vignetteWeight;
  83985. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  83986. }
  83987. // Exposure
  83988. effect.setFloat("exposureLinear", this.exposure);
  83989. // Contrast
  83990. effect.setFloat("contrast", this.contrast);
  83991. // Color transform settings
  83992. if (this.colorGradingTexture) {
  83993. effect.setTexture("txColorTransform", this.colorGradingTexture);
  83994. var textureSize = this.colorGradingTexture.getSize().height;
  83995. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  83996. 0.5 / textureSize, // textureOffset
  83997. textureSize, // textureSize
  83998. this.colorGradingTexture.level // weight
  83999. );
  84000. }
  84001. };
  84002. /**
  84003. * Clones the current image processing instance.
  84004. * @return The cloned image processing
  84005. */
  84006. ImageProcessingConfiguration.prototype.clone = function () {
  84007. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  84008. };
  84009. /**
  84010. * Serializes the current image processing instance to a json representation.
  84011. * @return a JSON representation
  84012. */
  84013. ImageProcessingConfiguration.prototype.serialize = function () {
  84014. return BABYLON.SerializationHelper.Serialize(this);
  84015. };
  84016. /**
  84017. * Parses the image processing from a json representation.
  84018. * @param source the JSON source to parse
  84019. * @return The parsed image processing
  84020. */
  84021. ImageProcessingConfiguration.Parse = function (source) {
  84022. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  84023. };
  84024. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  84025. /**
  84026. * Used to apply the vignette as a mix with the pixel color.
  84027. */
  84028. get: function () {
  84029. return this._VIGNETTEMODE_MULTIPLY;
  84030. },
  84031. enumerable: true,
  84032. configurable: true
  84033. });
  84034. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  84035. /**
  84036. * Used to apply the vignette as a replacement of the pixel color.
  84037. */
  84038. get: function () {
  84039. return this._VIGNETTEMODE_OPAQUE;
  84040. },
  84041. enumerable: true,
  84042. configurable: true
  84043. });
  84044. /**
  84045. * Default tone mapping applied in BabylonJS.
  84046. */
  84047. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  84048. /**
  84049. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  84050. * to other engines rendering to increase portability.
  84051. */
  84052. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  84053. // Static constants associated to the image processing.
  84054. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  84055. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  84056. __decorate([
  84057. BABYLON.serializeAsColorCurves()
  84058. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  84059. __decorate([
  84060. BABYLON.serialize()
  84061. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  84062. __decorate([
  84063. BABYLON.serializeAsTexture()
  84064. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  84065. __decorate([
  84066. BABYLON.serialize()
  84067. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  84068. __decorate([
  84069. BABYLON.serialize()
  84070. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  84071. __decorate([
  84072. BABYLON.serialize()
  84073. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  84074. __decorate([
  84075. BABYLON.serialize()
  84076. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  84077. __decorate([
  84078. BABYLON.serialize()
  84079. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  84080. __decorate([
  84081. BABYLON.serialize()
  84082. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  84083. __decorate([
  84084. BABYLON.serialize()
  84085. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  84086. __decorate([
  84087. BABYLON.serialize()
  84088. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  84089. __decorate([
  84090. BABYLON.serialize()
  84091. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  84092. __decorate([
  84093. BABYLON.serialize()
  84094. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  84095. __decorate([
  84096. BABYLON.serialize()
  84097. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  84098. __decorate([
  84099. BABYLON.serializeAsColor4()
  84100. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  84101. __decorate([
  84102. BABYLON.serialize()
  84103. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  84104. __decorate([
  84105. BABYLON.serialize()
  84106. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  84107. __decorate([
  84108. BABYLON.serialize()
  84109. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  84110. __decorate([
  84111. BABYLON.serialize()
  84112. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  84113. __decorate([
  84114. BABYLON.serialize()
  84115. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  84116. return ImageProcessingConfiguration;
  84117. }());
  84118. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  84119. })(BABYLON || (BABYLON = {}));
  84120. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  84121. var BABYLON;
  84122. (function (BABYLON) {
  84123. /**
  84124. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  84125. * It can help converting any input color in a desired output one. This can then be used to create effects
  84126. * from sepia, black and white to sixties or futuristic rendering...
  84127. *
  84128. * The only supported format is currently 3dl.
  84129. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  84130. */
  84131. var ColorGradingTexture = /** @class */ (function (_super) {
  84132. __extends(ColorGradingTexture, _super);
  84133. /**
  84134. * Instantiates a ColorGradingTexture from the following parameters.
  84135. *
  84136. * @param url The location of the color gradind data (currently only supporting 3dl)
  84137. * @param scene The scene the texture will be used in
  84138. */
  84139. function ColorGradingTexture(url, scene) {
  84140. var _this = _super.call(this, scene) || this;
  84141. if (!url) {
  84142. return _this;
  84143. }
  84144. _this._engine = scene.getEngine();
  84145. _this._textureMatrix = BABYLON.Matrix.Identity();
  84146. _this.name = url;
  84147. _this.url = url;
  84148. _this.hasAlpha = false;
  84149. _this.isCube = false;
  84150. _this.is3D = _this._engine.webGLVersion > 1;
  84151. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84152. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84153. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84154. _this.anisotropicFilteringLevel = 1;
  84155. _this._texture = _this._getFromCache(url, true);
  84156. if (!_this._texture) {
  84157. if (!scene.useDelayedTextureLoading) {
  84158. _this.loadTexture();
  84159. }
  84160. else {
  84161. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  84162. }
  84163. }
  84164. return _this;
  84165. }
  84166. /**
  84167. * Returns the texture matrix used in most of the material.
  84168. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  84169. */
  84170. ColorGradingTexture.prototype.getTextureMatrix = function () {
  84171. return this._textureMatrix;
  84172. };
  84173. /**
  84174. * Occurs when the file being loaded is a .3dl LUT file.
  84175. */
  84176. ColorGradingTexture.prototype.load3dlTexture = function () {
  84177. var engine = this._engine;
  84178. var texture;
  84179. if (engine.webGLVersion === 1) {
  84180. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84181. }
  84182. else {
  84183. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84184. }
  84185. this._texture = texture;
  84186. var callback = function (text) {
  84187. if (typeof text !== "string") {
  84188. return;
  84189. }
  84190. var data = null;
  84191. var tempData = null;
  84192. var line;
  84193. var lines = text.split('\n');
  84194. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  84195. var maxColor = 0;
  84196. for (var i = 0; i < lines.length; i++) {
  84197. line = lines[i];
  84198. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  84199. continue;
  84200. if (line.indexOf('#') === 0)
  84201. continue;
  84202. var words = line.split(" ");
  84203. if (size === 0) {
  84204. // Number of space + one
  84205. size = words.length;
  84206. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  84207. tempData = new Float32Array(size * size * size * 4);
  84208. continue;
  84209. }
  84210. if (size != 0) {
  84211. var r = Math.max(parseInt(words[0]), 0);
  84212. var g = Math.max(parseInt(words[1]), 0);
  84213. var b = Math.max(parseInt(words[2]), 0);
  84214. maxColor = Math.max(r, maxColor);
  84215. maxColor = Math.max(g, maxColor);
  84216. maxColor = Math.max(b, maxColor);
  84217. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  84218. if (tempData) {
  84219. tempData[pixelStorageIndex + 0] = r;
  84220. tempData[pixelStorageIndex + 1] = g;
  84221. tempData[pixelStorageIndex + 2] = b;
  84222. }
  84223. pixelIndexSlice++;
  84224. if (pixelIndexSlice % size == 0) {
  84225. pixelIndexH++;
  84226. pixelIndexSlice = 0;
  84227. if (pixelIndexH % size == 0) {
  84228. pixelIndexW++;
  84229. pixelIndexH = 0;
  84230. }
  84231. }
  84232. }
  84233. }
  84234. if (tempData && data) {
  84235. for (var i = 0; i < tempData.length; i++) {
  84236. if (i > 0 && (i + 1) % 4 === 0) {
  84237. data[i] = 255;
  84238. }
  84239. else {
  84240. var value = tempData[i];
  84241. data[i] = (value / maxColor * 255);
  84242. }
  84243. }
  84244. }
  84245. if (texture.is3D) {
  84246. texture.updateSize(size, size, size);
  84247. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  84248. }
  84249. else {
  84250. texture.updateSize(size * size, size);
  84251. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  84252. }
  84253. };
  84254. var scene = this.getScene();
  84255. if (scene) {
  84256. scene._loadFile(this.url, callback);
  84257. }
  84258. else {
  84259. this._engine._loadFile(this.url, callback);
  84260. }
  84261. return this._texture;
  84262. };
  84263. /**
  84264. * Starts the loading process of the texture.
  84265. */
  84266. ColorGradingTexture.prototype.loadTexture = function () {
  84267. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  84268. this.load3dlTexture();
  84269. }
  84270. };
  84271. /**
  84272. * Clones the color gradind texture.
  84273. */
  84274. ColorGradingTexture.prototype.clone = function () {
  84275. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  84276. // Base texture
  84277. newTexture.level = this.level;
  84278. return newTexture;
  84279. };
  84280. /**
  84281. * Called during delayed load for textures.
  84282. */
  84283. ColorGradingTexture.prototype.delayLoad = function () {
  84284. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84285. return;
  84286. }
  84287. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84288. this._texture = this._getFromCache(this.url, true);
  84289. if (!this._texture) {
  84290. this.loadTexture();
  84291. }
  84292. };
  84293. /**
  84294. * Parses a color grading texture serialized by Babylon.
  84295. * @param parsedTexture The texture information being parsedTexture
  84296. * @param scene The scene to load the texture in
  84297. * @param rootUrl The root url of the data assets to load
  84298. * @return A color gradind texture
  84299. */
  84300. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84301. var texture = null;
  84302. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84303. texture = new ColorGradingTexture(parsedTexture.name, scene);
  84304. texture.name = parsedTexture.name;
  84305. texture.level = parsedTexture.level;
  84306. }
  84307. return texture;
  84308. };
  84309. /**
  84310. * Serializes the LUT texture to json format.
  84311. */
  84312. ColorGradingTexture.prototype.serialize = function () {
  84313. if (!this.name) {
  84314. return null;
  84315. }
  84316. var serializationObject = {};
  84317. serializationObject.name = this.name;
  84318. serializationObject.level = this.level;
  84319. serializationObject.customType = "BABYLON.ColorGradingTexture";
  84320. return serializationObject;
  84321. };
  84322. /**
  84323. * Empty line regex stored for GC.
  84324. */
  84325. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  84326. return ColorGradingTexture;
  84327. }(BABYLON.BaseTexture));
  84328. BABYLON.ColorGradingTexture = ColorGradingTexture;
  84329. })(BABYLON || (BABYLON = {}));
  84330. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  84331. var BABYLON;
  84332. (function (BABYLON) {
  84333. /**
  84334. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84335. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84336. * 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;
  84337. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84338. */
  84339. var ColorCurves = /** @class */ (function () {
  84340. function ColorCurves() {
  84341. this._dirty = true;
  84342. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  84343. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  84344. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  84345. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  84346. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  84347. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  84348. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  84349. this._globalHue = 30;
  84350. this._globalDensity = 0;
  84351. this._globalSaturation = 0;
  84352. this._globalExposure = 0;
  84353. this._highlightsHue = 30;
  84354. this._highlightsDensity = 0;
  84355. this._highlightsSaturation = 0;
  84356. this._highlightsExposure = 0;
  84357. this._midtonesHue = 30;
  84358. this._midtonesDensity = 0;
  84359. this._midtonesSaturation = 0;
  84360. this._midtonesExposure = 0;
  84361. this._shadowsHue = 30;
  84362. this._shadowsDensity = 0;
  84363. this._shadowsSaturation = 0;
  84364. this._shadowsExposure = 0;
  84365. }
  84366. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  84367. /**
  84368. * Gets the global Hue value.
  84369. * 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).
  84370. */
  84371. get: function () {
  84372. return this._globalHue;
  84373. },
  84374. /**
  84375. * Sets the global Hue value.
  84376. * 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).
  84377. */
  84378. set: function (value) {
  84379. this._globalHue = value;
  84380. this._dirty = true;
  84381. },
  84382. enumerable: true,
  84383. configurable: true
  84384. });
  84385. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  84386. /**
  84387. * Gets the global Density value.
  84388. * 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.
  84389. * Values less than zero provide a filter of opposite hue.
  84390. */
  84391. get: function () {
  84392. return this._globalDensity;
  84393. },
  84394. /**
  84395. * Sets the global Density value.
  84396. * 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.
  84397. * Values less than zero provide a filter of opposite hue.
  84398. */
  84399. set: function (value) {
  84400. this._globalDensity = value;
  84401. this._dirty = true;
  84402. },
  84403. enumerable: true,
  84404. configurable: true
  84405. });
  84406. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  84407. /**
  84408. * Gets the global Saturation value.
  84409. * 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.
  84410. */
  84411. get: function () {
  84412. return this._globalSaturation;
  84413. },
  84414. /**
  84415. * Sets the global Saturation value.
  84416. * 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.
  84417. */
  84418. set: function (value) {
  84419. this._globalSaturation = value;
  84420. this._dirty = true;
  84421. },
  84422. enumerable: true,
  84423. configurable: true
  84424. });
  84425. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  84426. /**
  84427. * Gets the global Exposure value.
  84428. * 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.
  84429. */
  84430. get: function () {
  84431. return this._globalExposure;
  84432. },
  84433. /**
  84434. * Sets the global Exposure value.
  84435. * 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.
  84436. */
  84437. set: function (value) {
  84438. this._globalExposure = value;
  84439. this._dirty = true;
  84440. },
  84441. enumerable: true,
  84442. configurable: true
  84443. });
  84444. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  84445. /**
  84446. * Gets the highlights Hue value.
  84447. * 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).
  84448. */
  84449. get: function () {
  84450. return this._highlightsHue;
  84451. },
  84452. /**
  84453. * Sets the highlights Hue value.
  84454. * 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).
  84455. */
  84456. set: function (value) {
  84457. this._highlightsHue = value;
  84458. this._dirty = true;
  84459. },
  84460. enumerable: true,
  84461. configurable: true
  84462. });
  84463. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  84464. /**
  84465. * Gets the highlights Density value.
  84466. * 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.
  84467. * Values less than zero provide a filter of opposite hue.
  84468. */
  84469. get: function () {
  84470. return this._highlightsDensity;
  84471. },
  84472. /**
  84473. * Sets the highlights Density value.
  84474. * 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.
  84475. * Values less than zero provide a filter of opposite hue.
  84476. */
  84477. set: function (value) {
  84478. this._highlightsDensity = value;
  84479. this._dirty = true;
  84480. },
  84481. enumerable: true,
  84482. configurable: true
  84483. });
  84484. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  84485. /**
  84486. * Gets the highlights Saturation value.
  84487. * 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.
  84488. */
  84489. get: function () {
  84490. return this._highlightsSaturation;
  84491. },
  84492. /**
  84493. * Sets the highlights Saturation value.
  84494. * 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.
  84495. */
  84496. set: function (value) {
  84497. this._highlightsSaturation = value;
  84498. this._dirty = true;
  84499. },
  84500. enumerable: true,
  84501. configurable: true
  84502. });
  84503. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  84504. /**
  84505. * Gets the highlights Exposure value.
  84506. * 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.
  84507. */
  84508. get: function () {
  84509. return this._highlightsExposure;
  84510. },
  84511. /**
  84512. * Sets the highlights Exposure value.
  84513. * 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.
  84514. */
  84515. set: function (value) {
  84516. this._highlightsExposure = value;
  84517. this._dirty = true;
  84518. },
  84519. enumerable: true,
  84520. configurable: true
  84521. });
  84522. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  84523. /**
  84524. * Gets the midtones Hue value.
  84525. * 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).
  84526. */
  84527. get: function () {
  84528. return this._midtonesHue;
  84529. },
  84530. /**
  84531. * Sets the midtones Hue value.
  84532. * 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).
  84533. */
  84534. set: function (value) {
  84535. this._midtonesHue = value;
  84536. this._dirty = true;
  84537. },
  84538. enumerable: true,
  84539. configurable: true
  84540. });
  84541. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  84542. /**
  84543. * Gets the midtones Density value.
  84544. * 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.
  84545. * Values less than zero provide a filter of opposite hue.
  84546. */
  84547. get: function () {
  84548. return this._midtonesDensity;
  84549. },
  84550. /**
  84551. * Sets the midtones Density value.
  84552. * 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.
  84553. * Values less than zero provide a filter of opposite hue.
  84554. */
  84555. set: function (value) {
  84556. this._midtonesDensity = value;
  84557. this._dirty = true;
  84558. },
  84559. enumerable: true,
  84560. configurable: true
  84561. });
  84562. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  84563. /**
  84564. * Gets the midtones Saturation value.
  84565. * 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.
  84566. */
  84567. get: function () {
  84568. return this._midtonesSaturation;
  84569. },
  84570. /**
  84571. * Sets the midtones Saturation value.
  84572. * 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.
  84573. */
  84574. set: function (value) {
  84575. this._midtonesSaturation = value;
  84576. this._dirty = true;
  84577. },
  84578. enumerable: true,
  84579. configurable: true
  84580. });
  84581. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  84582. /**
  84583. * Gets the midtones Exposure value.
  84584. * 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.
  84585. */
  84586. get: function () {
  84587. return this._midtonesExposure;
  84588. },
  84589. /**
  84590. * Sets the midtones Exposure value.
  84591. * 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.
  84592. */
  84593. set: function (value) {
  84594. this._midtonesExposure = value;
  84595. this._dirty = true;
  84596. },
  84597. enumerable: true,
  84598. configurable: true
  84599. });
  84600. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  84601. /**
  84602. * Gets the shadows Hue value.
  84603. * 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).
  84604. */
  84605. get: function () {
  84606. return this._shadowsHue;
  84607. },
  84608. /**
  84609. * Sets the shadows Hue value.
  84610. * 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).
  84611. */
  84612. set: function (value) {
  84613. this._shadowsHue = value;
  84614. this._dirty = true;
  84615. },
  84616. enumerable: true,
  84617. configurable: true
  84618. });
  84619. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  84620. /**
  84621. * Gets the shadows Density value.
  84622. * 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.
  84623. * Values less than zero provide a filter of opposite hue.
  84624. */
  84625. get: function () {
  84626. return this._shadowsDensity;
  84627. },
  84628. /**
  84629. * Sets the shadows Density value.
  84630. * 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.
  84631. * Values less than zero provide a filter of opposite hue.
  84632. */
  84633. set: function (value) {
  84634. this._shadowsDensity = value;
  84635. this._dirty = true;
  84636. },
  84637. enumerable: true,
  84638. configurable: true
  84639. });
  84640. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  84641. /**
  84642. * Gets the shadows Saturation value.
  84643. * 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.
  84644. */
  84645. get: function () {
  84646. return this._shadowsSaturation;
  84647. },
  84648. /**
  84649. * Sets the shadows Saturation value.
  84650. * 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.
  84651. */
  84652. set: function (value) {
  84653. this._shadowsSaturation = value;
  84654. this._dirty = true;
  84655. },
  84656. enumerable: true,
  84657. configurable: true
  84658. });
  84659. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  84660. /**
  84661. * Gets the shadows Exposure value.
  84662. * 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.
  84663. */
  84664. get: function () {
  84665. return this._shadowsExposure;
  84666. },
  84667. /**
  84668. * Sets the shadows Exposure value.
  84669. * 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.
  84670. */
  84671. set: function (value) {
  84672. this._shadowsExposure = value;
  84673. this._dirty = true;
  84674. },
  84675. enumerable: true,
  84676. configurable: true
  84677. });
  84678. ColorCurves.prototype.getClassName = function () {
  84679. return "ColorCurves";
  84680. };
  84681. /**
  84682. * Binds the color curves to the shader.
  84683. * @param colorCurves The color curve to bind
  84684. * @param effect The effect to bind to
  84685. */
  84686. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  84687. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  84688. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  84689. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  84690. if (colorCurves._dirty) {
  84691. colorCurves._dirty = false;
  84692. // Fill in global info.
  84693. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  84694. // Compute highlights info.
  84695. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  84696. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  84697. // Compute midtones info.
  84698. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  84699. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  84700. // Compute shadows info.
  84701. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  84702. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  84703. // Compute deltas (neutral is midtones).
  84704. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  84705. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  84706. }
  84707. if (effect) {
  84708. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  84709. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  84710. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  84711. }
  84712. };
  84713. /**
  84714. * Prepare the list of uniforms associated with the ColorCurves effects.
  84715. * @param uniformsList The list of uniforms used in the effect
  84716. */
  84717. ColorCurves.PrepareUniforms = function (uniformsList) {
  84718. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  84719. };
  84720. /**
  84721. * Returns color grading data based on a hue, density, saturation and exposure value.
  84722. * @param filterHue The hue of the color filter.
  84723. * @param filterDensity The density of the color filter.
  84724. * @param saturation The saturation.
  84725. * @param exposure The exposure.
  84726. * @param result The result data container.
  84727. */
  84728. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  84729. if (hue == null) {
  84730. return;
  84731. }
  84732. hue = ColorCurves.clamp(hue, 0, 360);
  84733. density = ColorCurves.clamp(density, -100, 100);
  84734. saturation = ColorCurves.clamp(saturation, -100, 100);
  84735. exposure = ColorCurves.clamp(exposure, -100, 100);
  84736. // Remap the slider/config filter density with non-linear mapping and also scale by half
  84737. // so that the maximum filter density is only 50% control. This provides fine control
  84738. // for small values and reasonable range.
  84739. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  84740. density *= 0.5;
  84741. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  84742. if (density < 0) {
  84743. density *= -1;
  84744. hue = (hue + 180) % 360;
  84745. }
  84746. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  84747. result.scaleToRef(2, result);
  84748. result.a = 1 + 0.01 * saturation;
  84749. };
  84750. /**
  84751. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  84752. * @param value The input slider value in range [-100,100].
  84753. * @returns Adjusted value.
  84754. */
  84755. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  84756. value /= 100;
  84757. var x = Math.abs(value);
  84758. x = Math.pow(x, 2);
  84759. if (value < 0) {
  84760. x *= -1;
  84761. }
  84762. x *= 100;
  84763. return x;
  84764. };
  84765. /**
  84766. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  84767. * @param hue The hue (H) input.
  84768. * @param saturation The saturation (S) input.
  84769. * @param brightness The brightness (B) input.
  84770. * @result An RGBA color represented as Vector4.
  84771. */
  84772. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  84773. var h = ColorCurves.clamp(hue, 0, 360);
  84774. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  84775. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  84776. if (s === 0) {
  84777. result.r = v;
  84778. result.g = v;
  84779. result.b = v;
  84780. }
  84781. else {
  84782. // sector 0 to 5
  84783. h /= 60;
  84784. var i = Math.floor(h);
  84785. // fractional part of h
  84786. var f = h - i;
  84787. var p = v * (1 - s);
  84788. var q = v * (1 - s * f);
  84789. var t = v * (1 - s * (1 - f));
  84790. switch (i) {
  84791. case 0:
  84792. result.r = v;
  84793. result.g = t;
  84794. result.b = p;
  84795. break;
  84796. case 1:
  84797. result.r = q;
  84798. result.g = v;
  84799. result.b = p;
  84800. break;
  84801. case 2:
  84802. result.r = p;
  84803. result.g = v;
  84804. result.b = t;
  84805. break;
  84806. case 3:
  84807. result.r = p;
  84808. result.g = q;
  84809. result.b = v;
  84810. break;
  84811. case 4:
  84812. result.r = t;
  84813. result.g = p;
  84814. result.b = v;
  84815. break;
  84816. default: // case 5:
  84817. result.r = v;
  84818. result.g = p;
  84819. result.b = q;
  84820. break;
  84821. }
  84822. }
  84823. result.a = 1;
  84824. };
  84825. /**
  84826. * Returns a value clamped between min and max
  84827. * @param value The value to clamp
  84828. * @param min The minimum of value
  84829. * @param max The maximum of value
  84830. * @returns The clamped value.
  84831. */
  84832. ColorCurves.clamp = function (value, min, max) {
  84833. return Math.min(Math.max(value, min), max);
  84834. };
  84835. /**
  84836. * Clones the current color curve instance.
  84837. * @return The cloned curves
  84838. */
  84839. ColorCurves.prototype.clone = function () {
  84840. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  84841. };
  84842. /**
  84843. * Serializes the current color curve instance to a json representation.
  84844. * @return a JSON representation
  84845. */
  84846. ColorCurves.prototype.serialize = function () {
  84847. return BABYLON.SerializationHelper.Serialize(this);
  84848. };
  84849. /**
  84850. * Parses the color curve from a json representation.
  84851. * @param source the JSON source to parse
  84852. * @return The parsed curves
  84853. */
  84854. ColorCurves.Parse = function (source) {
  84855. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  84856. };
  84857. __decorate([
  84858. BABYLON.serialize()
  84859. ], ColorCurves.prototype, "_globalHue", void 0);
  84860. __decorate([
  84861. BABYLON.serialize()
  84862. ], ColorCurves.prototype, "_globalDensity", void 0);
  84863. __decorate([
  84864. BABYLON.serialize()
  84865. ], ColorCurves.prototype, "_globalSaturation", void 0);
  84866. __decorate([
  84867. BABYLON.serialize()
  84868. ], ColorCurves.prototype, "_globalExposure", void 0);
  84869. __decorate([
  84870. BABYLON.serialize()
  84871. ], ColorCurves.prototype, "_highlightsHue", void 0);
  84872. __decorate([
  84873. BABYLON.serialize()
  84874. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  84875. __decorate([
  84876. BABYLON.serialize()
  84877. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  84878. __decorate([
  84879. BABYLON.serialize()
  84880. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  84881. __decorate([
  84882. BABYLON.serialize()
  84883. ], ColorCurves.prototype, "_midtonesHue", void 0);
  84884. __decorate([
  84885. BABYLON.serialize()
  84886. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  84887. __decorate([
  84888. BABYLON.serialize()
  84889. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  84890. __decorate([
  84891. BABYLON.serialize()
  84892. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  84893. return ColorCurves;
  84894. }());
  84895. BABYLON.ColorCurves = ColorCurves;
  84896. })(BABYLON || (BABYLON = {}));
  84897. //# sourceMappingURL=babylon.colorCurves.js.map
  84898. var BABYLON;
  84899. (function (BABYLON) {
  84900. var RefractionPostProcess = /** @class */ (function (_super) {
  84901. __extends(RefractionPostProcess, _super);
  84902. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  84903. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  84904. _this.color = color;
  84905. _this.depth = depth;
  84906. _this.colorLevel = colorLevel;
  84907. _this._ownRefractionTexture = true;
  84908. _this.onActivateObservable.add(function (cam) {
  84909. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  84910. });
  84911. _this.onApplyObservable.add(function (effect) {
  84912. effect.setColor3("baseColor", _this.color);
  84913. effect.setFloat("depth", _this.depth);
  84914. effect.setFloat("colorLevel", _this.colorLevel);
  84915. effect.setTexture("refractionSampler", _this._refTexture);
  84916. });
  84917. return _this;
  84918. }
  84919. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  84920. /**
  84921. * Gets or sets the refraction texture
  84922. * Please note that you are responsible for disposing the texture if you set it manually
  84923. */
  84924. get: function () {
  84925. return this._refTexture;
  84926. },
  84927. set: function (value) {
  84928. if (this._refTexture && this._ownRefractionTexture) {
  84929. this._refTexture.dispose();
  84930. }
  84931. this._refTexture = value;
  84932. this._ownRefractionTexture = false;
  84933. },
  84934. enumerable: true,
  84935. configurable: true
  84936. });
  84937. // Methods
  84938. RefractionPostProcess.prototype.dispose = function (camera) {
  84939. if (this._refTexture && this._ownRefractionTexture) {
  84940. this._refTexture.dispose();
  84941. this._refTexture = null;
  84942. }
  84943. _super.prototype.dispose.call(this, camera);
  84944. };
  84945. return RefractionPostProcess;
  84946. }(BABYLON.PostProcess));
  84947. BABYLON.RefractionPostProcess = RefractionPostProcess;
  84948. })(BABYLON || (BABYLON = {}));
  84949. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  84950. var BABYLON;
  84951. (function (BABYLON) {
  84952. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  84953. __extends(BlackAndWhitePostProcess, _super);
  84954. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  84955. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  84956. _this.degree = 1;
  84957. _this.onApplyObservable.add(function (effect) {
  84958. effect.setFloat("degree", _this.degree);
  84959. });
  84960. return _this;
  84961. }
  84962. return BlackAndWhitePostProcess;
  84963. }(BABYLON.PostProcess));
  84964. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  84965. })(BABYLON || (BABYLON = {}));
  84966. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  84967. var BABYLON;
  84968. (function (BABYLON) {
  84969. /**
  84970. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  84971. * input texture to perform effects such as edge detection or sharpening
  84972. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  84973. */
  84974. var ConvolutionPostProcess = /** @class */ (function (_super) {
  84975. __extends(ConvolutionPostProcess, _super);
  84976. /**
  84977. * Creates a new instance ConvolutionPostProcess
  84978. * @param name The name of the effect.
  84979. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  84980. * @param options The required width/height ratio to downsize to before computing the render pass.
  84981. * @param camera The camera to apply the render pass to.
  84982. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84983. * @param engine The engine which the post process will be applied. (default: current engine)
  84984. * @param reusable If the post process can be reused on the same frame. (default: false)
  84985. * @param textureType Type of textures used when performing the post process. (default: 0)
  84986. */
  84987. function ConvolutionPostProcess(name,
  84988. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  84989. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  84990. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84991. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  84992. _this.kernel = kernel;
  84993. _this.onApply = function (effect) {
  84994. effect.setFloat2("screenSize", _this.width, _this.height);
  84995. effect.setArray("kernel", _this.kernel);
  84996. };
  84997. return _this;
  84998. }
  84999. // Statics
  85000. /**
  85001. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85002. */
  85003. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  85004. /**
  85005. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85006. */
  85007. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  85008. /**
  85009. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85010. */
  85011. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  85012. /**
  85013. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85014. */
  85015. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  85016. /**
  85017. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85018. */
  85019. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  85020. /**
  85021. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85022. */
  85023. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  85024. return ConvolutionPostProcess;
  85025. }(BABYLON.PostProcess));
  85026. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  85027. })(BABYLON || (BABYLON = {}));
  85028. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  85029. var BABYLON;
  85030. (function (BABYLON) {
  85031. var FilterPostProcess = /** @class */ (function (_super) {
  85032. __extends(FilterPostProcess, _super);
  85033. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  85034. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  85035. _this.kernelMatrix = kernelMatrix;
  85036. _this.onApply = function (effect) {
  85037. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  85038. };
  85039. return _this;
  85040. }
  85041. return FilterPostProcess;
  85042. }(BABYLON.PostProcess));
  85043. BABYLON.FilterPostProcess = FilterPostProcess;
  85044. })(BABYLON || (BABYLON = {}));
  85045. //# sourceMappingURL=babylon.filterPostProcess.js.map
  85046. var BABYLON;
  85047. (function (BABYLON) {
  85048. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  85049. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  85050. __extends(VolumetricLightScatteringPostProcess, _super);
  85051. /**
  85052. * @constructor
  85053. * @param {string} name - The post-process name
  85054. * @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)
  85055. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  85056. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  85057. * @param {number} samples - The post-process quality, default 100
  85058. * @param {number} samplingMode - The post-process filtering mode
  85059. * @param {BABYLON.Engine} engine - The babylon engine
  85060. * @param {boolean} reusable - If the post-process is reusable
  85061. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  85062. */
  85063. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  85064. if (samples === void 0) { samples = 100; }
  85065. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85066. 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;
  85067. _this._screenCoordinates = BABYLON.Vector2.Zero();
  85068. /**
  85069. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  85070. */
  85071. _this.customMeshPosition = BABYLON.Vector3.Zero();
  85072. /**
  85073. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  85074. */
  85075. _this.useCustomMeshPosition = false;
  85076. /**
  85077. * If the post-process should inverse the light scattering direction
  85078. */
  85079. _this.invert = true;
  85080. /**
  85081. * Array containing the excluded meshes not rendered in the internal pass
  85082. */
  85083. _this.excludedMeshes = new Array();
  85084. /**
  85085. * Controls the overall intensity of the post-process
  85086. */
  85087. _this.exposure = 0.3;
  85088. /**
  85089. * Dissipates each sample's contribution in range [0, 1]
  85090. */
  85091. _this.decay = 0.96815;
  85092. /**
  85093. * Controls the overall intensity of each sample
  85094. */
  85095. _this.weight = 0.58767;
  85096. /**
  85097. * Controls the density of each sample
  85098. */
  85099. _this.density = 0.926;
  85100. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  85101. engine = scene.getEngine();
  85102. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  85103. // Configure mesh
  85104. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  85105. // Configure
  85106. _this._createPass(scene, ratio.passRatio || ratio);
  85107. _this.onActivate = function (camera) {
  85108. if (!_this.isSupported) {
  85109. _this.dispose(camera);
  85110. }
  85111. _this.onActivate = null;
  85112. };
  85113. _this.onApplyObservable.add(function (effect) {
  85114. _this._updateMeshScreenCoordinates(scene);
  85115. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  85116. effect.setFloat("exposure", _this.exposure);
  85117. effect.setFloat("decay", _this.decay);
  85118. effect.setFloat("weight", _this.weight);
  85119. effect.setFloat("density", _this.density);
  85120. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  85121. });
  85122. return _this;
  85123. }
  85124. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  85125. get: function () {
  85126. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  85127. return false;
  85128. },
  85129. set: function (useDiffuseColor) {
  85130. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  85131. },
  85132. enumerable: true,
  85133. configurable: true
  85134. });
  85135. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  85136. return "VolumetricLightScatteringPostProcess";
  85137. };
  85138. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  85139. var mesh = subMesh.getMesh();
  85140. // Render this.mesh as default
  85141. if (mesh === this.mesh && mesh.material) {
  85142. return mesh.material.isReady(mesh);
  85143. }
  85144. var defines = [];
  85145. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85146. var material = subMesh.getMaterial();
  85147. // Alpha test
  85148. if (material) {
  85149. if (material.needAlphaTesting()) {
  85150. defines.push("#define ALPHATEST");
  85151. }
  85152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85153. attribs.push(BABYLON.VertexBuffer.UVKind);
  85154. defines.push("#define UV1");
  85155. }
  85156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85157. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85158. defines.push("#define UV2");
  85159. }
  85160. }
  85161. // Bones
  85162. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85163. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85164. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85165. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85166. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85167. }
  85168. else {
  85169. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85170. }
  85171. // Instances
  85172. if (useInstances) {
  85173. defines.push("#define INSTANCES");
  85174. attribs.push("world0");
  85175. attribs.push("world1");
  85176. attribs.push("world2");
  85177. attribs.push("world3");
  85178. }
  85179. // Get correct effect
  85180. var join = defines.join("\n");
  85181. if (this._cachedDefines !== join) {
  85182. this._cachedDefines = join;
  85183. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  85184. }
  85185. return this._volumetricLightScatteringPass.isReady();
  85186. };
  85187. /**
  85188. * Sets the new light position for light scattering effect
  85189. * @param {BABYLON.Vector3} The new custom light position
  85190. */
  85191. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  85192. this.customMeshPosition = position;
  85193. };
  85194. /**
  85195. * Returns the light position for light scattering effect
  85196. * @return {BABYLON.Vector3} The custom light position
  85197. */
  85198. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  85199. return this.customMeshPosition;
  85200. };
  85201. /**
  85202. * Disposes the internal assets and detaches the post-process from the camera
  85203. */
  85204. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  85205. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  85206. if (rttIndex !== -1) {
  85207. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  85208. }
  85209. this._volumetricLightScatteringRTT.dispose();
  85210. _super.prototype.dispose.call(this, camera);
  85211. };
  85212. /**
  85213. * Returns the render target texture used by the post-process
  85214. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  85215. */
  85216. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  85217. return this._volumetricLightScatteringRTT;
  85218. };
  85219. // Private methods
  85220. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  85221. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  85222. return true;
  85223. }
  85224. return false;
  85225. };
  85226. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  85227. var _this = this;
  85228. var engine = scene.getEngine();
  85229. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85230. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85231. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85232. this._volumetricLightScatteringRTT.renderList = null;
  85233. this._volumetricLightScatteringRTT.renderParticles = false;
  85234. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  85235. var camera = this.getCamera();
  85236. if (camera) {
  85237. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  85238. }
  85239. else {
  85240. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  85241. }
  85242. // Custom render function for submeshes
  85243. var renderSubMesh = function (subMesh) {
  85244. var mesh = subMesh.getRenderingMesh();
  85245. if (_this._meshExcluded(mesh)) {
  85246. return;
  85247. }
  85248. var material = subMesh.getMaterial();
  85249. if (!material) {
  85250. return;
  85251. }
  85252. var scene = mesh.getScene();
  85253. var engine = scene.getEngine();
  85254. // Culling
  85255. engine.setState(material.backFaceCulling);
  85256. // Managing instances
  85257. var batch = mesh._getInstancesRenderList(subMesh._id);
  85258. if (batch.mustReturn) {
  85259. return;
  85260. }
  85261. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85262. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  85263. var effect = _this._volumetricLightScatteringPass;
  85264. if (mesh === _this.mesh) {
  85265. if (subMesh.effect) {
  85266. effect = subMesh.effect;
  85267. }
  85268. else {
  85269. effect = material.getEffect();
  85270. }
  85271. }
  85272. engine.enableEffect(effect);
  85273. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  85274. if (mesh === _this.mesh) {
  85275. material.bind(mesh.getWorldMatrix(), mesh);
  85276. }
  85277. else {
  85278. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  85279. // Alpha test
  85280. if (material && material.needAlphaTesting()) {
  85281. var alphaTexture = material.getAlphaTestTexture();
  85282. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  85283. if (alphaTexture) {
  85284. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85285. }
  85286. }
  85287. // Bones
  85288. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85289. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85290. }
  85291. }
  85292. // Draw
  85293. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  85294. }
  85295. };
  85296. // Render target texture callbacks
  85297. var savedSceneClearColor;
  85298. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  85299. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  85300. savedSceneClearColor = scene.clearColor;
  85301. scene.clearColor = sceneClearColor;
  85302. });
  85303. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  85304. scene.clearColor = savedSceneClearColor;
  85305. });
  85306. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85307. var engine = scene.getEngine();
  85308. var index;
  85309. if (depthOnlySubMeshes.length) {
  85310. engine.setColorWrite(false);
  85311. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85312. renderSubMesh(depthOnlySubMeshes.data[index]);
  85313. }
  85314. engine.setColorWrite(true);
  85315. }
  85316. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85317. renderSubMesh(opaqueSubMeshes.data[index]);
  85318. }
  85319. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85320. renderSubMesh(alphaTestSubMeshes.data[index]);
  85321. }
  85322. if (transparentSubMeshes.length) {
  85323. // Sort sub meshes
  85324. for (index = 0; index < transparentSubMeshes.length; index++) {
  85325. var submesh = transparentSubMeshes.data[index];
  85326. var boundingInfo = submesh.getBoundingInfo();
  85327. if (boundingInfo && scene.activeCamera) {
  85328. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  85329. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  85330. }
  85331. }
  85332. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  85333. sortedArray.sort(function (a, b) {
  85334. // Alpha index first
  85335. if (a._alphaIndex > b._alphaIndex) {
  85336. return 1;
  85337. }
  85338. if (a._alphaIndex < b._alphaIndex) {
  85339. return -1;
  85340. }
  85341. // Then distance to camera
  85342. if (a._distanceToCamera < b._distanceToCamera) {
  85343. return 1;
  85344. }
  85345. if (a._distanceToCamera > b._distanceToCamera) {
  85346. return -1;
  85347. }
  85348. return 0;
  85349. });
  85350. // Render sub meshes
  85351. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  85352. for (index = 0; index < sortedArray.length; index++) {
  85353. renderSubMesh(sortedArray[index]);
  85354. }
  85355. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85356. }
  85357. };
  85358. };
  85359. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  85360. var transform = scene.getTransformMatrix();
  85361. var meshPosition;
  85362. if (this.useCustomMeshPosition) {
  85363. meshPosition = this.customMeshPosition;
  85364. }
  85365. else if (this.attachedNode) {
  85366. meshPosition = this.attachedNode.position;
  85367. }
  85368. else {
  85369. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  85370. }
  85371. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  85372. this._screenCoordinates.x = pos.x / this._viewPort.width;
  85373. this._screenCoordinates.y = pos.y / this._viewPort.height;
  85374. if (this.invert)
  85375. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  85376. };
  85377. // Static methods
  85378. /**
  85379. * Creates a default mesh for the Volumeric Light Scattering post-process
  85380. * @param {string} The mesh name
  85381. * @param {BABYLON.Scene} The scene where to create the mesh
  85382. * @return {BABYLON.Mesh} the default mesh
  85383. */
  85384. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  85385. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  85386. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  85387. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  85388. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  85389. mesh.material = material;
  85390. return mesh;
  85391. };
  85392. __decorate([
  85393. BABYLON.serializeAsVector3()
  85394. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  85395. __decorate([
  85396. BABYLON.serialize()
  85397. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  85398. __decorate([
  85399. BABYLON.serialize()
  85400. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  85401. __decorate([
  85402. BABYLON.serializeAsMeshReference()
  85403. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  85404. __decorate([
  85405. BABYLON.serialize()
  85406. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  85407. __decorate([
  85408. BABYLON.serialize()
  85409. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  85410. __decorate([
  85411. BABYLON.serialize()
  85412. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  85413. __decorate([
  85414. BABYLON.serialize()
  85415. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  85416. __decorate([
  85417. BABYLON.serialize()
  85418. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  85419. return VolumetricLightScatteringPostProcess;
  85420. }(BABYLON.PostProcess));
  85421. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  85422. })(BABYLON || (BABYLON = {}));
  85423. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  85424. //
  85425. // This post-process allows the modification of rendered colors by using
  85426. // a 'look-up table' (LUT). This effect is also called Color Grading.
  85427. //
  85428. // The object needs to be provided an url to a texture containing the color
  85429. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  85430. // Use an image editing software to tweak the LUT to match your needs.
  85431. //
  85432. // For an example of a color LUT, see here:
  85433. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  85434. // For explanations on color grading, see here:
  85435. // http://udn.epicgames.com/Three/ColorGrading.html
  85436. //
  85437. var BABYLON;
  85438. (function (BABYLON) {
  85439. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  85440. __extends(ColorCorrectionPostProcess, _super);
  85441. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  85442. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  85443. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85444. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  85445. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85446. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85447. _this.onApply = function (effect) {
  85448. effect.setTexture("colorTable", _this._colorTableTexture);
  85449. };
  85450. return _this;
  85451. }
  85452. return ColorCorrectionPostProcess;
  85453. }(BABYLON.PostProcess));
  85454. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  85455. })(BABYLON || (BABYLON = {}));
  85456. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  85457. var BABYLON;
  85458. (function (BABYLON) {
  85459. /** Defines operator used for tonemapping */
  85460. var TonemappingOperator;
  85461. (function (TonemappingOperator) {
  85462. /** Hable */
  85463. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  85464. /** Reinhard */
  85465. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  85466. /** HejiDawson */
  85467. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  85468. /** Photographic */
  85469. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  85470. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  85471. ;
  85472. /**
  85473. * Defines a post process to apply tone mapping
  85474. */
  85475. var TonemapPostProcess = /** @class */ (function (_super) {
  85476. __extends(TonemapPostProcess, _super);
  85477. /**
  85478. * Creates a new TonemapPostProcess
  85479. * @param name defines the name of the postprocess
  85480. * @param _operator defines the operator to use
  85481. * @param exposureAdjustment defines the required exposure adjustement
  85482. * @param camera defines the camera to use (can be null)
  85483. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  85484. * @param engine defines the hosting engine (can be ignore if camera is set)
  85485. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  85486. */
  85487. function TonemapPostProcess(name, _operator,
  85488. /** Defines the required exposure adjustement */
  85489. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  85490. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85491. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85492. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  85493. _this._operator = _operator;
  85494. _this.exposureAdjustment = exposureAdjustment;
  85495. var defines = "#define ";
  85496. if (_this._operator === TonemappingOperator.Hable)
  85497. defines += "HABLE_TONEMAPPING";
  85498. else if (_this._operator === TonemappingOperator.Reinhard)
  85499. defines += "REINHARD_TONEMAPPING";
  85500. else if (_this._operator === TonemappingOperator.HejiDawson)
  85501. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  85502. else if (_this._operator === TonemappingOperator.Photographic)
  85503. defines += "PHOTOGRAPHIC_TONEMAPPING";
  85504. //sadly a second call to create the effect.
  85505. _this.updateEffect(defines);
  85506. _this.onApply = function (effect) {
  85507. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  85508. };
  85509. return _this;
  85510. }
  85511. return TonemapPostProcess;
  85512. }(BABYLON.PostProcess));
  85513. BABYLON.TonemapPostProcess = TonemapPostProcess;
  85514. })(BABYLON || (BABYLON = {}));
  85515. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  85516. var BABYLON;
  85517. (function (BABYLON) {
  85518. var DisplayPassPostProcess = /** @class */ (function (_super) {
  85519. __extends(DisplayPassPostProcess, _super);
  85520. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  85521. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  85522. }
  85523. return DisplayPassPostProcess;
  85524. }(BABYLON.PostProcess));
  85525. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  85526. })(BABYLON || (BABYLON = {}));
  85527. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  85528. var BABYLON;
  85529. (function (BABYLON) {
  85530. var HighlightsPostProcess = /** @class */ (function (_super) {
  85531. __extends(HighlightsPostProcess, _super);
  85532. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85533. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85534. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85535. }
  85536. return HighlightsPostProcess;
  85537. }(BABYLON.PostProcess));
  85538. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  85539. })(BABYLON || (BABYLON = {}));
  85540. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  85541. var BABYLON;
  85542. (function (BABYLON) {
  85543. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  85544. __extends(ImageProcessingPostProcess, _super);
  85545. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  85546. if (camera === void 0) { camera = null; }
  85547. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85548. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  85549. _this._fromLinearSpace = true;
  85550. /**
  85551. * Defines cache preventing GC.
  85552. */
  85553. _this._defines = {
  85554. IMAGEPROCESSING: false,
  85555. VIGNETTE: false,
  85556. VIGNETTEBLENDMODEMULTIPLY: false,
  85557. VIGNETTEBLENDMODEOPAQUE: false,
  85558. TONEMAPPING: false,
  85559. TONEMAPPING_ACES: false,
  85560. CONTRAST: false,
  85561. COLORCURVES: false,
  85562. COLORGRADING: false,
  85563. COLORGRADING3D: false,
  85564. FROMLINEARSPACE: false,
  85565. SAMPLER3DGREENDEPTH: false,
  85566. SAMPLER3DBGRMAP: false,
  85567. IMAGEPROCESSINGPOSTPROCESS: false,
  85568. EXPOSURE: false,
  85569. };
  85570. // Setup the configuration as forced by the constructor. This would then not force the
  85571. // scene materials output in linear space and let untouched the default forward pass.
  85572. if (imageProcessingConfiguration) {
  85573. imageProcessingConfiguration.applyByPostProcess = true;
  85574. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  85575. // This will cause the shader to be compiled
  85576. _this.fromLinearSpace = false;
  85577. }
  85578. // Setup the default processing configuration to the scene.
  85579. else {
  85580. _this._attachImageProcessingConfiguration(null, true);
  85581. _this.imageProcessingConfiguration.applyByPostProcess = true;
  85582. }
  85583. _this.onApply = function (effect) {
  85584. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  85585. };
  85586. return _this;
  85587. }
  85588. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  85589. /**
  85590. * Gets the image processing configuration used either in this material.
  85591. */
  85592. get: function () {
  85593. return this._imageProcessingConfiguration;
  85594. },
  85595. /**
  85596. * Sets the Default image processing configuration used either in the this material.
  85597. *
  85598. * If sets to null, the scene one is in use.
  85599. */
  85600. set: function (value) {
  85601. this._attachImageProcessingConfiguration(value);
  85602. },
  85603. enumerable: true,
  85604. configurable: true
  85605. });
  85606. /**
  85607. * Attaches a new image processing configuration to the PBR Material.
  85608. * @param configuration
  85609. */
  85610. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  85611. var _this = this;
  85612. if (doNotBuild === void 0) { doNotBuild = false; }
  85613. if (configuration === this._imageProcessingConfiguration) {
  85614. return;
  85615. }
  85616. // Detaches observer.
  85617. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85618. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85619. }
  85620. // Pick the scene configuration if needed.
  85621. if (!configuration) {
  85622. var scene = null;
  85623. var engine = this.getEngine();
  85624. var camera = this.getCamera();
  85625. if (camera) {
  85626. scene = camera.getScene();
  85627. }
  85628. else if (engine && engine.scenes) {
  85629. var scenes = engine.scenes;
  85630. scene = scenes[scenes.length - 1];
  85631. }
  85632. else {
  85633. scene = BABYLON.Engine.LastCreatedScene;
  85634. }
  85635. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  85636. }
  85637. else {
  85638. this._imageProcessingConfiguration = configuration;
  85639. }
  85640. // Attaches observer.
  85641. if (this._imageProcessingConfiguration) {
  85642. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  85643. _this._updateParameters();
  85644. });
  85645. }
  85646. // Ensure the effect will be rebuilt.
  85647. if (!doNotBuild) {
  85648. this._updateParameters();
  85649. }
  85650. };
  85651. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  85652. /**
  85653. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  85654. */
  85655. get: function () {
  85656. return this.imageProcessingConfiguration.colorCurves;
  85657. },
  85658. /**
  85659. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  85660. */
  85661. set: function (value) {
  85662. this.imageProcessingConfiguration.colorCurves = value;
  85663. },
  85664. enumerable: true,
  85665. configurable: true
  85666. });
  85667. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  85668. /**
  85669. * Gets wether the color curves effect is enabled.
  85670. */
  85671. get: function () {
  85672. return this.imageProcessingConfiguration.colorCurvesEnabled;
  85673. },
  85674. /**
  85675. * Sets wether the color curves effect is enabled.
  85676. */
  85677. set: function (value) {
  85678. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  85679. },
  85680. enumerable: true,
  85681. configurable: true
  85682. });
  85683. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  85684. /**
  85685. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  85686. */
  85687. get: function () {
  85688. return this.imageProcessingConfiguration.colorGradingTexture;
  85689. },
  85690. /**
  85691. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  85692. */
  85693. set: function (value) {
  85694. this.imageProcessingConfiguration.colorGradingTexture = value;
  85695. },
  85696. enumerable: true,
  85697. configurable: true
  85698. });
  85699. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  85700. /**
  85701. * Gets wether the color grading effect is enabled.
  85702. */
  85703. get: function () {
  85704. return this.imageProcessingConfiguration.colorGradingEnabled;
  85705. },
  85706. /**
  85707. * Gets wether the color grading effect is enabled.
  85708. */
  85709. set: function (value) {
  85710. this.imageProcessingConfiguration.colorGradingEnabled = value;
  85711. },
  85712. enumerable: true,
  85713. configurable: true
  85714. });
  85715. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  85716. /**
  85717. * Gets exposure used in the effect.
  85718. */
  85719. get: function () {
  85720. return this.imageProcessingConfiguration.exposure;
  85721. },
  85722. /**
  85723. * Sets exposure used in the effect.
  85724. */
  85725. set: function (value) {
  85726. this.imageProcessingConfiguration.exposure = value;
  85727. },
  85728. enumerable: true,
  85729. configurable: true
  85730. });
  85731. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  85732. /**
  85733. * Gets wether tonemapping is enabled or not.
  85734. */
  85735. get: function () {
  85736. return this._imageProcessingConfiguration.toneMappingEnabled;
  85737. },
  85738. /**
  85739. * Sets wether tonemapping is enabled or not
  85740. */
  85741. set: function (value) {
  85742. this._imageProcessingConfiguration.toneMappingEnabled = value;
  85743. },
  85744. enumerable: true,
  85745. configurable: true
  85746. });
  85747. ;
  85748. ;
  85749. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  85750. /**
  85751. * Gets contrast used in the effect.
  85752. */
  85753. get: function () {
  85754. return this.imageProcessingConfiguration.contrast;
  85755. },
  85756. /**
  85757. * Sets contrast used in the effect.
  85758. */
  85759. set: function (value) {
  85760. this.imageProcessingConfiguration.contrast = value;
  85761. },
  85762. enumerable: true,
  85763. configurable: true
  85764. });
  85765. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  85766. /**
  85767. * Gets Vignette stretch size.
  85768. */
  85769. get: function () {
  85770. return this.imageProcessingConfiguration.vignetteStretch;
  85771. },
  85772. /**
  85773. * Sets Vignette stretch size.
  85774. */
  85775. set: function (value) {
  85776. this.imageProcessingConfiguration.vignetteStretch = value;
  85777. },
  85778. enumerable: true,
  85779. configurable: true
  85780. });
  85781. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  85782. /**
  85783. * Gets Vignette centre X Offset.
  85784. */
  85785. get: function () {
  85786. return this.imageProcessingConfiguration.vignetteCentreX;
  85787. },
  85788. /**
  85789. * Sets Vignette centre X Offset.
  85790. */
  85791. set: function (value) {
  85792. this.imageProcessingConfiguration.vignetteCentreX = value;
  85793. },
  85794. enumerable: true,
  85795. configurable: true
  85796. });
  85797. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  85798. /**
  85799. * Gets Vignette centre Y Offset.
  85800. */
  85801. get: function () {
  85802. return this.imageProcessingConfiguration.vignetteCentreY;
  85803. },
  85804. /**
  85805. * Sets Vignette centre Y Offset.
  85806. */
  85807. set: function (value) {
  85808. this.imageProcessingConfiguration.vignetteCentreY = value;
  85809. },
  85810. enumerable: true,
  85811. configurable: true
  85812. });
  85813. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  85814. /**
  85815. * Gets Vignette weight or intensity of the vignette effect.
  85816. */
  85817. get: function () {
  85818. return this.imageProcessingConfiguration.vignetteWeight;
  85819. },
  85820. /**
  85821. * Sets Vignette weight or intensity of the vignette effect.
  85822. */
  85823. set: function (value) {
  85824. this.imageProcessingConfiguration.vignetteWeight = value;
  85825. },
  85826. enumerable: true,
  85827. configurable: true
  85828. });
  85829. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  85830. /**
  85831. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  85832. * if vignetteEnabled is set to true.
  85833. */
  85834. get: function () {
  85835. return this.imageProcessingConfiguration.vignetteColor;
  85836. },
  85837. /**
  85838. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  85839. * if vignetteEnabled is set to true.
  85840. */
  85841. set: function (value) {
  85842. this.imageProcessingConfiguration.vignetteColor = value;
  85843. },
  85844. enumerable: true,
  85845. configurable: true
  85846. });
  85847. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  85848. /**
  85849. * Gets Camera field of view used by the Vignette effect.
  85850. */
  85851. get: function () {
  85852. return this.imageProcessingConfiguration.vignetteCameraFov;
  85853. },
  85854. /**
  85855. * Sets Camera field of view used by the Vignette effect.
  85856. */
  85857. set: function (value) {
  85858. this.imageProcessingConfiguration.vignetteCameraFov = value;
  85859. },
  85860. enumerable: true,
  85861. configurable: true
  85862. });
  85863. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  85864. /**
  85865. * Gets the vignette blend mode allowing different kind of effect.
  85866. */
  85867. get: function () {
  85868. return this.imageProcessingConfiguration.vignetteBlendMode;
  85869. },
  85870. /**
  85871. * Sets the vignette blend mode allowing different kind of effect.
  85872. */
  85873. set: function (value) {
  85874. this.imageProcessingConfiguration.vignetteBlendMode = value;
  85875. },
  85876. enumerable: true,
  85877. configurable: true
  85878. });
  85879. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  85880. /**
  85881. * Gets wether the vignette effect is enabled.
  85882. */
  85883. get: function () {
  85884. return this.imageProcessingConfiguration.vignetteEnabled;
  85885. },
  85886. /**
  85887. * Sets wether the vignette effect is enabled.
  85888. */
  85889. set: function (value) {
  85890. this.imageProcessingConfiguration.vignetteEnabled = value;
  85891. },
  85892. enumerable: true,
  85893. configurable: true
  85894. });
  85895. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  85896. /**
  85897. * Gets wether the input of the processing is in Gamma or Linear Space.
  85898. */
  85899. get: function () {
  85900. return this._fromLinearSpace;
  85901. },
  85902. /**
  85903. * Sets wether the input of the processing is in Gamma or Linear Space.
  85904. */
  85905. set: function (value) {
  85906. if (this._fromLinearSpace === value) {
  85907. return;
  85908. }
  85909. this._fromLinearSpace = value;
  85910. this._updateParameters();
  85911. },
  85912. enumerable: true,
  85913. configurable: true
  85914. });
  85915. ImageProcessingPostProcess.prototype.getClassName = function () {
  85916. return "ImageProcessingPostProcess";
  85917. };
  85918. ImageProcessingPostProcess.prototype._updateParameters = function () {
  85919. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  85920. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  85921. var defines = "";
  85922. for (var define in this._defines) {
  85923. if (this._defines[define]) {
  85924. defines += "#define " + define + ";\r\n";
  85925. }
  85926. }
  85927. var samplers = ["textureSampler"];
  85928. var uniforms = ["scale"];
  85929. if (BABYLON.ImageProcessingConfiguration) {
  85930. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  85931. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  85932. }
  85933. this.updateEffect(defines, uniforms, samplers);
  85934. };
  85935. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  85936. _super.prototype.dispose.call(this, camera);
  85937. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85938. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85939. }
  85940. if (this._imageProcessingConfiguration) {
  85941. this.imageProcessingConfiguration.applyByPostProcess = false;
  85942. }
  85943. };
  85944. __decorate([
  85945. BABYLON.serialize()
  85946. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  85947. return ImageProcessingPostProcess;
  85948. }(BABYLON.PostProcess));
  85949. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  85950. })(BABYLON || (BABYLON = {}));
  85951. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  85952. var BABYLON;
  85953. (function (BABYLON) {
  85954. /**
  85955. * Class used to store bone information
  85956. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  85957. */
  85958. var Bone = /** @class */ (function (_super) {
  85959. __extends(Bone, _super);
  85960. /**
  85961. * Create a new bone
  85962. * @param name defines the bone name
  85963. * @param skeleton defines the parent skeleton
  85964. * @param parentBone defines the parent (can be null if the bone is the root)
  85965. * @param localMatrix defines the local matrix
  85966. * @param restPose defines the rest pose matrix
  85967. * @param baseMatrix defines the base matrix
  85968. * @param index defines index of the bone in the hiearchy
  85969. */
  85970. function Bone(
  85971. /**
  85972. * defines the bone name
  85973. */
  85974. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  85975. if (parentBone === void 0) { parentBone = null; }
  85976. if (localMatrix === void 0) { localMatrix = null; }
  85977. if (restPose === void 0) { restPose = null; }
  85978. if (baseMatrix === void 0) { baseMatrix = null; }
  85979. if (index === void 0) { index = null; }
  85980. var _this = _super.call(this, name, skeleton.getScene()) || this;
  85981. _this.name = name;
  85982. /**
  85983. * Gets the list of child bones
  85984. */
  85985. _this.children = new Array();
  85986. /** Gets the animations associated with this bone */
  85987. _this.animations = new Array();
  85988. /**
  85989. * @hidden Internal only
  85990. * Set this value to map this bone to a different index in the transform matrices
  85991. * Set this value to -1 to exclude the bone from the transform matrices
  85992. */
  85993. _this._index = null;
  85994. _this._absoluteTransform = new BABYLON.Matrix();
  85995. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  85996. _this._scalingDeterminant = 1;
  85997. _this._worldTransform = new BABYLON.Matrix();
  85998. _this._needToDecompose = true;
  85999. _this._needToCompose = false;
  86000. _this._skeleton = skeleton;
  86001. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  86002. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  86003. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  86004. _this._index = index;
  86005. skeleton.bones.push(_this);
  86006. _this.setParent(parentBone, false);
  86007. if (baseMatrix || localMatrix) {
  86008. _this._updateDifferenceMatrix();
  86009. }
  86010. return _this;
  86011. }
  86012. Object.defineProperty(Bone.prototype, "_matrix", {
  86013. /** @hidden */
  86014. get: function () {
  86015. this._compose();
  86016. return this._localMatrix;
  86017. },
  86018. /** @hidden */
  86019. set: function (value) {
  86020. this._localMatrix.copyFrom(value);
  86021. this._needToDecompose = true;
  86022. },
  86023. enumerable: true,
  86024. configurable: true
  86025. });
  86026. // Members
  86027. /**
  86028. * Gets the parent skeleton
  86029. * @returns a skeleton
  86030. */
  86031. Bone.prototype.getSkeleton = function () {
  86032. return this._skeleton;
  86033. };
  86034. /**
  86035. * Gets parent bone
  86036. * @returns a bone or null if the bone is the root of the bone hierarchy
  86037. */
  86038. Bone.prototype.getParent = function () {
  86039. return this._parent;
  86040. };
  86041. /**
  86042. * Sets the parent bone
  86043. * @param parent defines the parent (can be null if the bone is the root)
  86044. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86045. */
  86046. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  86047. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86048. if (this._parent === parent) {
  86049. return;
  86050. }
  86051. if (this._parent) {
  86052. var index = this._parent.children.indexOf(this);
  86053. if (index !== -1) {
  86054. this._parent.children.splice(index, 1);
  86055. }
  86056. }
  86057. this._parent = parent;
  86058. if (this._parent) {
  86059. this._parent.children.push(this);
  86060. }
  86061. if (updateDifferenceMatrix) {
  86062. this._updateDifferenceMatrix();
  86063. }
  86064. this.markAsDirty();
  86065. };
  86066. /**
  86067. * Gets the local matrix
  86068. * @returns a matrix
  86069. */
  86070. Bone.prototype.getLocalMatrix = function () {
  86071. this._compose();
  86072. return this._localMatrix;
  86073. };
  86074. /**
  86075. * Gets the base matrix (initial matrix which remains unchanged)
  86076. * @returns a matrix
  86077. */
  86078. Bone.prototype.getBaseMatrix = function () {
  86079. return this._baseMatrix;
  86080. };
  86081. /**
  86082. * Gets the rest pose matrix
  86083. * @returns a matrix
  86084. */
  86085. Bone.prototype.getRestPose = function () {
  86086. return this._restPose;
  86087. };
  86088. /**
  86089. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  86090. */
  86091. Bone.prototype.getWorldMatrix = function () {
  86092. return this._worldTransform;
  86093. };
  86094. /**
  86095. * Sets the local matrix to rest pose matrix
  86096. */
  86097. Bone.prototype.returnToRest = function () {
  86098. this.updateMatrix(this._restPose.clone());
  86099. };
  86100. /**
  86101. * Gets the inverse of the absolute transform matrix.
  86102. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  86103. * @returns a matrix
  86104. */
  86105. Bone.prototype.getInvertedAbsoluteTransform = function () {
  86106. return this._invertedAbsoluteTransform;
  86107. };
  86108. /**
  86109. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  86110. * @returns a matrix
  86111. */
  86112. Bone.prototype.getAbsoluteTransform = function () {
  86113. return this._absoluteTransform;
  86114. };
  86115. Object.defineProperty(Bone.prototype, "position", {
  86116. // Properties (matches AbstractMesh properties)
  86117. /** Gets or sets current position (in local space) */
  86118. get: function () {
  86119. this._decompose();
  86120. return this._localPosition;
  86121. },
  86122. set: function (newPosition) {
  86123. this._decompose();
  86124. this._localPosition.copyFrom(newPosition);
  86125. this._markAsDirtyAndCompose();
  86126. },
  86127. enumerable: true,
  86128. configurable: true
  86129. });
  86130. Object.defineProperty(Bone.prototype, "rotation", {
  86131. /** Gets or sets current rotation (in local space) */
  86132. get: function () {
  86133. return this.getRotation();
  86134. },
  86135. set: function (newRotation) {
  86136. this.setRotation(newRotation);
  86137. },
  86138. enumerable: true,
  86139. configurable: true
  86140. });
  86141. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  86142. /** Gets or sets current rotation quaternion (in local space) */
  86143. get: function () {
  86144. this._decompose();
  86145. return this._localRotation;
  86146. },
  86147. set: function (newRotation) {
  86148. this.setRotationQuaternion(newRotation);
  86149. },
  86150. enumerable: true,
  86151. configurable: true
  86152. });
  86153. Object.defineProperty(Bone.prototype, "scaling", {
  86154. /** Gets or sets current scaling (in local space) */
  86155. get: function () {
  86156. return this.getScale();
  86157. },
  86158. set: function (newScaling) {
  86159. this.setScale(newScaling);
  86160. },
  86161. enumerable: true,
  86162. configurable: true
  86163. });
  86164. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  86165. /**
  86166. * Gets the animation properties override
  86167. */
  86168. get: function () {
  86169. return this._skeleton.animationPropertiesOverride;
  86170. },
  86171. enumerable: true,
  86172. configurable: true
  86173. });
  86174. // Methods
  86175. Bone.prototype._decompose = function () {
  86176. if (!this._needToDecompose) {
  86177. return;
  86178. }
  86179. this._needToDecompose = false;
  86180. if (!this._localScaling) {
  86181. this._localScaling = BABYLON.Vector3.Zero();
  86182. this._localRotation = BABYLON.Quaternion.Zero();
  86183. this._localPosition = BABYLON.Vector3.Zero();
  86184. }
  86185. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  86186. };
  86187. Bone.prototype._compose = function () {
  86188. if (!this._needToCompose) {
  86189. return;
  86190. }
  86191. this._needToCompose = false;
  86192. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  86193. };
  86194. /**
  86195. * Update the base and local matrices
  86196. * @param matrix defines the new base or local matrix
  86197. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86198. * @param updateLocalMatrix defines if the local matrix should be updated
  86199. */
  86200. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  86201. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86202. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  86203. this._baseMatrix.copyFrom(matrix);
  86204. if (updateDifferenceMatrix) {
  86205. this._updateDifferenceMatrix();
  86206. }
  86207. if (updateLocalMatrix) {
  86208. this._localMatrix.copyFrom(matrix);
  86209. this._markAsDirtyAndDecompose();
  86210. }
  86211. else {
  86212. this.markAsDirty();
  86213. }
  86214. };
  86215. /** @hidden */
  86216. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  86217. if (updateChildren === void 0) { updateChildren = true; }
  86218. if (!rootMatrix) {
  86219. rootMatrix = this._baseMatrix;
  86220. }
  86221. if (this._parent) {
  86222. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  86223. }
  86224. else {
  86225. this._absoluteTransform.copyFrom(rootMatrix);
  86226. }
  86227. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  86228. if (updateChildren) {
  86229. for (var index = 0; index < this.children.length; index++) {
  86230. this.children[index]._updateDifferenceMatrix();
  86231. }
  86232. }
  86233. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  86234. };
  86235. /**
  86236. * Flag the bone as dirty (Forcing it to update everything)
  86237. */
  86238. Bone.prototype.markAsDirty = function () {
  86239. this._currentRenderId++;
  86240. this._childRenderId++;
  86241. this._skeleton._markAsDirty();
  86242. };
  86243. Bone.prototype._markAsDirtyAndCompose = function () {
  86244. this.markAsDirty();
  86245. this._needToCompose = true;
  86246. };
  86247. Bone.prototype._markAsDirtyAndDecompose = function () {
  86248. this.markAsDirty();
  86249. this._needToDecompose = true;
  86250. };
  86251. /**
  86252. * Copy an animation range from another bone
  86253. * @param source defines the source bone
  86254. * @param rangeName defines the range name to copy
  86255. * @param frameOffset defines the frame offset
  86256. * @param rescaleAsRequired defines if rescaling must be applied if required
  86257. * @param skelDimensionsRatio defines the scaling ratio
  86258. * @returns true if operation was successful
  86259. */
  86260. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  86261. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86262. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  86263. // all animation may be coming from a library skeleton, so may need to create animation
  86264. if (this.animations.length === 0) {
  86265. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  86266. this.animations[0].setKeys([]);
  86267. }
  86268. // get animation info / verify there is such a range from the source bone
  86269. var sourceRange = source.animations[0].getRange(rangeName);
  86270. if (!sourceRange) {
  86271. return false;
  86272. }
  86273. var from = sourceRange.from;
  86274. var to = sourceRange.to;
  86275. var sourceKeys = source.animations[0].getKeys();
  86276. // rescaling prep
  86277. var sourceBoneLength = source.length;
  86278. var sourceParent = source.getParent();
  86279. var parent = this.getParent();
  86280. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  86281. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  86282. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  86283. var destKeys = this.animations[0].getKeys();
  86284. // loop vars declaration
  86285. var orig;
  86286. var origTranslation;
  86287. var mat;
  86288. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  86289. orig = sourceKeys[key];
  86290. if (orig.frame >= from && orig.frame <= to) {
  86291. if (rescaleAsRequired) {
  86292. mat = orig.value.clone();
  86293. // scale based on parent ratio, when bone has parent
  86294. if (parentScalingReqd) {
  86295. origTranslation = mat.getTranslation();
  86296. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  86297. // scale based on skeleton dimension ratio when root bone, and value is passed
  86298. }
  86299. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  86300. origTranslation = mat.getTranslation();
  86301. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  86302. // use original when root bone, and no data for skelDimensionsRatio
  86303. }
  86304. else {
  86305. mat = orig.value;
  86306. }
  86307. }
  86308. else {
  86309. mat = orig.value;
  86310. }
  86311. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  86312. }
  86313. }
  86314. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  86315. return true;
  86316. };
  86317. /**
  86318. * Translate the bone in local or world space
  86319. * @param vec The amount to translate the bone
  86320. * @param space The space that the translation is in
  86321. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86322. */
  86323. Bone.prototype.translate = function (vec, space, mesh) {
  86324. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86325. var lm = this.getLocalMatrix();
  86326. if (space == BABYLON.Space.LOCAL) {
  86327. lm.m[12] += vec.x;
  86328. lm.m[13] += vec.y;
  86329. lm.m[14] += vec.z;
  86330. }
  86331. else {
  86332. var wm = null;
  86333. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86334. if (mesh) {
  86335. wm = mesh.getWorldMatrix();
  86336. }
  86337. this._skeleton.computeAbsoluteTransforms();
  86338. var tmat = Bone._tmpMats[0];
  86339. var tvec = Bone._tmpVecs[0];
  86340. if (this._parent) {
  86341. if (mesh && wm) {
  86342. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86343. tmat.multiplyToRef(wm, tmat);
  86344. }
  86345. else {
  86346. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86347. }
  86348. }
  86349. tmat.m[12] = 0;
  86350. tmat.m[13] = 0;
  86351. tmat.m[14] = 0;
  86352. tmat.invert();
  86353. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  86354. lm.m[12] += tvec.x;
  86355. lm.m[13] += tvec.y;
  86356. lm.m[14] += tvec.z;
  86357. }
  86358. this._markAsDirtyAndDecompose();
  86359. };
  86360. /**
  86361. * Set the postion of the bone in local or world space
  86362. * @param position The position to set the bone
  86363. * @param space The space that the position is in
  86364. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86365. */
  86366. Bone.prototype.setPosition = function (position, space, mesh) {
  86367. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86368. var lm = this.getLocalMatrix();
  86369. if (space == BABYLON.Space.LOCAL) {
  86370. lm.m[12] = position.x;
  86371. lm.m[13] = position.y;
  86372. lm.m[14] = position.z;
  86373. }
  86374. else {
  86375. var wm = null;
  86376. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86377. if (mesh) {
  86378. wm = mesh.getWorldMatrix();
  86379. }
  86380. this._skeleton.computeAbsoluteTransforms();
  86381. var tmat = Bone._tmpMats[0];
  86382. var vec = Bone._tmpVecs[0];
  86383. if (this._parent) {
  86384. if (mesh && wm) {
  86385. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86386. tmat.multiplyToRef(wm, tmat);
  86387. }
  86388. else {
  86389. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86390. }
  86391. }
  86392. tmat.invert();
  86393. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  86394. lm.m[12] = vec.x;
  86395. lm.m[13] = vec.y;
  86396. lm.m[14] = vec.z;
  86397. }
  86398. this._markAsDirtyAndDecompose();
  86399. };
  86400. /**
  86401. * Set the absolute position of the bone (world space)
  86402. * @param position The position to set the bone
  86403. * @param mesh The mesh that this bone is attached to
  86404. */
  86405. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  86406. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  86407. };
  86408. /**
  86409. * Scale the bone on the x, y and z axes (in local space)
  86410. * @param x The amount to scale the bone on the x axis
  86411. * @param y The amount to scale the bone on the y axis
  86412. * @param z The amount to scale the bone on the z axis
  86413. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  86414. */
  86415. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  86416. if (scaleChildren === void 0) { scaleChildren = false; }
  86417. var locMat = this.getLocalMatrix();
  86418. // Apply new scaling on top of current local matrix
  86419. var scaleMat = Bone._tmpMats[0];
  86420. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  86421. scaleMat.multiplyToRef(locMat, locMat);
  86422. // Invert scaling matrix and apply the inverse to all children
  86423. scaleMat.invert();
  86424. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  86425. var child = _a[_i];
  86426. var cm = child.getLocalMatrix();
  86427. cm.multiplyToRef(scaleMat, cm);
  86428. cm.m[12] *= x;
  86429. cm.m[13] *= y;
  86430. cm.m[14] *= z;
  86431. child._markAsDirtyAndDecompose();
  86432. }
  86433. this._markAsDirtyAndDecompose();
  86434. if (scaleChildren) {
  86435. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  86436. var child = _c[_b];
  86437. child.scale(x, y, z, scaleChildren);
  86438. }
  86439. }
  86440. };
  86441. /**
  86442. * Set the bone scaling in local space
  86443. * @param scale defines the scaling vector
  86444. */
  86445. Bone.prototype.setScale = function (scale) {
  86446. this._decompose();
  86447. this._localScaling.copyFrom(scale);
  86448. this._markAsDirtyAndCompose();
  86449. };
  86450. /**
  86451. * Gets the current scaling in local space
  86452. * @returns the current scaling vector
  86453. */
  86454. Bone.prototype.getScale = function () {
  86455. this._decompose();
  86456. return this._localScaling;
  86457. };
  86458. /**
  86459. * Gets the current scaling in local space and stores it in a target vector
  86460. * @param result defines the target vector
  86461. */
  86462. Bone.prototype.getScaleToRef = function (result) {
  86463. this._decompose();
  86464. result.copyFrom(this._localScaling);
  86465. };
  86466. /**
  86467. * Set the yaw, pitch, and roll of the bone in local or world space
  86468. * @param yaw The rotation of the bone on the y axis
  86469. * @param pitch The rotation of the bone on the x axis
  86470. * @param roll The rotation of the bone on the z axis
  86471. * @param space The space that the axes of rotation are in
  86472. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86473. */
  86474. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  86475. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86476. if (space === BABYLON.Space.LOCAL) {
  86477. var quat = Bone._tmpQuat;
  86478. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  86479. this.setRotationQuaternion(quat, space, mesh);
  86480. return;
  86481. }
  86482. var rotMatInv = Bone._tmpMats[0];
  86483. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86484. return;
  86485. }
  86486. var rotMat = Bone._tmpMats[1];
  86487. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  86488. rotMatInv.multiplyToRef(rotMat, rotMat);
  86489. this._rotateWithMatrix(rotMat, space, mesh);
  86490. };
  86491. /**
  86492. * Add a rotation to the bone on an axis in local or world space
  86493. * @param axis The axis to rotate the bone on
  86494. * @param amount The amount to rotate the bone
  86495. * @param space The space that the axis is in
  86496. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86497. */
  86498. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  86499. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86500. var rmat = Bone._tmpMats[0];
  86501. rmat.m[12] = 0;
  86502. rmat.m[13] = 0;
  86503. rmat.m[14] = 0;
  86504. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  86505. this._rotateWithMatrix(rmat, space, mesh);
  86506. };
  86507. /**
  86508. * Set the rotation of the bone to a particular axis angle in local or world space
  86509. * @param axis The axis to rotate the bone on
  86510. * @param angle The angle that the bone should be rotated to
  86511. * @param space The space that the axis is in
  86512. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86513. */
  86514. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  86515. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86516. if (space === BABYLON.Space.LOCAL) {
  86517. var quat = Bone._tmpQuat;
  86518. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  86519. this.setRotationQuaternion(quat, space, mesh);
  86520. return;
  86521. }
  86522. var rotMatInv = Bone._tmpMats[0];
  86523. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86524. return;
  86525. }
  86526. var rotMat = Bone._tmpMats[1];
  86527. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  86528. rotMatInv.multiplyToRef(rotMat, rotMat);
  86529. this._rotateWithMatrix(rotMat, space, mesh);
  86530. };
  86531. /**
  86532. * Set the euler rotation of the bone in local of world space
  86533. * @param rotation The euler rotation that the bone should be set to
  86534. * @param space The space that the rotation is in
  86535. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86536. */
  86537. Bone.prototype.setRotation = function (rotation, space, mesh) {
  86538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86539. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  86540. };
  86541. /**
  86542. * Set the quaternion rotation of the bone in local of world space
  86543. * @param quat The quaternion rotation that the bone should be set to
  86544. * @param space The space that the rotation is in
  86545. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86546. */
  86547. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  86548. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86549. if (space === BABYLON.Space.LOCAL) {
  86550. this._decompose();
  86551. this._localRotation.copyFrom(quat);
  86552. this._markAsDirtyAndCompose();
  86553. return;
  86554. }
  86555. var rotMatInv = Bone._tmpMats[0];
  86556. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86557. return;
  86558. }
  86559. var rotMat = Bone._tmpMats[1];
  86560. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  86561. rotMatInv.multiplyToRef(rotMat, rotMat);
  86562. this._rotateWithMatrix(rotMat, space, mesh);
  86563. };
  86564. /**
  86565. * Set the rotation matrix of the bone in local of world space
  86566. * @param rotMat The rotation matrix that the bone should be set to
  86567. * @param space The space that the rotation is in
  86568. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86569. */
  86570. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  86571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86572. if (space === BABYLON.Space.LOCAL) {
  86573. var quat = Bone._tmpQuat;
  86574. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  86575. this.setRotationQuaternion(quat, space, mesh);
  86576. return;
  86577. }
  86578. var rotMatInv = Bone._tmpMats[0];
  86579. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86580. return;
  86581. }
  86582. var rotMat2 = Bone._tmpMats[1];
  86583. rotMat2.copyFrom(rotMat);
  86584. rotMatInv.multiplyToRef(rotMat, rotMat2);
  86585. this._rotateWithMatrix(rotMat2, space, mesh);
  86586. };
  86587. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  86588. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86589. var lmat = this.getLocalMatrix();
  86590. var lx = lmat.m[12];
  86591. var ly = lmat.m[13];
  86592. var lz = lmat.m[14];
  86593. var parent = this.getParent();
  86594. var parentScale = Bone._tmpMats[3];
  86595. var parentScaleInv = Bone._tmpMats[4];
  86596. if (parent && space == BABYLON.Space.WORLD) {
  86597. if (mesh) {
  86598. parentScale.copyFrom(mesh.getWorldMatrix());
  86599. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  86600. }
  86601. else {
  86602. parentScale.copyFrom(parent.getAbsoluteTransform());
  86603. }
  86604. parentScaleInv.copyFrom(parentScale);
  86605. parentScaleInv.invert();
  86606. lmat.multiplyToRef(parentScale, lmat);
  86607. lmat.multiplyToRef(rmat, lmat);
  86608. lmat.multiplyToRef(parentScaleInv, lmat);
  86609. }
  86610. else {
  86611. if (space == BABYLON.Space.WORLD && mesh) {
  86612. parentScale.copyFrom(mesh.getWorldMatrix());
  86613. parentScaleInv.copyFrom(parentScale);
  86614. parentScaleInv.invert();
  86615. lmat.multiplyToRef(parentScale, lmat);
  86616. lmat.multiplyToRef(rmat, lmat);
  86617. lmat.multiplyToRef(parentScaleInv, lmat);
  86618. }
  86619. else {
  86620. lmat.multiplyToRef(rmat, lmat);
  86621. }
  86622. }
  86623. lmat.m[12] = lx;
  86624. lmat.m[13] = ly;
  86625. lmat.m[14] = lz;
  86626. this.computeAbsoluteTransforms();
  86627. this._markAsDirtyAndDecompose();
  86628. };
  86629. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  86630. var scaleMatrix = Bone._tmpMats[2];
  86631. rotMatInv.copyFrom(this.getAbsoluteTransform());
  86632. if (mesh) {
  86633. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  86634. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  86635. }
  86636. rotMatInv.invert();
  86637. if (isNaN(rotMatInv.m[0])) {
  86638. // Matrix failed to invert.
  86639. // This can happen if scale is zero for example.
  86640. return false;
  86641. }
  86642. scaleMatrix.m[0] *= this._scalingDeterminant;
  86643. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  86644. return true;
  86645. };
  86646. /**
  86647. * Get the position of the bone in local or world space
  86648. * @param space The space that the returned position is in
  86649. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86650. * @returns The position of the bone
  86651. */
  86652. Bone.prototype.getPosition = function (space, mesh) {
  86653. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86654. if (mesh === void 0) { mesh = null; }
  86655. var pos = BABYLON.Vector3.Zero();
  86656. this.getPositionToRef(space, mesh, pos);
  86657. return pos;
  86658. };
  86659. /**
  86660. * Copy the position of the bone to a vector3 in local or world space
  86661. * @param space The space that the returned position is in
  86662. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86663. * @param result The vector3 to copy the position to
  86664. */
  86665. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  86666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86667. if (space == BABYLON.Space.LOCAL) {
  86668. var lm = this.getLocalMatrix();
  86669. result.x = lm.m[12];
  86670. result.y = lm.m[13];
  86671. result.z = lm.m[14];
  86672. }
  86673. else {
  86674. var wm = null;
  86675. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86676. if (mesh) {
  86677. wm = mesh.getWorldMatrix();
  86678. }
  86679. this._skeleton.computeAbsoluteTransforms();
  86680. var tmat = Bone._tmpMats[0];
  86681. if (mesh && wm) {
  86682. tmat.copyFrom(this.getAbsoluteTransform());
  86683. tmat.multiplyToRef(wm, tmat);
  86684. }
  86685. else {
  86686. tmat = this.getAbsoluteTransform();
  86687. }
  86688. result.x = tmat.m[12];
  86689. result.y = tmat.m[13];
  86690. result.z = tmat.m[14];
  86691. }
  86692. };
  86693. /**
  86694. * Get the absolute position of the bone (world space)
  86695. * @param mesh The mesh that this bone is attached to
  86696. * @returns The absolute position of the bone
  86697. */
  86698. Bone.prototype.getAbsolutePosition = function (mesh) {
  86699. if (mesh === void 0) { mesh = null; }
  86700. var pos = BABYLON.Vector3.Zero();
  86701. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  86702. return pos;
  86703. };
  86704. /**
  86705. * Copy the absolute position of the bone (world space) to the result param
  86706. * @param mesh The mesh that this bone is attached to
  86707. * @param result The vector3 to copy the absolute position to
  86708. */
  86709. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  86710. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  86711. };
  86712. /**
  86713. * Compute the absolute transforms of this bone and its children
  86714. */
  86715. Bone.prototype.computeAbsoluteTransforms = function () {
  86716. this._compose();
  86717. if (this._parent) {
  86718. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  86719. }
  86720. else {
  86721. this._absoluteTransform.copyFrom(this._localMatrix);
  86722. var poseMatrix = this._skeleton.getPoseMatrix();
  86723. if (poseMatrix) {
  86724. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  86725. }
  86726. }
  86727. var children = this.children;
  86728. var len = children.length;
  86729. for (var i = 0; i < len; i++) {
  86730. children[i].computeAbsoluteTransforms();
  86731. }
  86732. };
  86733. /**
  86734. * Get the world direction from an axis that is in the local space of the bone
  86735. * @param localAxis The local direction that is used to compute the world direction
  86736. * @param mesh The mesh that this bone is attached to
  86737. * @returns The world direction
  86738. */
  86739. Bone.prototype.getDirection = function (localAxis, mesh) {
  86740. if (mesh === void 0) { mesh = null; }
  86741. var result = BABYLON.Vector3.Zero();
  86742. this.getDirectionToRef(localAxis, mesh, result);
  86743. return result;
  86744. };
  86745. /**
  86746. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  86747. * @param localAxis The local direction that is used to compute the world direction
  86748. * @param mesh The mesh that this bone is attached to
  86749. * @param result The vector3 that the world direction will be copied to
  86750. */
  86751. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  86752. if (mesh === void 0) { mesh = null; }
  86753. var wm = null;
  86754. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86755. if (mesh) {
  86756. wm = mesh.getWorldMatrix();
  86757. }
  86758. this._skeleton.computeAbsoluteTransforms();
  86759. var mat = Bone._tmpMats[0];
  86760. mat.copyFrom(this.getAbsoluteTransform());
  86761. if (mesh && wm) {
  86762. mat.multiplyToRef(wm, mat);
  86763. }
  86764. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  86765. result.normalize();
  86766. };
  86767. /**
  86768. * Get the euler rotation of the bone in local or world space
  86769. * @param space The space that the rotation should be in
  86770. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86771. * @returns The euler rotation
  86772. */
  86773. Bone.prototype.getRotation = function (space, mesh) {
  86774. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86775. if (mesh === void 0) { mesh = null; }
  86776. var result = BABYLON.Vector3.Zero();
  86777. this.getRotationToRef(space, mesh, result);
  86778. return result;
  86779. };
  86780. /**
  86781. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  86782. * @param space The space that the rotation should be in
  86783. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86784. * @param result The vector3 that the rotation should be copied to
  86785. */
  86786. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  86787. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86788. if (mesh === void 0) { mesh = null; }
  86789. var quat = Bone._tmpQuat;
  86790. this.getRotationQuaternionToRef(space, mesh, quat);
  86791. quat.toEulerAnglesToRef(result);
  86792. };
  86793. /**
  86794. * Get the quaternion rotation of the bone in either local or world space
  86795. * @param space The space that the rotation should be in
  86796. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86797. * @returns The quaternion rotation
  86798. */
  86799. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  86800. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86801. if (mesh === void 0) { mesh = null; }
  86802. var result = BABYLON.Quaternion.Identity();
  86803. this.getRotationQuaternionToRef(space, mesh, result);
  86804. return result;
  86805. };
  86806. /**
  86807. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  86808. * @param space The space that the rotation should be in
  86809. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86810. * @param result The quaternion that the rotation should be copied to
  86811. */
  86812. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  86813. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86814. if (mesh === void 0) { mesh = null; }
  86815. if (space == BABYLON.Space.LOCAL) {
  86816. this._decompose();
  86817. result.copyFrom(this._localRotation);
  86818. }
  86819. else {
  86820. var mat = Bone._tmpMats[0];
  86821. var amat = this.getAbsoluteTransform();
  86822. if (mesh) {
  86823. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  86824. }
  86825. else {
  86826. mat.copyFrom(amat);
  86827. }
  86828. mat.m[0] *= this._scalingDeterminant;
  86829. mat.m[1] *= this._scalingDeterminant;
  86830. mat.m[2] *= this._scalingDeterminant;
  86831. mat.decompose(undefined, result, undefined);
  86832. }
  86833. };
  86834. /**
  86835. * Get the rotation matrix of the bone in local or world space
  86836. * @param space The space that the rotation should be in
  86837. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86838. * @returns The rotation matrix
  86839. */
  86840. Bone.prototype.getRotationMatrix = function (space, mesh) {
  86841. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86842. var result = BABYLON.Matrix.Identity();
  86843. this.getRotationMatrixToRef(space, mesh, result);
  86844. return result;
  86845. };
  86846. /**
  86847. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  86848. * @param space The space that the rotation should be in
  86849. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86850. * @param result The quaternion that the rotation should be copied to
  86851. */
  86852. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  86853. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86854. if (space == BABYLON.Space.LOCAL) {
  86855. this.getLocalMatrix().getRotationMatrixToRef(result);
  86856. }
  86857. else {
  86858. var mat = Bone._tmpMats[0];
  86859. var amat = this.getAbsoluteTransform();
  86860. if (mesh) {
  86861. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  86862. }
  86863. else {
  86864. mat.copyFrom(amat);
  86865. }
  86866. mat.m[0] *= this._scalingDeterminant;
  86867. mat.m[1] *= this._scalingDeterminant;
  86868. mat.m[2] *= this._scalingDeterminant;
  86869. mat.getRotationMatrixToRef(result);
  86870. }
  86871. };
  86872. /**
  86873. * Get the world position of a point that is in the local space of the bone
  86874. * @param position The local position
  86875. * @param mesh The mesh that this bone is attached to
  86876. * @returns The world position
  86877. */
  86878. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  86879. if (mesh === void 0) { mesh = null; }
  86880. var result = BABYLON.Vector3.Zero();
  86881. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  86882. return result;
  86883. };
  86884. /**
  86885. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  86886. * @param position The local position
  86887. * @param mesh The mesh that this bone is attached to
  86888. * @param result The vector3 that the world position should be copied to
  86889. */
  86890. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  86891. if (mesh === void 0) { mesh = null; }
  86892. var wm = null;
  86893. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86894. if (mesh) {
  86895. wm = mesh.getWorldMatrix();
  86896. }
  86897. this._skeleton.computeAbsoluteTransforms();
  86898. var tmat = Bone._tmpMats[0];
  86899. if (mesh && wm) {
  86900. tmat.copyFrom(this.getAbsoluteTransform());
  86901. tmat.multiplyToRef(wm, tmat);
  86902. }
  86903. else {
  86904. tmat = this.getAbsoluteTransform();
  86905. }
  86906. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  86907. };
  86908. /**
  86909. * Get the local position of a point that is in world space
  86910. * @param position The world position
  86911. * @param mesh The mesh that this bone is attached to
  86912. * @returns The local position
  86913. */
  86914. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  86915. if (mesh === void 0) { mesh = null; }
  86916. var result = BABYLON.Vector3.Zero();
  86917. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  86918. return result;
  86919. };
  86920. /**
  86921. * Get the local position of a point that is in world space and copy it to the result param
  86922. * @param position The world position
  86923. * @param mesh The mesh that this bone is attached to
  86924. * @param result The vector3 that the local position should be copied to
  86925. */
  86926. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  86927. if (mesh === void 0) { mesh = null; }
  86928. var wm = null;
  86929. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86930. if (mesh) {
  86931. wm = mesh.getWorldMatrix();
  86932. }
  86933. this._skeleton.computeAbsoluteTransforms();
  86934. var tmat = Bone._tmpMats[0];
  86935. tmat.copyFrom(this.getAbsoluteTransform());
  86936. if (mesh && wm) {
  86937. tmat.multiplyToRef(wm, tmat);
  86938. }
  86939. tmat.invert();
  86940. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  86941. };
  86942. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86943. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  86944. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  86945. return Bone;
  86946. }(BABYLON.Node));
  86947. BABYLON.Bone = Bone;
  86948. })(BABYLON || (BABYLON = {}));
  86949. //# sourceMappingURL=babylon.bone.js.map
  86950. var BABYLON;
  86951. (function (BABYLON) {
  86952. /**
  86953. * Class used to apply inverse kinematics to bones
  86954. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  86955. */
  86956. var BoneIKController = /** @class */ (function () {
  86957. /**
  86958. * Creates a new BoneIKController
  86959. * @param mesh defines the mesh to control
  86960. * @param bone defines the bone to control
  86961. * @param options defines options to set up the controller
  86962. */
  86963. function BoneIKController(mesh, bone, options) {
  86964. /**
  86965. * Gets or sets the target position
  86966. */
  86967. this.targetPosition = BABYLON.Vector3.Zero();
  86968. /**
  86969. * Gets or sets the pole target position
  86970. */
  86971. this.poleTargetPosition = BABYLON.Vector3.Zero();
  86972. /**
  86973. * Gets or sets the pole target local offset
  86974. */
  86975. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  86976. /**
  86977. * Gets or sets the pole angle
  86978. */
  86979. this.poleAngle = 0;
  86980. /**
  86981. * 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)
  86982. */
  86983. this.slerpAmount = 1;
  86984. this._bone1Quat = BABYLON.Quaternion.Identity();
  86985. this._bone1Mat = BABYLON.Matrix.Identity();
  86986. this._bone2Ang = Math.PI;
  86987. this._maxAngle = Math.PI;
  86988. this._rightHandedSystem = false;
  86989. this._bendAxis = BABYLON.Vector3.Right();
  86990. this._slerping = false;
  86991. this._adjustRoll = 0;
  86992. this._bone2 = bone;
  86993. this._bone1 = bone.getParent();
  86994. if (!this._bone1) {
  86995. return;
  86996. }
  86997. this.mesh = mesh;
  86998. var bonePos = bone.getPosition();
  86999. if (bone.getAbsoluteTransform().determinant() > 0) {
  87000. this._rightHandedSystem = true;
  87001. this._bendAxis.x = 0;
  87002. this._bendAxis.y = 0;
  87003. this._bendAxis.z = -1;
  87004. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  87005. this._adjustRoll = Math.PI * .5;
  87006. this._bendAxis.z = 1;
  87007. }
  87008. }
  87009. if (this._bone1.length) {
  87010. var boneScale1 = this._bone1.getScale();
  87011. var boneScale2 = this._bone2.getScale();
  87012. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  87013. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  87014. }
  87015. else if (this._bone1.children[0]) {
  87016. mesh.computeWorldMatrix(true);
  87017. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  87018. var pos2 = this._bone2.getAbsolutePosition(mesh);
  87019. var pos3 = this._bone1.getAbsolutePosition(mesh);
  87020. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  87021. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  87022. }
  87023. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  87024. this.maxAngle = Math.PI;
  87025. if (options) {
  87026. if (options.targetMesh) {
  87027. this.targetMesh = options.targetMesh;
  87028. this.targetMesh.computeWorldMatrix(true);
  87029. }
  87030. if (options.poleTargetMesh) {
  87031. this.poleTargetMesh = options.poleTargetMesh;
  87032. this.poleTargetMesh.computeWorldMatrix(true);
  87033. }
  87034. else if (options.poleTargetBone) {
  87035. this.poleTargetBone = options.poleTargetBone;
  87036. }
  87037. else if (this._bone1.getParent()) {
  87038. this.poleTargetBone = this._bone1.getParent();
  87039. }
  87040. if (options.poleTargetLocalOffset) {
  87041. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  87042. }
  87043. if (options.poleAngle) {
  87044. this.poleAngle = options.poleAngle;
  87045. }
  87046. if (options.bendAxis) {
  87047. this._bendAxis.copyFrom(options.bendAxis);
  87048. }
  87049. if (options.maxAngle) {
  87050. this.maxAngle = options.maxAngle;
  87051. }
  87052. if (options.slerpAmount) {
  87053. this.slerpAmount = options.slerpAmount;
  87054. }
  87055. }
  87056. }
  87057. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  87058. /**
  87059. * Gets or sets maximum allowed angle
  87060. */
  87061. get: function () {
  87062. return this._maxAngle;
  87063. },
  87064. set: function (value) {
  87065. this._setMaxAngle(value);
  87066. },
  87067. enumerable: true,
  87068. configurable: true
  87069. });
  87070. BoneIKController.prototype._setMaxAngle = function (ang) {
  87071. if (ang < 0) {
  87072. ang = 0;
  87073. }
  87074. if (ang > Math.PI || ang == undefined) {
  87075. ang = Math.PI;
  87076. }
  87077. this._maxAngle = ang;
  87078. var a = this._bone1Length;
  87079. var b = this._bone2Length;
  87080. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  87081. };
  87082. /**
  87083. * Force the controller to update the bones
  87084. */
  87085. BoneIKController.prototype.update = function () {
  87086. var bone1 = this._bone1;
  87087. if (!bone1) {
  87088. return;
  87089. }
  87090. var target = this.targetPosition;
  87091. var poleTarget = this.poleTargetPosition;
  87092. var mat1 = BoneIKController._tmpMats[0];
  87093. var mat2 = BoneIKController._tmpMats[1];
  87094. if (this.targetMesh) {
  87095. target.copyFrom(this.targetMesh.getAbsolutePosition());
  87096. }
  87097. if (this.poleTargetBone) {
  87098. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  87099. }
  87100. else if (this.poleTargetMesh) {
  87101. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  87102. }
  87103. var bonePos = BoneIKController._tmpVecs[0];
  87104. var zaxis = BoneIKController._tmpVecs[1];
  87105. var xaxis = BoneIKController._tmpVecs[2];
  87106. var yaxis = BoneIKController._tmpVecs[3];
  87107. var upAxis = BoneIKController._tmpVecs[4];
  87108. var _tmpQuat = BoneIKController._tmpQuat;
  87109. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  87110. poleTarget.subtractToRef(bonePos, upAxis);
  87111. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  87112. upAxis.y = 1;
  87113. }
  87114. else {
  87115. upAxis.normalize();
  87116. }
  87117. target.subtractToRef(bonePos, yaxis);
  87118. yaxis.normalize();
  87119. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  87120. zaxis.normalize();
  87121. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  87122. xaxis.normalize();
  87123. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  87124. var a = this._bone1Length;
  87125. var b = this._bone2Length;
  87126. var c = BABYLON.Vector3.Distance(bonePos, target);
  87127. if (this._maxReach > 0) {
  87128. c = Math.min(this._maxReach, c);
  87129. }
  87130. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  87131. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  87132. if (acosa > 1) {
  87133. acosa = 1;
  87134. }
  87135. if (acosb > 1) {
  87136. acosb = 1;
  87137. }
  87138. if (acosa < -1) {
  87139. acosa = -1;
  87140. }
  87141. if (acosb < -1) {
  87142. acosb = -1;
  87143. }
  87144. var angA = Math.acos(acosa);
  87145. var angB = Math.acos(acosb);
  87146. var angC = -angA - angB;
  87147. if (this._rightHandedSystem) {
  87148. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  87149. mat2.multiplyToRef(mat1, mat1);
  87150. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  87151. mat2.multiplyToRef(mat1, mat1);
  87152. }
  87153. else {
  87154. var _tmpVec = BoneIKController._tmpVecs[5];
  87155. _tmpVec.copyFrom(this._bendAxis);
  87156. _tmpVec.x *= -1;
  87157. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  87158. mat2.multiplyToRef(mat1, mat1);
  87159. }
  87160. if (this.poleAngle) {
  87161. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  87162. mat1.multiplyToRef(mat2, mat1);
  87163. }
  87164. if (this._bone1) {
  87165. if (this.slerpAmount < 1) {
  87166. if (!this._slerping) {
  87167. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  87168. }
  87169. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  87170. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  87171. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  87172. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  87173. this._slerping = true;
  87174. }
  87175. else {
  87176. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  87177. this._bone1Mat.copyFrom(mat1);
  87178. this._slerping = false;
  87179. }
  87180. }
  87181. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  87182. this._bone2Ang = angC;
  87183. };
  87184. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87185. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  87186. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87187. return BoneIKController;
  87188. }());
  87189. BABYLON.BoneIKController = BoneIKController;
  87190. })(BABYLON || (BABYLON = {}));
  87191. //# sourceMappingURL=babylon.boneIKController.js.map
  87192. var BABYLON;
  87193. (function (BABYLON) {
  87194. /**
  87195. * Class used to make a bone look toward a point in space
  87196. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  87197. */
  87198. var BoneLookController = /** @class */ (function () {
  87199. /**
  87200. * Create a BoneLookController
  87201. * @param mesh the mesh that the bone belongs to
  87202. * @param bone the bone that will be looking to the target
  87203. * @param target the target Vector3 to look at
  87204. * @param settings optional settings:
  87205. * * maxYaw: the maximum angle the bone will yaw to
  87206. * * minYaw: the minimum angle the bone will yaw to
  87207. * * maxPitch: the maximum angle the bone will pitch to
  87208. * * minPitch: the minimum angle the bone will yaw to
  87209. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  87210. * * upAxis: the up axis of the coordinate system
  87211. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  87212. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  87213. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  87214. * * adjustYaw: used to make an adjustment to the yaw of the bone
  87215. * * adjustPitch: used to make an adjustment to the pitch of the bone
  87216. * * adjustRoll: used to make an adjustment to the roll of the bone
  87217. **/
  87218. function BoneLookController(mesh, bone, target, options) {
  87219. /**
  87220. * The up axis of the coordinate system that is used when the bone is rotated
  87221. */
  87222. this.upAxis = BABYLON.Vector3.Up();
  87223. /**
  87224. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  87225. */
  87226. this.upAxisSpace = BABYLON.Space.LOCAL;
  87227. /**
  87228. * Used to make an adjustment to the yaw of the bone
  87229. */
  87230. this.adjustYaw = 0;
  87231. /**
  87232. * Used to make an adjustment to the pitch of the bone
  87233. */
  87234. this.adjustPitch = 0;
  87235. /**
  87236. * Used to make an adjustment to the roll of the bone
  87237. */
  87238. this.adjustRoll = 0;
  87239. /**
  87240. * 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)
  87241. */
  87242. this.slerpAmount = 1;
  87243. this._boneQuat = BABYLON.Quaternion.Identity();
  87244. this._slerping = false;
  87245. this._firstFrameSkipped = false;
  87246. this._fowardAxis = BABYLON.Vector3.Forward();
  87247. this.mesh = mesh;
  87248. this.bone = bone;
  87249. this.target = target;
  87250. if (options) {
  87251. if (options.adjustYaw) {
  87252. this.adjustYaw = options.adjustYaw;
  87253. }
  87254. if (options.adjustPitch) {
  87255. this.adjustPitch = options.adjustPitch;
  87256. }
  87257. if (options.adjustRoll) {
  87258. this.adjustRoll = options.adjustRoll;
  87259. }
  87260. if (options.maxYaw != null) {
  87261. this.maxYaw = options.maxYaw;
  87262. }
  87263. else {
  87264. this.maxYaw = Math.PI;
  87265. }
  87266. if (options.minYaw != null) {
  87267. this.minYaw = options.minYaw;
  87268. }
  87269. else {
  87270. this.minYaw = -Math.PI;
  87271. }
  87272. if (options.maxPitch != null) {
  87273. this.maxPitch = options.maxPitch;
  87274. }
  87275. else {
  87276. this.maxPitch = Math.PI;
  87277. }
  87278. if (options.minPitch != null) {
  87279. this.minPitch = options.minPitch;
  87280. }
  87281. else {
  87282. this.minPitch = -Math.PI;
  87283. }
  87284. if (options.slerpAmount != null) {
  87285. this.slerpAmount = options.slerpAmount;
  87286. }
  87287. if (options.upAxis != null) {
  87288. this.upAxis = options.upAxis;
  87289. }
  87290. if (options.upAxisSpace != null) {
  87291. this.upAxisSpace = options.upAxisSpace;
  87292. }
  87293. if (options.yawAxis != null || options.pitchAxis != null) {
  87294. var newYawAxis = BABYLON.Axis.Y;
  87295. var newPitchAxis = BABYLON.Axis.X;
  87296. if (options.yawAxis != null) {
  87297. newYawAxis = options.yawAxis.clone();
  87298. newYawAxis.normalize();
  87299. }
  87300. if (options.pitchAxis != null) {
  87301. newPitchAxis = options.pitchAxis.clone();
  87302. newPitchAxis.normalize();
  87303. }
  87304. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  87305. this._transformYawPitch = BABYLON.Matrix.Identity();
  87306. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  87307. this._transformYawPitchInv = this._transformYawPitch.clone();
  87308. this._transformYawPitch.invert();
  87309. }
  87310. }
  87311. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  87312. this.upAxisSpace = BABYLON.Space.LOCAL;
  87313. }
  87314. }
  87315. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  87316. /**
  87317. * Gets or sets the minimum yaw angle that the bone can look to
  87318. */
  87319. get: function () {
  87320. return this._minYaw;
  87321. },
  87322. set: function (value) {
  87323. this._minYaw = value;
  87324. this._minYawSin = Math.sin(value);
  87325. this._minYawCos = Math.cos(value);
  87326. if (this._maxYaw != null) {
  87327. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  87328. this._yawRange = this._maxYaw - this._minYaw;
  87329. }
  87330. },
  87331. enumerable: true,
  87332. configurable: true
  87333. });
  87334. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  87335. /**
  87336. * Gets or sets the maximum yaw angle that the bone can look to
  87337. */
  87338. get: function () {
  87339. return this._maxYaw;
  87340. },
  87341. set: function (value) {
  87342. this._maxYaw = value;
  87343. this._maxYawSin = Math.sin(value);
  87344. this._maxYawCos = Math.cos(value);
  87345. if (this._minYaw != null) {
  87346. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  87347. this._yawRange = this._maxYaw - this._minYaw;
  87348. }
  87349. },
  87350. enumerable: true,
  87351. configurable: true
  87352. });
  87353. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  87354. /**
  87355. * Gets or sets the minimum pitch angle that the bone can look to
  87356. */
  87357. get: function () {
  87358. return this._minPitch;
  87359. },
  87360. set: function (value) {
  87361. this._minPitch = value;
  87362. this._minPitchTan = Math.tan(value);
  87363. },
  87364. enumerable: true,
  87365. configurable: true
  87366. });
  87367. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  87368. /**
  87369. * Gets or sets the maximum pitch angle that the bone can look to
  87370. */
  87371. get: function () {
  87372. return this._maxPitch;
  87373. },
  87374. set: function (value) {
  87375. this._maxPitch = value;
  87376. this._maxPitchTan = Math.tan(value);
  87377. },
  87378. enumerable: true,
  87379. configurable: true
  87380. });
  87381. /**
  87382. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  87383. */
  87384. BoneLookController.prototype.update = function () {
  87385. //skip the first frame when slerping so that the mesh rotation is correct
  87386. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  87387. this._firstFrameSkipped = true;
  87388. return;
  87389. }
  87390. var bone = this.bone;
  87391. var bonePos = BoneLookController._tmpVecs[0];
  87392. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  87393. var target = this.target;
  87394. var _tmpMat1 = BoneLookController._tmpMats[0];
  87395. var _tmpMat2 = BoneLookController._tmpMats[1];
  87396. var mesh = this.mesh;
  87397. var parentBone = bone.getParent();
  87398. var upAxis = BoneLookController._tmpVecs[1];
  87399. upAxis.copyFrom(this.upAxis);
  87400. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  87401. if (this._transformYawPitch) {
  87402. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  87403. }
  87404. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  87405. }
  87406. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  87407. mesh.getDirectionToRef(upAxis, upAxis);
  87408. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  87409. upAxis.normalize();
  87410. }
  87411. }
  87412. var checkYaw = false;
  87413. var checkPitch = false;
  87414. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  87415. checkYaw = true;
  87416. }
  87417. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  87418. checkPitch = true;
  87419. }
  87420. if (checkYaw || checkPitch) {
  87421. var spaceMat = BoneLookController._tmpMats[2];
  87422. var spaceMatInv = BoneLookController._tmpMats[3];
  87423. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  87424. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  87425. }
  87426. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  87427. spaceMat.copyFrom(mesh.getWorldMatrix());
  87428. }
  87429. else {
  87430. var forwardAxis = BoneLookController._tmpVecs[2];
  87431. forwardAxis.copyFrom(this._fowardAxis);
  87432. if (this._transformYawPitch) {
  87433. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  87434. }
  87435. if (parentBone) {
  87436. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  87437. }
  87438. else {
  87439. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  87440. }
  87441. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  87442. rightAxis.normalize();
  87443. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  87444. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  87445. }
  87446. spaceMat.invertToRef(spaceMatInv);
  87447. var xzlen = null;
  87448. if (checkPitch) {
  87449. var localTarget = BoneLookController._tmpVecs[3];
  87450. target.subtractToRef(bonePos, localTarget);
  87451. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  87452. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87453. var pitch = Math.atan2(localTarget.y, xzlen);
  87454. var newPitch = pitch;
  87455. if (pitch > this._maxPitch) {
  87456. localTarget.y = this._maxPitchTan * xzlen;
  87457. newPitch = this._maxPitch;
  87458. }
  87459. else if (pitch < this._minPitch) {
  87460. localTarget.y = this._minPitchTan * xzlen;
  87461. newPitch = this._minPitch;
  87462. }
  87463. if (pitch != newPitch) {
  87464. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  87465. localTarget.addInPlace(bonePos);
  87466. target = localTarget;
  87467. }
  87468. }
  87469. if (checkYaw) {
  87470. var localTarget = BoneLookController._tmpVecs[4];
  87471. target.subtractToRef(bonePos, localTarget);
  87472. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  87473. var yaw = Math.atan2(localTarget.x, localTarget.z);
  87474. var newYaw = yaw;
  87475. if (yaw > this._maxYaw || yaw < this._minYaw) {
  87476. if (xzlen == null) {
  87477. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87478. }
  87479. if (this._yawRange > Math.PI) {
  87480. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  87481. localTarget.z = this._maxYawCos * xzlen;
  87482. localTarget.x = this._maxYawSin * xzlen;
  87483. newYaw = this._maxYaw;
  87484. }
  87485. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  87486. localTarget.z = this._minYawCos * xzlen;
  87487. localTarget.x = this._minYawSin * xzlen;
  87488. newYaw = this._minYaw;
  87489. }
  87490. }
  87491. else {
  87492. if (yaw > this._maxYaw) {
  87493. localTarget.z = this._maxYawCos * xzlen;
  87494. localTarget.x = this._maxYawSin * xzlen;
  87495. newYaw = this._maxYaw;
  87496. }
  87497. else if (yaw < this._minYaw) {
  87498. localTarget.z = this._minYawCos * xzlen;
  87499. localTarget.x = this._minYawSin * xzlen;
  87500. newYaw = this._minYaw;
  87501. }
  87502. }
  87503. }
  87504. if (this._slerping && this._yawRange > Math.PI) {
  87505. //are we going to be crossing into the min/max region?
  87506. var boneFwd = BoneLookController._tmpVecs[8];
  87507. boneFwd.copyFrom(BABYLON.Axis.Z);
  87508. if (this._transformYawPitch) {
  87509. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  87510. }
  87511. var boneRotMat = BoneLookController._tmpMats[4];
  87512. this._boneQuat.toRotationMatrix(boneRotMat);
  87513. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  87514. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  87515. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  87516. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  87517. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  87518. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  87519. if (angBtwTar > angBtwMidYaw) {
  87520. if (xzlen == null) {
  87521. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87522. }
  87523. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  87524. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  87525. if (angBtwMin < angBtwMax) {
  87526. newYaw = boneYaw + Math.PI * .75;
  87527. localTarget.z = Math.cos(newYaw) * xzlen;
  87528. localTarget.x = Math.sin(newYaw) * xzlen;
  87529. }
  87530. else {
  87531. newYaw = boneYaw - Math.PI * .75;
  87532. localTarget.z = Math.cos(newYaw) * xzlen;
  87533. localTarget.x = Math.sin(newYaw) * xzlen;
  87534. }
  87535. }
  87536. }
  87537. if (yaw != newYaw) {
  87538. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  87539. localTarget.addInPlace(bonePos);
  87540. target = localTarget;
  87541. }
  87542. }
  87543. }
  87544. var zaxis = BoneLookController._tmpVecs[5];
  87545. var xaxis = BoneLookController._tmpVecs[6];
  87546. var yaxis = BoneLookController._tmpVecs[7];
  87547. var _tmpQuat = BoneLookController._tmpQuat;
  87548. target.subtractToRef(bonePos, zaxis);
  87549. zaxis.normalize();
  87550. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  87551. xaxis.normalize();
  87552. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  87553. yaxis.normalize();
  87554. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  87555. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  87556. return;
  87557. }
  87558. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  87559. return;
  87560. }
  87561. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  87562. return;
  87563. }
  87564. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  87565. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  87566. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  87567. }
  87568. if (this.slerpAmount < 1) {
  87569. if (!this._slerping) {
  87570. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  87571. }
  87572. if (this._transformYawPitch) {
  87573. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  87574. }
  87575. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  87576. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  87577. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  87578. this._slerping = true;
  87579. }
  87580. else {
  87581. if (this._transformYawPitch) {
  87582. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  87583. }
  87584. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  87585. this._slerping = false;
  87586. }
  87587. };
  87588. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  87589. var angDiff = ang2 - ang1;
  87590. angDiff %= Math.PI * 2;
  87591. if (angDiff > Math.PI) {
  87592. angDiff -= Math.PI * 2;
  87593. }
  87594. else if (angDiff < -Math.PI) {
  87595. angDiff += Math.PI * 2;
  87596. }
  87597. return angDiff;
  87598. };
  87599. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  87600. ang1 %= (2 * Math.PI);
  87601. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  87602. ang2 %= (2 * Math.PI);
  87603. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  87604. var ab = 0;
  87605. if (ang1 < ang2) {
  87606. ab = ang2 - ang1;
  87607. }
  87608. else {
  87609. ab = ang1 - ang2;
  87610. }
  87611. if (ab > Math.PI) {
  87612. ab = Math.PI * 2 - ab;
  87613. }
  87614. return ab;
  87615. };
  87616. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  87617. ang %= (2 * Math.PI);
  87618. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  87619. ang1 %= (2 * Math.PI);
  87620. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  87621. ang2 %= (2 * Math.PI);
  87622. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  87623. if (ang1 < ang2) {
  87624. if (ang > ang1 && ang < ang2) {
  87625. return true;
  87626. }
  87627. }
  87628. else {
  87629. if (ang > ang2 && ang < ang1) {
  87630. return true;
  87631. }
  87632. }
  87633. return false;
  87634. };
  87635. 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()];
  87636. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  87637. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87638. return BoneLookController;
  87639. }());
  87640. BABYLON.BoneLookController = BoneLookController;
  87641. })(BABYLON || (BABYLON = {}));
  87642. //# sourceMappingURL=babylon.boneLookController.js.map
  87643. var BABYLON;
  87644. (function (BABYLON) {
  87645. /**
  87646. * Class used to handle skinning animations
  87647. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  87648. */
  87649. var Skeleton = /** @class */ (function () {
  87650. /**
  87651. * Creates a new skeleton
  87652. * @param name defines the skeleton name
  87653. * @param id defines the skeleton Id
  87654. * @param scene defines the hosting scene
  87655. */
  87656. function Skeleton(
  87657. /** defines the skeleton name */
  87658. name,
  87659. /** defines the skeleton Id */
  87660. id, scene) {
  87661. this.name = name;
  87662. this.id = id;
  87663. /**
  87664. * Gets the list of child bones
  87665. */
  87666. this.bones = new Array();
  87667. /**
  87668. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  87669. */
  87670. this.needInitialSkinMatrix = false;
  87671. this._isDirty = true;
  87672. this._meshesWithPoseMatrix = new Array();
  87673. this._identity = BABYLON.Matrix.Identity();
  87674. this._ranges = {};
  87675. this._lastAbsoluteTransformsUpdateId = -1;
  87676. /**
  87677. * Specifies if the skeleton should be serialized
  87678. */
  87679. this.doNotSerialize = false;
  87680. this._animationPropertiesOverride = null;
  87681. // Events
  87682. /**
  87683. * An observable triggered before computing the skeleton's matrices
  87684. */
  87685. this.onBeforeComputeObservable = new BABYLON.Observable();
  87686. this.bones = [];
  87687. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87688. scene.skeletons.push(this);
  87689. //make sure it will recalculate the matrix next time prepare is called.
  87690. this._isDirty = true;
  87691. }
  87692. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  87693. /**
  87694. * Gets or sets the animation properties override
  87695. */
  87696. get: function () {
  87697. if (!this._animationPropertiesOverride) {
  87698. return this._scene.animationPropertiesOverride;
  87699. }
  87700. return this._animationPropertiesOverride;
  87701. },
  87702. set: function (value) {
  87703. this._animationPropertiesOverride = value;
  87704. },
  87705. enumerable: true,
  87706. configurable: true
  87707. });
  87708. // Members
  87709. /**
  87710. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  87711. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  87712. * @returns a Float32Array containing matrices data
  87713. */
  87714. Skeleton.prototype.getTransformMatrices = function (mesh) {
  87715. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  87716. return mesh._bonesTransformMatrices;
  87717. }
  87718. if (!this._transformMatrices) {
  87719. this.prepare();
  87720. }
  87721. return this._transformMatrices;
  87722. };
  87723. /**
  87724. * Gets the current hosting scene
  87725. * @returns a scene object
  87726. */
  87727. Skeleton.prototype.getScene = function () {
  87728. return this._scene;
  87729. };
  87730. // Methods
  87731. /**
  87732. * Gets a string representing the current skeleton data
  87733. * @param fullDetails defines a boolean indicating if we want a verbose version
  87734. * @returns a string representing the current skeleton data
  87735. */
  87736. Skeleton.prototype.toString = function (fullDetails) {
  87737. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  87738. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  87739. if (fullDetails) {
  87740. ret += ", Ranges: {";
  87741. var first = true;
  87742. for (var name_1 in this._ranges) {
  87743. if (first) {
  87744. ret += ", ";
  87745. first = false;
  87746. }
  87747. ret += name_1;
  87748. }
  87749. ret += "}";
  87750. }
  87751. return ret;
  87752. };
  87753. /**
  87754. * Get bone's index searching by name
  87755. * @param name defines bone's name to search for
  87756. * @return the indice of the bone. Returns -1 if not found
  87757. */
  87758. Skeleton.prototype.getBoneIndexByName = function (name) {
  87759. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  87760. if (this.bones[boneIndex].name === name) {
  87761. return boneIndex;
  87762. }
  87763. }
  87764. return -1;
  87765. };
  87766. /**
  87767. * Creater a new animation range
  87768. * @param name defines the name of the range
  87769. * @param from defines the start key
  87770. * @param to defines the end key
  87771. */
  87772. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  87773. // check name not already in use
  87774. if (!this._ranges[name]) {
  87775. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  87776. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  87777. if (this.bones[i].animations[0]) {
  87778. this.bones[i].animations[0].createRange(name, from, to);
  87779. }
  87780. }
  87781. }
  87782. };
  87783. /**
  87784. * Delete a specific animation range
  87785. * @param name defines the name of the range
  87786. * @param deleteFrames defines if frames must be removed as well
  87787. */
  87788. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  87789. if (deleteFrames === void 0) { deleteFrames = true; }
  87790. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  87791. if (this.bones[i].animations[0]) {
  87792. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  87793. }
  87794. }
  87795. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  87796. };
  87797. /**
  87798. * Gets a specific animation range
  87799. * @param name defines the name of the range to look for
  87800. * @returns the requested animation range or null if not found
  87801. */
  87802. Skeleton.prototype.getAnimationRange = function (name) {
  87803. return this._ranges[name];
  87804. };
  87805. /**
  87806. * Gets the list of all animation ranges defined on this skeleton
  87807. * @returns an array
  87808. */
  87809. Skeleton.prototype.getAnimationRanges = function () {
  87810. var animationRanges = [];
  87811. var name;
  87812. var i = 0;
  87813. for (name in this._ranges) {
  87814. animationRanges[i] = this._ranges[name];
  87815. i++;
  87816. }
  87817. return animationRanges;
  87818. };
  87819. /**
  87820. * Copy animation range from a source skeleton.
  87821. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  87822. * @param source defines the source skeleton
  87823. * @param name defines the name of the range to copy
  87824. * @param rescaleAsRequired defines if rescaling must be applied if required
  87825. * @returns true if operation was successful
  87826. */
  87827. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  87828. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87829. if (this._ranges[name] || !source.getAnimationRange(name)) {
  87830. return false;
  87831. }
  87832. var ret = true;
  87833. var frameOffset = this._getHighestAnimationFrame() + 1;
  87834. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  87835. var boneDict = {};
  87836. var sourceBones = source.bones;
  87837. var nBones;
  87838. var i;
  87839. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  87840. boneDict[sourceBones[i].name] = sourceBones[i];
  87841. }
  87842. if (this.bones.length !== sourceBones.length) {
  87843. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  87844. ret = false;
  87845. }
  87846. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  87847. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  87848. var boneName = this.bones[i].name;
  87849. var sourceBone = boneDict[boneName];
  87850. if (sourceBone) {
  87851. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  87852. }
  87853. else {
  87854. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  87855. ret = false;
  87856. }
  87857. }
  87858. // do not call createAnimationRange(), since it also is done to bones, which was already done
  87859. var range = source.getAnimationRange(name);
  87860. if (range) {
  87861. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  87862. }
  87863. return ret;
  87864. };
  87865. /**
  87866. * Forces the skeleton to go to rest pose
  87867. */
  87868. Skeleton.prototype.returnToRest = function () {
  87869. for (var index = 0; index < this.bones.length; index++) {
  87870. this.bones[index].returnToRest();
  87871. }
  87872. };
  87873. Skeleton.prototype._getHighestAnimationFrame = function () {
  87874. var ret = 0;
  87875. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  87876. if (this.bones[i].animations[0]) {
  87877. var highest = this.bones[i].animations[0].getHighestFrame();
  87878. if (ret < highest) {
  87879. ret = highest;
  87880. }
  87881. }
  87882. }
  87883. return ret;
  87884. };
  87885. /**
  87886. * Begin a specific animation range
  87887. * @param name defines the name of the range to start
  87888. * @param loop defines if looping must be turned on (false by default)
  87889. * @param speedRatio defines the speed ratio to apply (1 by default)
  87890. * @param onAnimationEnd defines a callback which will be called when animation will end
  87891. * @returns a new animatable
  87892. */
  87893. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  87894. var range = this.getAnimationRange(name);
  87895. if (!range) {
  87896. return null;
  87897. }
  87898. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  87899. };
  87900. /** @hidden */
  87901. Skeleton.prototype._markAsDirty = function () {
  87902. this._isDirty = true;
  87903. };
  87904. /** @hidden */
  87905. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  87906. this._meshesWithPoseMatrix.push(mesh);
  87907. };
  87908. /** @hidden */
  87909. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  87910. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  87911. if (index > -1) {
  87912. this._meshesWithPoseMatrix.splice(index, 1);
  87913. }
  87914. };
  87915. /** @hidden */
  87916. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  87917. this.onBeforeComputeObservable.notifyObservers(this);
  87918. for (var index = 0; index < this.bones.length; index++) {
  87919. var bone = this.bones[index];
  87920. var parentBone = bone.getParent();
  87921. if (parentBone) {
  87922. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  87923. }
  87924. else {
  87925. if (initialSkinMatrix) {
  87926. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  87927. }
  87928. else {
  87929. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  87930. }
  87931. }
  87932. if (bone._index !== -1) {
  87933. var mappedIndex = bone._index === null ? index : bone._index;
  87934. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  87935. }
  87936. }
  87937. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  87938. };
  87939. /**
  87940. * Build all resources required to render a skeleton
  87941. */
  87942. Skeleton.prototype.prepare = function () {
  87943. if (!this._isDirty) {
  87944. return;
  87945. }
  87946. if (this.needInitialSkinMatrix) {
  87947. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  87948. var mesh = this._meshesWithPoseMatrix[index];
  87949. var poseMatrix = mesh.getPoseMatrix();
  87950. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  87951. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  87952. }
  87953. if (this._synchronizedWithMesh !== mesh) {
  87954. this._synchronizedWithMesh = mesh;
  87955. // Prepare bones
  87956. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  87957. var bone = this.bones[boneIndex];
  87958. if (!bone.getParent()) {
  87959. var matrix = bone.getBaseMatrix();
  87960. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  87961. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  87962. }
  87963. }
  87964. }
  87965. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  87966. }
  87967. }
  87968. else {
  87969. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  87970. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  87971. }
  87972. this._computeTransformMatrices(this._transformMatrices, null);
  87973. }
  87974. this._isDirty = false;
  87975. this._scene._activeBones.addCount(this.bones.length, false);
  87976. };
  87977. /**
  87978. * Gets the list of animatables currently running for this skeleton
  87979. * @returns an array of animatables
  87980. */
  87981. Skeleton.prototype.getAnimatables = function () {
  87982. if (!this._animatables || this._animatables.length !== this.bones.length) {
  87983. this._animatables = [];
  87984. for (var index = 0; index < this.bones.length; index++) {
  87985. this._animatables.push(this.bones[index]);
  87986. }
  87987. }
  87988. return this._animatables;
  87989. };
  87990. /**
  87991. * Clone the current skeleton
  87992. * @param name defines the name of the new skeleton
  87993. * @param id defines the id of the enw skeleton
  87994. * @returns the new skeleton
  87995. */
  87996. Skeleton.prototype.clone = function (name, id) {
  87997. var result = new Skeleton(name, id || name, this._scene);
  87998. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  87999. for (var index = 0; index < this.bones.length; index++) {
  88000. var source = this.bones[index];
  88001. var parentBone = null;
  88002. var parent_1 = source.getParent();
  88003. if (parent_1) {
  88004. var parentIndex = this.bones.indexOf(parent_1);
  88005. parentBone = result.bones[parentIndex];
  88006. }
  88007. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  88008. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  88009. }
  88010. if (this._ranges) {
  88011. result._ranges = {};
  88012. for (var rangeName in this._ranges) {
  88013. var range = this._ranges[rangeName];
  88014. if (range) {
  88015. result._ranges[rangeName] = range.clone();
  88016. }
  88017. }
  88018. }
  88019. this._isDirty = true;
  88020. return result;
  88021. };
  88022. /**
  88023. * Enable animation blending for this skeleton
  88024. * @param blendingSpeed defines the blending speed to apply
  88025. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  88026. */
  88027. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  88028. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  88029. this.bones.forEach(function (bone) {
  88030. bone.animations.forEach(function (animation) {
  88031. animation.enableBlending = true;
  88032. animation.blendingSpeed = blendingSpeed;
  88033. });
  88034. });
  88035. };
  88036. /**
  88037. * Releases all resources associated with the current skeleton
  88038. */
  88039. Skeleton.prototype.dispose = function () {
  88040. this._meshesWithPoseMatrix = [];
  88041. // Animations
  88042. this.getScene().stopAnimation(this);
  88043. // Remove from scene
  88044. this.getScene().removeSkeleton(this);
  88045. };
  88046. /**
  88047. * Serialize the skeleton in a JSON object
  88048. * @returns a JSON object
  88049. */
  88050. Skeleton.prototype.serialize = function () {
  88051. var serializationObject = {};
  88052. serializationObject.name = this.name;
  88053. serializationObject.id = this.id;
  88054. if (this.dimensionsAtRest) {
  88055. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  88056. }
  88057. serializationObject.bones = [];
  88058. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88059. for (var index = 0; index < this.bones.length; index++) {
  88060. var bone = this.bones[index];
  88061. var parent_2 = bone.getParent();
  88062. var serializedBone = {
  88063. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  88064. name: bone.name,
  88065. matrix: bone.getBaseMatrix().toArray(),
  88066. rest: bone.getRestPose().toArray()
  88067. };
  88068. serializationObject.bones.push(serializedBone);
  88069. if (bone.length) {
  88070. serializedBone.length = bone.length;
  88071. }
  88072. if (bone.metadata) {
  88073. serializedBone.metadata = bone.metadata;
  88074. }
  88075. if (bone.animations && bone.animations.length > 0) {
  88076. serializedBone.animation = bone.animations[0].serialize();
  88077. }
  88078. serializationObject.ranges = [];
  88079. for (var name in this._ranges) {
  88080. var source = this._ranges[name];
  88081. if (!source) {
  88082. continue;
  88083. }
  88084. var range = {};
  88085. range.name = name;
  88086. range.from = source.from;
  88087. range.to = source.to;
  88088. serializationObject.ranges.push(range);
  88089. }
  88090. }
  88091. return serializationObject;
  88092. };
  88093. /**
  88094. * Creates a new skeleton from serialized data
  88095. * @param parsedSkeleton defines the serialized data
  88096. * @param scene defines the hosting scene
  88097. * @returns a new skeleton
  88098. */
  88099. Skeleton.Parse = function (parsedSkeleton, scene) {
  88100. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  88101. if (parsedSkeleton.dimensionsAtRest) {
  88102. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  88103. }
  88104. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  88105. var index;
  88106. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  88107. var parsedBone = parsedSkeleton.bones[index];
  88108. var parentBone = null;
  88109. if (parsedBone.parentBoneIndex > -1) {
  88110. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  88111. }
  88112. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  88113. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  88114. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  88115. bone.id = parsedBone.id;
  88116. }
  88117. if (parsedBone.length) {
  88118. bone.length = parsedBone.length;
  88119. }
  88120. if (parsedBone.metadata) {
  88121. bone.metadata = parsedBone.metadata;
  88122. }
  88123. if (parsedBone.animation) {
  88124. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  88125. }
  88126. }
  88127. // placed after bones, so createAnimationRange can cascade down
  88128. if (parsedSkeleton.ranges) {
  88129. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  88130. var data = parsedSkeleton.ranges[index];
  88131. skeleton.createAnimationRange(data.name, data.from, data.to);
  88132. }
  88133. }
  88134. return skeleton;
  88135. };
  88136. /**
  88137. * Compute all node absolute transforms
  88138. * @param forceUpdate defines if computation must be done even if cache is up to date
  88139. */
  88140. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  88141. if (forceUpdate === void 0) { forceUpdate = false; }
  88142. var renderId = this._scene.getRenderId();
  88143. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  88144. this.bones[0].computeAbsoluteTransforms();
  88145. this._lastAbsoluteTransformsUpdateId = renderId;
  88146. }
  88147. };
  88148. /**
  88149. * Gets the root pose matrix
  88150. * @returns a matrix
  88151. */
  88152. Skeleton.prototype.getPoseMatrix = function () {
  88153. var poseMatrix = null;
  88154. if (this._meshesWithPoseMatrix.length > 0) {
  88155. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  88156. }
  88157. return poseMatrix;
  88158. };
  88159. /**
  88160. * Sorts bones per internal index
  88161. */
  88162. Skeleton.prototype.sortBones = function () {
  88163. var bones = new Array();
  88164. var visited = new Array(this.bones.length);
  88165. for (var index = 0; index < this.bones.length; index++) {
  88166. this._sortBones(index, bones, visited);
  88167. }
  88168. this.bones = bones;
  88169. };
  88170. Skeleton.prototype._sortBones = function (index, bones, visited) {
  88171. if (visited[index]) {
  88172. return;
  88173. }
  88174. visited[index] = true;
  88175. var bone = this.bones[index];
  88176. if (bone._index === undefined) {
  88177. bone._index = index;
  88178. }
  88179. var parentBone = bone.getParent();
  88180. if (parentBone) {
  88181. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  88182. }
  88183. bones.push(bone);
  88184. };
  88185. return Skeleton;
  88186. }());
  88187. BABYLON.Skeleton = Skeleton;
  88188. })(BABYLON || (BABYLON = {}));
  88189. //# sourceMappingURL=babylon.skeleton.js.map
  88190. var BABYLON;
  88191. (function (BABYLON) {
  88192. ;
  88193. /**
  88194. * This groups tools to convert HDR texture to native colors array.
  88195. */
  88196. var HDRTools = /** @class */ (function () {
  88197. function HDRTools() {
  88198. }
  88199. HDRTools.Ldexp = function (mantissa, exponent) {
  88200. if (exponent > 1023) {
  88201. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  88202. }
  88203. if (exponent < -1074) {
  88204. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  88205. }
  88206. return mantissa * Math.pow(2, exponent);
  88207. };
  88208. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  88209. if (exponent > 0) { /*nonzero pixel*/
  88210. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  88211. float32array[index + 0] = red * exponent;
  88212. float32array[index + 1] = green * exponent;
  88213. float32array[index + 2] = blue * exponent;
  88214. }
  88215. else {
  88216. float32array[index + 0] = 0;
  88217. float32array[index + 1] = 0;
  88218. float32array[index + 2] = 0;
  88219. }
  88220. };
  88221. HDRTools.readStringLine = function (uint8array, startIndex) {
  88222. var line = "";
  88223. var character = "";
  88224. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  88225. character = String.fromCharCode(uint8array[i]);
  88226. if (character == "\n") {
  88227. break;
  88228. }
  88229. line += character;
  88230. }
  88231. return line;
  88232. };
  88233. /**
  88234. * Reads header information from an RGBE texture stored in a native array.
  88235. * More information on this format are available here:
  88236. * https://en.wikipedia.org/wiki/RGBE_image_format
  88237. *
  88238. * @param uint8array The binary file stored in native array.
  88239. * @return The header information.
  88240. */
  88241. HDRTools.RGBE_ReadHeader = function (uint8array) {
  88242. var height = 0;
  88243. var width = 0;
  88244. var line = this.readStringLine(uint8array, 0);
  88245. if (line[0] != '#' || line[1] != '?') {
  88246. throw "Bad HDR Format.";
  88247. }
  88248. var endOfHeader = false;
  88249. var findFormat = false;
  88250. var lineIndex = 0;
  88251. do {
  88252. lineIndex += (line.length + 1);
  88253. line = this.readStringLine(uint8array, lineIndex);
  88254. if (line == "FORMAT=32-bit_rle_rgbe") {
  88255. findFormat = true;
  88256. }
  88257. else if (line.length == 0) {
  88258. endOfHeader = true;
  88259. }
  88260. } while (!endOfHeader);
  88261. if (!findFormat) {
  88262. throw "HDR Bad header format, unsupported FORMAT";
  88263. }
  88264. lineIndex += (line.length + 1);
  88265. line = this.readStringLine(uint8array, lineIndex);
  88266. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  88267. var match = sizeRegexp.exec(line);
  88268. // TODO. Support +Y and -X if needed.
  88269. if (!match || match.length < 3) {
  88270. throw "HDR Bad header format, no size";
  88271. }
  88272. width = parseInt(match[2]);
  88273. height = parseInt(match[1]);
  88274. if (width < 8 || width > 0x7fff) {
  88275. throw "HDR Bad header format, unsupported size";
  88276. }
  88277. lineIndex += (line.length + 1);
  88278. return {
  88279. height: height,
  88280. width: width,
  88281. dataPosition: lineIndex
  88282. };
  88283. };
  88284. /**
  88285. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  88286. * This RGBE texture needs to store the information as a panorama.
  88287. *
  88288. * More information on this format are available here:
  88289. * https://en.wikipedia.org/wiki/RGBE_image_format
  88290. *
  88291. * @param buffer The binary file stored in an array buffer.
  88292. * @param size The expected size of the extracted cubemap.
  88293. * @return The Cube Map information.
  88294. */
  88295. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  88296. var uint8array = new Uint8Array(buffer);
  88297. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  88298. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  88299. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  88300. return cubeMapData;
  88301. };
  88302. /**
  88303. * Returns the pixels data extracted from an RGBE texture.
  88304. * This pixels will be stored left to right up to down in the R G B order in one array.
  88305. *
  88306. * More information on this format are available here:
  88307. * https://en.wikipedia.org/wiki/RGBE_image_format
  88308. *
  88309. * @param uint8array The binary file stored in an array buffer.
  88310. * @param hdrInfo The header information of the file.
  88311. * @return The pixels data in RGB right to left up to down order.
  88312. */
  88313. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  88314. // Keep for multi format supports.
  88315. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  88316. };
  88317. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  88318. var num_scanlines = hdrInfo.height;
  88319. var scanline_width = hdrInfo.width;
  88320. var a, b, c, d, count;
  88321. var dataIndex = hdrInfo.dataPosition;
  88322. var index = 0, endIndex = 0, i = 0;
  88323. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  88324. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  88325. // 3 channels of 4 bytes per pixel in float.
  88326. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  88327. var resultArray = new Float32Array(resultBuffer);
  88328. // read in each successive scanline
  88329. while (num_scanlines > 0) {
  88330. a = uint8array[dataIndex++];
  88331. b = uint8array[dataIndex++];
  88332. c = uint8array[dataIndex++];
  88333. d = uint8array[dataIndex++];
  88334. if (a != 2 || b != 2 || (c & 0x80)) {
  88335. // this file is not run length encoded
  88336. throw "HDR Bad header format, not RLE";
  88337. }
  88338. if (((c << 8) | d) != scanline_width) {
  88339. throw "HDR Bad header format, wrong scan line width";
  88340. }
  88341. index = 0;
  88342. // read each of the four channels for the scanline into the buffer
  88343. for (i = 0; i < 4; i++) {
  88344. endIndex = (i + 1) * scanline_width;
  88345. while (index < endIndex) {
  88346. a = uint8array[dataIndex++];
  88347. b = uint8array[dataIndex++];
  88348. if (a > 128) {
  88349. // a run of the same value
  88350. count = a - 128;
  88351. if ((count == 0) || (count > endIndex - index)) {
  88352. throw "HDR Bad Format, bad scanline data (run)";
  88353. }
  88354. while (count-- > 0) {
  88355. scanLineArray[index++] = b;
  88356. }
  88357. }
  88358. else {
  88359. // a non-run
  88360. count = a;
  88361. if ((count == 0) || (count > endIndex - index)) {
  88362. throw "HDR Bad Format, bad scanline data (non-run)";
  88363. }
  88364. scanLineArray[index++] = b;
  88365. if (--count > 0) {
  88366. for (var j = 0; j < count; j++) {
  88367. scanLineArray[index++] = uint8array[dataIndex++];
  88368. }
  88369. }
  88370. }
  88371. }
  88372. }
  88373. // now convert data from buffer into floats
  88374. for (i = 0; i < scanline_width; i++) {
  88375. a = scanLineArray[i];
  88376. b = scanLineArray[i + scanline_width];
  88377. c = scanLineArray[i + 2 * scanline_width];
  88378. d = scanLineArray[i + 3 * scanline_width];
  88379. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  88380. }
  88381. num_scanlines--;
  88382. }
  88383. return resultArray;
  88384. };
  88385. return HDRTools;
  88386. }());
  88387. BABYLON.HDRTools = HDRTools;
  88388. })(BABYLON || (BABYLON = {}));
  88389. //# sourceMappingURL=babylon.hdr.js.map
  88390. var BABYLON;
  88391. (function (BABYLON) {
  88392. /**
  88393. * This represents a texture coming from an HDR input.
  88394. *
  88395. * The only supported format is currently panorama picture stored in RGBE format.
  88396. * Example of such files can be found on HDRLib: http://hdrlib.com/
  88397. */
  88398. var HDRCubeTexture = /** @class */ (function (_super) {
  88399. __extends(HDRCubeTexture, _super);
  88400. /**
  88401. * Instantiates an HDRTexture from the following parameters.
  88402. *
  88403. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  88404. * @param scene The scene the texture will be used in
  88405. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  88406. * @param noMipmap Forces to not generate the mipmap if true
  88407. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  88408. * @param gammaSpace 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)
  88409. * @param reserved Reserved flag for internal use.
  88410. */
  88411. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  88412. if (noMipmap === void 0) { noMipmap = false; }
  88413. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88414. if (gammaSpace === void 0) { gammaSpace = false; }
  88415. if (reserved === void 0) { reserved = false; }
  88416. if (onLoad === void 0) { onLoad = null; }
  88417. if (onError === void 0) { onError = null; }
  88418. var _this = _super.call(this, scene) || this;
  88419. _this._generateHarmonics = true;
  88420. _this._onLoad = null;
  88421. _this._onError = null;
  88422. /**
  88423. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  88424. */
  88425. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  88426. _this._isBlocking = true;
  88427. _this._rotationY = 0;
  88428. /**
  88429. * Gets or sets the center of the bounding box associated with the cube texture
  88430. * It must define where the camera used to render the texture was set
  88431. */
  88432. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  88433. if (!url) {
  88434. return _this;
  88435. }
  88436. _this.name = url;
  88437. _this.url = url;
  88438. _this.hasAlpha = false;
  88439. _this.isCube = true;
  88440. _this._textureMatrix = BABYLON.Matrix.Identity();
  88441. _this._onLoad = onLoad;
  88442. _this._onError = onError;
  88443. _this.gammaSpace = gammaSpace;
  88444. _this._noMipmap = noMipmap;
  88445. _this._size = size;
  88446. _this._texture = _this._getFromCache(url, _this._noMipmap);
  88447. if (!_this._texture) {
  88448. if (!scene.useDelayedTextureLoading) {
  88449. _this.loadTexture();
  88450. }
  88451. else {
  88452. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  88453. }
  88454. }
  88455. return _this;
  88456. }
  88457. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  88458. /**
  88459. * Gets wether or not the texture is blocking during loading.
  88460. */
  88461. get: function () {
  88462. return this._isBlocking;
  88463. },
  88464. /**
  88465. * Sets wether or not the texture is blocking during loading.
  88466. */
  88467. set: function (value) {
  88468. this._isBlocking = value;
  88469. },
  88470. enumerable: true,
  88471. configurable: true
  88472. });
  88473. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  88474. /**
  88475. * Gets texture matrix rotation angle around Y axis radians.
  88476. */
  88477. get: function () {
  88478. return this._rotationY;
  88479. },
  88480. /**
  88481. * Sets texture matrix rotation angle around Y axis in radians.
  88482. */
  88483. set: function (value) {
  88484. this._rotationY = value;
  88485. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  88486. },
  88487. enumerable: true,
  88488. configurable: true
  88489. });
  88490. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  88491. get: function () {
  88492. return this._boundingBoxSize;
  88493. },
  88494. /**
  88495. * Gets or sets the size of the bounding box associated with the cube texture
  88496. * When defined, the cubemap will switch to local mode
  88497. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  88498. * @example https://www.babylonjs-playground.com/#RNASML
  88499. */
  88500. set: function (value) {
  88501. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  88502. return;
  88503. }
  88504. this._boundingBoxSize = value;
  88505. var scene = this.getScene();
  88506. if (scene) {
  88507. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  88508. }
  88509. },
  88510. enumerable: true,
  88511. configurable: true
  88512. });
  88513. /**
  88514. * Occurs when the file is raw .hdr file.
  88515. */
  88516. HDRCubeTexture.prototype.loadTexture = function () {
  88517. var _this = this;
  88518. var callback = function (buffer) {
  88519. _this.lodGenerationOffset = 0.0;
  88520. _this.lodGenerationScale = 0.8;
  88521. var scene = _this.getScene();
  88522. if (!scene) {
  88523. return null;
  88524. }
  88525. // Extract the raw linear data.
  88526. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  88527. // Generate harmonics if needed.
  88528. if (_this._generateHarmonics) {
  88529. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  88530. _this.sphericalPolynomial = sphericalPolynomial;
  88531. }
  88532. var results = [];
  88533. var byteArray = null;
  88534. // Push each faces.
  88535. for (var j = 0; j < 6; j++) {
  88536. // Create uintarray fallback.
  88537. if (!scene.getEngine().getCaps().textureFloat) {
  88538. // 3 channels of 1 bytes per pixel in bytes.
  88539. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  88540. byteArray = new Uint8Array(byteBuffer);
  88541. }
  88542. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  88543. // If special cases.
  88544. if (_this.gammaSpace || byteArray) {
  88545. for (var i = 0; i < _this._size * _this._size; i++) {
  88546. // Put in gamma space if requested.
  88547. if (_this.gammaSpace) {
  88548. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  88549. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  88550. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  88551. }
  88552. // Convert to int texture for fallback.
  88553. if (byteArray) {
  88554. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  88555. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  88556. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  88557. // May use luminance instead if the result is not accurate.
  88558. var max = Math.max(Math.max(r, g), b);
  88559. if (max > 255) {
  88560. var scale = 255 / max;
  88561. r *= scale;
  88562. g *= scale;
  88563. b *= scale;
  88564. }
  88565. byteArray[(i * 3) + 0] = r;
  88566. byteArray[(i * 3) + 1] = g;
  88567. byteArray[(i * 3) + 2] = b;
  88568. }
  88569. }
  88570. }
  88571. if (byteArray) {
  88572. results.push(byteArray);
  88573. }
  88574. else {
  88575. results.push(dataFace);
  88576. }
  88577. }
  88578. return results;
  88579. };
  88580. var scene = this.getScene();
  88581. if (scene) {
  88582. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  88583. }
  88584. };
  88585. HDRCubeTexture.prototype.clone = function () {
  88586. var scene = this.getScene();
  88587. if (!scene) {
  88588. return this;
  88589. }
  88590. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  88591. // Base texture
  88592. newTexture.level = this.level;
  88593. newTexture.wrapU = this.wrapU;
  88594. newTexture.wrapV = this.wrapV;
  88595. newTexture.coordinatesIndex = this.coordinatesIndex;
  88596. newTexture.coordinatesMode = this.coordinatesMode;
  88597. return newTexture;
  88598. };
  88599. // Methods
  88600. HDRCubeTexture.prototype.delayLoad = function () {
  88601. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88602. return;
  88603. }
  88604. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88605. this._texture = this._getFromCache(this.url, this._noMipmap);
  88606. if (!this._texture) {
  88607. this.loadTexture();
  88608. }
  88609. };
  88610. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  88611. return this._textureMatrix;
  88612. };
  88613. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  88614. this._textureMatrix = value;
  88615. };
  88616. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88617. var texture = null;
  88618. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88619. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  88620. texture.name = parsedTexture.name;
  88621. texture.hasAlpha = parsedTexture.hasAlpha;
  88622. texture.level = parsedTexture.level;
  88623. texture.coordinatesMode = parsedTexture.coordinatesMode;
  88624. texture.isBlocking = parsedTexture.isBlocking;
  88625. }
  88626. if (texture) {
  88627. if (parsedTexture.boundingBoxPosition) {
  88628. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  88629. }
  88630. if (parsedTexture.boundingBoxSize) {
  88631. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  88632. }
  88633. if (parsedTexture.rotationY) {
  88634. texture.rotationY = parsedTexture.rotationY;
  88635. }
  88636. }
  88637. return texture;
  88638. };
  88639. HDRCubeTexture.prototype.serialize = function () {
  88640. if (!this.name) {
  88641. return null;
  88642. }
  88643. var serializationObject = {};
  88644. serializationObject.name = this.name;
  88645. serializationObject.hasAlpha = this.hasAlpha;
  88646. serializationObject.isCube = true;
  88647. serializationObject.level = this.level;
  88648. serializationObject.size = this._size;
  88649. serializationObject.coordinatesMode = this.coordinatesMode;
  88650. serializationObject.useInGammaSpace = this.gammaSpace;
  88651. serializationObject.generateHarmonics = this._generateHarmonics;
  88652. serializationObject.customType = "BABYLON.HDRCubeTexture";
  88653. serializationObject.noMipmap = this._noMipmap;
  88654. serializationObject.isBlocking = this._isBlocking;
  88655. serializationObject.rotationY = this._rotationY;
  88656. return serializationObject;
  88657. };
  88658. HDRCubeTexture._facesMapping = [
  88659. "right",
  88660. "left",
  88661. "up",
  88662. "down",
  88663. "front",
  88664. "back"
  88665. ];
  88666. return HDRCubeTexture;
  88667. }(BABYLON.BaseTexture));
  88668. BABYLON.HDRCubeTexture = HDRCubeTexture;
  88669. })(BABYLON || (BABYLON = {}));
  88670. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  88671. var BABYLON;
  88672. (function (BABYLON) {
  88673. /**
  88674. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  88675. */
  88676. var PanoramaToCubeMapTools = /** @class */ (function () {
  88677. function PanoramaToCubeMapTools() {
  88678. }
  88679. /**
  88680. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  88681. *
  88682. * @param float32Array The source data.
  88683. * @param inputWidth The width of the input panorama.
  88684. * @param inputhHeight The height of the input panorama.
  88685. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  88686. * @return The cubemap data
  88687. */
  88688. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  88689. if (!float32Array) {
  88690. throw "ConvertPanoramaToCubemap: input cannot be null";
  88691. }
  88692. if (float32Array.length != inputWidth * inputHeight * 3) {
  88693. throw "ConvertPanoramaToCubemap: input size is wrong";
  88694. }
  88695. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  88696. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  88697. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  88698. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  88699. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  88700. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  88701. return {
  88702. front: textureFront,
  88703. back: textureBack,
  88704. left: textureLeft,
  88705. right: textureRight,
  88706. up: textureUp,
  88707. down: textureDown,
  88708. size: size,
  88709. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88710. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  88711. gammaSpace: false,
  88712. };
  88713. };
  88714. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  88715. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  88716. var textureArray = new Float32Array(buffer);
  88717. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  88718. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  88719. var dy = 1 / texSize;
  88720. var fy = 0;
  88721. for (var y = 0; y < texSize; y++) {
  88722. var xv1 = faceData[0];
  88723. var xv2 = faceData[2];
  88724. for (var x = 0; x < texSize; x++) {
  88725. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  88726. v.normalize();
  88727. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  88728. // 3 channels per pixels
  88729. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  88730. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  88731. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  88732. xv1 = xv1.add(rotDX1);
  88733. xv2 = xv2.add(rotDX2);
  88734. }
  88735. fy += dy;
  88736. }
  88737. return textureArray;
  88738. };
  88739. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  88740. var theta = Math.atan2(vDir.z, vDir.x);
  88741. var phi = Math.acos(vDir.y);
  88742. while (theta < -Math.PI)
  88743. theta += 2 * Math.PI;
  88744. while (theta > Math.PI)
  88745. theta -= 2 * Math.PI;
  88746. var dx = theta / Math.PI;
  88747. var dy = phi / Math.PI;
  88748. // recenter.
  88749. dx = dx * 0.5 + 0.5;
  88750. var px = Math.round(dx * inputWidth);
  88751. if (px < 0)
  88752. px = 0;
  88753. else if (px >= inputWidth)
  88754. px = inputWidth - 1;
  88755. var py = Math.round(dy * inputHeight);
  88756. if (py < 0)
  88757. py = 0;
  88758. else if (py >= inputHeight)
  88759. py = inputHeight - 1;
  88760. var inputY = (inputHeight - py - 1);
  88761. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  88762. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  88763. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  88764. return {
  88765. r: r,
  88766. g: g,
  88767. b: b
  88768. };
  88769. };
  88770. PanoramaToCubeMapTools.FACE_FRONT = [
  88771. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88772. new BABYLON.Vector3(1.0, -1.0, -1.0),
  88773. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  88774. new BABYLON.Vector3(1.0, 1.0, -1.0)
  88775. ];
  88776. PanoramaToCubeMapTools.FACE_BACK = [
  88777. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88778. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88779. new BABYLON.Vector3(1.0, 1.0, 1.0),
  88780. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  88781. ];
  88782. PanoramaToCubeMapTools.FACE_RIGHT = [
  88783. new BABYLON.Vector3(1.0, -1.0, -1.0),
  88784. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88785. new BABYLON.Vector3(1.0, 1.0, -1.0),
  88786. new BABYLON.Vector3(1.0, 1.0, 1.0)
  88787. ];
  88788. PanoramaToCubeMapTools.FACE_LEFT = [
  88789. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88790. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88791. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  88792. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  88793. ];
  88794. PanoramaToCubeMapTools.FACE_DOWN = [
  88795. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  88796. new BABYLON.Vector3(1.0, 1.0, -1.0),
  88797. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  88798. new BABYLON.Vector3(1.0, 1.0, 1.0)
  88799. ];
  88800. PanoramaToCubeMapTools.FACE_UP = [
  88801. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88802. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88803. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88804. new BABYLON.Vector3(1.0, -1.0, -1.0)
  88805. ];
  88806. return PanoramaToCubeMapTools;
  88807. }());
  88808. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  88809. })(BABYLON || (BABYLON = {}));
  88810. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  88811. var BABYLON;
  88812. (function (BABYLON) {
  88813. var IndexedVector2 = /** @class */ (function (_super) {
  88814. __extends(IndexedVector2, _super);
  88815. function IndexedVector2(original, index) {
  88816. var _this = _super.call(this, original.x, original.y) || this;
  88817. _this.index = index;
  88818. return _this;
  88819. }
  88820. return IndexedVector2;
  88821. }(BABYLON.Vector2));
  88822. var PolygonPoints = /** @class */ (function () {
  88823. function PolygonPoints() {
  88824. this.elements = new Array();
  88825. }
  88826. PolygonPoints.prototype.add = function (originalPoints) {
  88827. var _this = this;
  88828. var result = new Array();
  88829. originalPoints.forEach(function (point) {
  88830. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  88831. var newPoint = new IndexedVector2(point, _this.elements.length);
  88832. result.push(newPoint);
  88833. _this.elements.push(newPoint);
  88834. }
  88835. });
  88836. return result;
  88837. };
  88838. PolygonPoints.prototype.computeBounds = function () {
  88839. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  88840. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  88841. this.elements.forEach(function (point) {
  88842. // x
  88843. if (point.x < lmin.x) {
  88844. lmin.x = point.x;
  88845. }
  88846. else if (point.x > lmax.x) {
  88847. lmax.x = point.x;
  88848. }
  88849. // y
  88850. if (point.y < lmin.y) {
  88851. lmin.y = point.y;
  88852. }
  88853. else if (point.y > lmax.y) {
  88854. lmax.y = point.y;
  88855. }
  88856. });
  88857. return {
  88858. min: lmin,
  88859. max: lmax,
  88860. width: lmax.x - lmin.x,
  88861. height: lmax.y - lmin.y
  88862. };
  88863. };
  88864. return PolygonPoints;
  88865. }());
  88866. var Polygon = /** @class */ (function () {
  88867. function Polygon() {
  88868. }
  88869. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  88870. return [
  88871. new BABYLON.Vector2(xmin, ymin),
  88872. new BABYLON.Vector2(xmax, ymin),
  88873. new BABYLON.Vector2(xmax, ymax),
  88874. new BABYLON.Vector2(xmin, ymax)
  88875. ];
  88876. };
  88877. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  88878. if (cx === void 0) { cx = 0; }
  88879. if (cy === void 0) { cy = 0; }
  88880. if (numberOfSides === void 0) { numberOfSides = 32; }
  88881. var result = new Array();
  88882. var angle = 0;
  88883. var increment = (Math.PI * 2) / numberOfSides;
  88884. for (var i = 0; i < numberOfSides; i++) {
  88885. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  88886. angle -= increment;
  88887. }
  88888. return result;
  88889. };
  88890. Polygon.Parse = function (input) {
  88891. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  88892. var i, result = [];
  88893. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  88894. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  88895. }
  88896. return result;
  88897. };
  88898. Polygon.StartingAt = function (x, y) {
  88899. return BABYLON.Path2.StartingAt(x, y);
  88900. };
  88901. return Polygon;
  88902. }());
  88903. BABYLON.Polygon = Polygon;
  88904. var PolygonMeshBuilder = /** @class */ (function () {
  88905. function PolygonMeshBuilder(name, contours, scene) {
  88906. this._points = new PolygonPoints();
  88907. this._outlinepoints = new PolygonPoints();
  88908. this._holes = new Array();
  88909. this._epoints = new Array();
  88910. this._eholes = new Array();
  88911. this._name = name;
  88912. this._scene = scene;
  88913. var points;
  88914. if (contours instanceof BABYLON.Path2) {
  88915. points = contours.getPoints();
  88916. }
  88917. else {
  88918. points = contours;
  88919. }
  88920. this._addToepoint(points);
  88921. this._points.add(points);
  88922. this._outlinepoints.add(points);
  88923. if (typeof earcut === 'undefined') {
  88924. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  88925. }
  88926. }
  88927. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  88928. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  88929. var p = points_1[_i];
  88930. this._epoints.push(p.x, p.y);
  88931. }
  88932. };
  88933. PolygonMeshBuilder.prototype.addHole = function (hole) {
  88934. this._points.add(hole);
  88935. var holepoints = new PolygonPoints();
  88936. holepoints.add(hole);
  88937. this._holes.push(holepoints);
  88938. this._eholes.push(this._epoints.length / 2);
  88939. this._addToepoint(hole);
  88940. return this;
  88941. };
  88942. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  88943. var _this = this;
  88944. if (updatable === void 0) { updatable = false; }
  88945. if (depth === void 0) { depth = 0; }
  88946. var result = new BABYLON.Mesh(this._name, this._scene);
  88947. var normals = new Array();
  88948. var positions = new Array();
  88949. var uvs = new Array();
  88950. var bounds = this._points.computeBounds();
  88951. this._points.elements.forEach(function (p) {
  88952. normals.push(0, 1.0, 0);
  88953. positions.push(p.x, 0, p.y);
  88954. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  88955. });
  88956. var indices = new Array();
  88957. var res = earcut(this._epoints, this._eholes, 2);
  88958. for (var i = 0; i < res.length; i++) {
  88959. indices.push(res[i]);
  88960. }
  88961. if (depth > 0) {
  88962. var positionscount = (positions.length / 3); //get the current pointcount
  88963. this._points.elements.forEach(function (p) {
  88964. normals.push(0, -1.0, 0);
  88965. positions.push(p.x, -depth, p.y);
  88966. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  88967. });
  88968. var totalCount = indices.length;
  88969. for (var i = 0; i < totalCount; i += 3) {
  88970. var i0 = indices[i + 0];
  88971. var i1 = indices[i + 1];
  88972. var i2 = indices[i + 2];
  88973. indices.push(i2 + positionscount);
  88974. indices.push(i1 + positionscount);
  88975. indices.push(i0 + positionscount);
  88976. }
  88977. //Add the sides
  88978. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  88979. this._holes.forEach(function (hole) {
  88980. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  88981. });
  88982. }
  88983. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  88984. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  88985. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  88986. result.setIndices(indices);
  88987. return result;
  88988. };
  88989. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  88990. var StartIndex = positions.length / 3;
  88991. var ulength = 0;
  88992. for (var i = 0; i < points.elements.length; i++) {
  88993. var p = points.elements[i];
  88994. var p1;
  88995. if ((i + 1) > points.elements.length - 1) {
  88996. p1 = points.elements[0];
  88997. }
  88998. else {
  88999. p1 = points.elements[i + 1];
  89000. }
  89001. positions.push(p.x, 0, p.y);
  89002. positions.push(p.x, -depth, p.y);
  89003. positions.push(p1.x, 0, p1.y);
  89004. positions.push(p1.x, -depth, p1.y);
  89005. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  89006. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  89007. var v3 = v2.subtract(v1);
  89008. var v4 = new BABYLON.Vector3(0, 1, 0);
  89009. var vn = BABYLON.Vector3.Cross(v3, v4);
  89010. vn = vn.normalize();
  89011. uvs.push(ulength / bounds.width, 0);
  89012. uvs.push(ulength / bounds.width, 1);
  89013. ulength += v3.length();
  89014. uvs.push((ulength / bounds.width), 0);
  89015. uvs.push((ulength / bounds.width), 1);
  89016. if (!flip) {
  89017. normals.push(-vn.x, -vn.y, -vn.z);
  89018. normals.push(-vn.x, -vn.y, -vn.z);
  89019. normals.push(-vn.x, -vn.y, -vn.z);
  89020. normals.push(-vn.x, -vn.y, -vn.z);
  89021. indices.push(StartIndex);
  89022. indices.push(StartIndex + 1);
  89023. indices.push(StartIndex + 2);
  89024. indices.push(StartIndex + 1);
  89025. indices.push(StartIndex + 3);
  89026. indices.push(StartIndex + 2);
  89027. }
  89028. else {
  89029. normals.push(vn.x, vn.y, vn.z);
  89030. normals.push(vn.x, vn.y, vn.z);
  89031. normals.push(vn.x, vn.y, vn.z);
  89032. normals.push(vn.x, vn.y, vn.z);
  89033. indices.push(StartIndex);
  89034. indices.push(StartIndex + 2);
  89035. indices.push(StartIndex + 1);
  89036. indices.push(StartIndex + 1);
  89037. indices.push(StartIndex + 2);
  89038. indices.push(StartIndex + 3);
  89039. }
  89040. StartIndex += 4;
  89041. }
  89042. ;
  89043. };
  89044. return PolygonMeshBuilder;
  89045. }());
  89046. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  89047. })(BABYLON || (BABYLON = {}));
  89048. //# sourceMappingURL=babylon.polygonMesh.js.map
  89049. var BABYLON;
  89050. (function (BABYLON) {
  89051. // Unique ID when we import meshes from Babylon to CSG
  89052. var currentCSGMeshId = 0;
  89053. // # class Vertex
  89054. // Represents a vertex of a polygon. Use your own vertex class instead of this
  89055. // one to provide additional features like texture coordinates and vertex
  89056. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  89057. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  89058. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  89059. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  89060. // is not used anywhere else.
  89061. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  89062. var Vertex = /** @class */ (function () {
  89063. function Vertex(pos, normal, uv) {
  89064. this.pos = pos;
  89065. this.normal = normal;
  89066. this.uv = uv;
  89067. }
  89068. Vertex.prototype.clone = function () {
  89069. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  89070. };
  89071. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  89072. // orientation of a polygon is flipped.
  89073. Vertex.prototype.flip = function () {
  89074. this.normal = this.normal.scale(-1);
  89075. };
  89076. // Create a new vertex between this vertex and `other` by linearly
  89077. // interpolating all properties using a parameter of `t`. Subclasses should
  89078. // override this to interpolate additional properties.
  89079. Vertex.prototype.interpolate = function (other, t) {
  89080. 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));
  89081. };
  89082. return Vertex;
  89083. }());
  89084. // # class Plane
  89085. // Represents a plane in 3D space.
  89086. var Plane = /** @class */ (function () {
  89087. function Plane(normal, w) {
  89088. this.normal = normal;
  89089. this.w = w;
  89090. }
  89091. Plane.FromPoints = function (a, b, c) {
  89092. var v0 = c.subtract(a);
  89093. var v1 = b.subtract(a);
  89094. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  89095. return null;
  89096. }
  89097. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  89098. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  89099. };
  89100. Plane.prototype.clone = function () {
  89101. return new Plane(this.normal.clone(), this.w);
  89102. };
  89103. Plane.prototype.flip = function () {
  89104. this.normal.scaleInPlace(-1);
  89105. this.w = -this.w;
  89106. };
  89107. // Split `polygon` by this plane if needed, then put the polygon or polygon
  89108. // fragments in the appropriate lists. Coplanar polygons go into either
  89109. // `coplanarFront` or `coplanarBack` depending on their orientation with
  89110. // respect to this plane. Polygons in front or in back of this plane go into
  89111. // either `front` or `back`.
  89112. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  89113. var COPLANAR = 0;
  89114. var FRONT = 1;
  89115. var BACK = 2;
  89116. var SPANNING = 3;
  89117. // Classify each point as well as the entire polygon into one of the above
  89118. // four classes.
  89119. var polygonType = 0;
  89120. var types = [];
  89121. var i;
  89122. var t;
  89123. for (i = 0; i < polygon.vertices.length; i++) {
  89124. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  89125. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  89126. polygonType |= type;
  89127. types.push(type);
  89128. }
  89129. // Put the polygon in the correct list, splitting it when necessary.
  89130. switch (polygonType) {
  89131. case COPLANAR:
  89132. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  89133. break;
  89134. case FRONT:
  89135. front.push(polygon);
  89136. break;
  89137. case BACK:
  89138. back.push(polygon);
  89139. break;
  89140. case SPANNING:
  89141. var f = [], b = [];
  89142. for (i = 0; i < polygon.vertices.length; i++) {
  89143. var j = (i + 1) % polygon.vertices.length;
  89144. var ti = types[i], tj = types[j];
  89145. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  89146. if (ti !== BACK)
  89147. f.push(vi);
  89148. if (ti !== FRONT)
  89149. b.push(ti !== BACK ? vi.clone() : vi);
  89150. if ((ti | tj) === SPANNING) {
  89151. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  89152. var v = vi.interpolate(vj, t);
  89153. f.push(v);
  89154. b.push(v.clone());
  89155. }
  89156. }
  89157. var poly;
  89158. if (f.length >= 3) {
  89159. poly = new Polygon(f, polygon.shared);
  89160. if (poly.plane)
  89161. front.push(poly);
  89162. }
  89163. if (b.length >= 3) {
  89164. poly = new Polygon(b, polygon.shared);
  89165. if (poly.plane)
  89166. back.push(poly);
  89167. }
  89168. break;
  89169. }
  89170. };
  89171. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  89172. // point is on the plane.
  89173. Plane.EPSILON = 1e-5;
  89174. return Plane;
  89175. }());
  89176. // # class Polygon
  89177. // Represents a convex polygon. The vertices used to initialize a polygon must
  89178. // be coplanar and form a convex loop.
  89179. //
  89180. // Each convex polygon has a `shared` property, which is shared between all
  89181. // polygons that are clones of each other or were split from the same polygon.
  89182. // This can be used to define per-polygon properties (such as surface color).
  89183. var Polygon = /** @class */ (function () {
  89184. function Polygon(vertices, shared) {
  89185. this.vertices = vertices;
  89186. this.shared = shared;
  89187. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  89188. }
  89189. Polygon.prototype.clone = function () {
  89190. var vertices = this.vertices.map(function (v) { return v.clone(); });
  89191. return new Polygon(vertices, this.shared);
  89192. };
  89193. Polygon.prototype.flip = function () {
  89194. this.vertices.reverse().map(function (v) { v.flip(); });
  89195. this.plane.flip();
  89196. };
  89197. return Polygon;
  89198. }());
  89199. // # class Node
  89200. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  89201. // by picking a polygon to split along. That polygon (and all other coplanar
  89202. // polygons) are added directly to that node and the other polygons are added to
  89203. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  89204. // no distinction between internal and leaf nodes.
  89205. var Node = /** @class */ (function () {
  89206. function Node(polygons) {
  89207. this.plane = null;
  89208. this.front = null;
  89209. this.back = null;
  89210. this.polygons = new Array();
  89211. if (polygons) {
  89212. this.build(polygons);
  89213. }
  89214. }
  89215. Node.prototype.clone = function () {
  89216. var node = new Node();
  89217. node.plane = this.plane && this.plane.clone();
  89218. node.front = this.front && this.front.clone();
  89219. node.back = this.back && this.back.clone();
  89220. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  89221. return node;
  89222. };
  89223. // Convert solid space to empty space and empty space to solid space.
  89224. Node.prototype.invert = function () {
  89225. for (var i = 0; i < this.polygons.length; i++) {
  89226. this.polygons[i].flip();
  89227. }
  89228. if (this.plane) {
  89229. this.plane.flip();
  89230. }
  89231. if (this.front) {
  89232. this.front.invert();
  89233. }
  89234. if (this.back) {
  89235. this.back.invert();
  89236. }
  89237. var temp = this.front;
  89238. this.front = this.back;
  89239. this.back = temp;
  89240. };
  89241. // Recursively remove all polygons in `polygons` that are inside this BSP
  89242. // tree.
  89243. Node.prototype.clipPolygons = function (polygons) {
  89244. if (!this.plane)
  89245. return polygons.slice();
  89246. var front = new Array(), back = new Array();
  89247. for (var i = 0; i < polygons.length; i++) {
  89248. this.plane.splitPolygon(polygons[i], front, back, front, back);
  89249. }
  89250. if (this.front) {
  89251. front = this.front.clipPolygons(front);
  89252. }
  89253. if (this.back) {
  89254. back = this.back.clipPolygons(back);
  89255. }
  89256. else {
  89257. back = [];
  89258. }
  89259. return front.concat(back);
  89260. };
  89261. // Remove all polygons in this BSP tree that are inside the other BSP tree
  89262. // `bsp`.
  89263. Node.prototype.clipTo = function (bsp) {
  89264. this.polygons = bsp.clipPolygons(this.polygons);
  89265. if (this.front)
  89266. this.front.clipTo(bsp);
  89267. if (this.back)
  89268. this.back.clipTo(bsp);
  89269. };
  89270. // Return a list of all polygons in this BSP tree.
  89271. Node.prototype.allPolygons = function () {
  89272. var polygons = this.polygons.slice();
  89273. if (this.front)
  89274. polygons = polygons.concat(this.front.allPolygons());
  89275. if (this.back)
  89276. polygons = polygons.concat(this.back.allPolygons());
  89277. return polygons;
  89278. };
  89279. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  89280. // new polygons are filtered down to the bottom of the tree and become new
  89281. // nodes there. Each set of polygons is partitioned using the first polygon
  89282. // (no heuristic is used to pick a good split).
  89283. Node.prototype.build = function (polygons) {
  89284. if (!polygons.length)
  89285. return;
  89286. if (!this.plane)
  89287. this.plane = polygons[0].plane.clone();
  89288. var front = new Array(), back = new Array();
  89289. for (var i = 0; i < polygons.length; i++) {
  89290. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  89291. }
  89292. if (front.length) {
  89293. if (!this.front)
  89294. this.front = new Node();
  89295. this.front.build(front);
  89296. }
  89297. if (back.length) {
  89298. if (!this.back)
  89299. this.back = new Node();
  89300. this.back.build(back);
  89301. }
  89302. };
  89303. return Node;
  89304. }());
  89305. var CSG = /** @class */ (function () {
  89306. function CSG() {
  89307. this.polygons = new Array();
  89308. }
  89309. // Convert BABYLON.Mesh to BABYLON.CSG
  89310. CSG.FromMesh = function (mesh) {
  89311. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  89312. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  89313. if (mesh instanceof BABYLON.Mesh) {
  89314. mesh.computeWorldMatrix(true);
  89315. matrix = mesh.getWorldMatrix();
  89316. meshPosition = mesh.position.clone();
  89317. meshRotation = mesh.rotation.clone();
  89318. if (mesh.rotationQuaternion) {
  89319. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  89320. }
  89321. meshScaling = mesh.scaling.clone();
  89322. }
  89323. else {
  89324. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  89325. }
  89326. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89327. var subMeshes = mesh.subMeshes;
  89328. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  89329. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  89330. vertices = [];
  89331. for (var j = 0; j < 3; j++) {
  89332. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  89333. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  89334. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  89335. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  89336. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  89337. vertex = new Vertex(position, normal, uv);
  89338. vertices.push(vertex);
  89339. }
  89340. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  89341. // To handle the case of degenerated triangle
  89342. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  89343. if (polygon.plane)
  89344. polygons.push(polygon);
  89345. }
  89346. }
  89347. var csg = CSG.FromPolygons(polygons);
  89348. csg.matrix = matrix;
  89349. csg.position = meshPosition;
  89350. csg.rotation = meshRotation;
  89351. csg.scaling = meshScaling;
  89352. csg.rotationQuaternion = meshRotationQuaternion;
  89353. currentCSGMeshId++;
  89354. return csg;
  89355. };
  89356. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  89357. CSG.FromPolygons = function (polygons) {
  89358. var csg = new CSG();
  89359. csg.polygons = polygons;
  89360. return csg;
  89361. };
  89362. CSG.prototype.clone = function () {
  89363. var csg = new CSG();
  89364. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  89365. csg.copyTransformAttributes(this);
  89366. return csg;
  89367. };
  89368. CSG.prototype.union = function (csg) {
  89369. var a = new Node(this.clone().polygons);
  89370. var b = new Node(csg.clone().polygons);
  89371. a.clipTo(b);
  89372. b.clipTo(a);
  89373. b.invert();
  89374. b.clipTo(a);
  89375. b.invert();
  89376. a.build(b.allPolygons());
  89377. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89378. };
  89379. CSG.prototype.unionInPlace = function (csg) {
  89380. var a = new Node(this.polygons);
  89381. var b = new Node(csg.polygons);
  89382. a.clipTo(b);
  89383. b.clipTo(a);
  89384. b.invert();
  89385. b.clipTo(a);
  89386. b.invert();
  89387. a.build(b.allPolygons());
  89388. this.polygons = a.allPolygons();
  89389. };
  89390. CSG.prototype.subtract = function (csg) {
  89391. var a = new Node(this.clone().polygons);
  89392. var b = new Node(csg.clone().polygons);
  89393. a.invert();
  89394. a.clipTo(b);
  89395. b.clipTo(a);
  89396. b.invert();
  89397. b.clipTo(a);
  89398. b.invert();
  89399. a.build(b.allPolygons());
  89400. a.invert();
  89401. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89402. };
  89403. CSG.prototype.subtractInPlace = function (csg) {
  89404. var a = new Node(this.polygons);
  89405. var b = new Node(csg.polygons);
  89406. a.invert();
  89407. a.clipTo(b);
  89408. b.clipTo(a);
  89409. b.invert();
  89410. b.clipTo(a);
  89411. b.invert();
  89412. a.build(b.allPolygons());
  89413. a.invert();
  89414. this.polygons = a.allPolygons();
  89415. };
  89416. CSG.prototype.intersect = function (csg) {
  89417. var a = new Node(this.clone().polygons);
  89418. var b = new Node(csg.clone().polygons);
  89419. a.invert();
  89420. b.clipTo(a);
  89421. b.invert();
  89422. a.clipTo(b);
  89423. b.clipTo(a);
  89424. a.build(b.allPolygons());
  89425. a.invert();
  89426. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89427. };
  89428. CSG.prototype.intersectInPlace = function (csg) {
  89429. var a = new Node(this.polygons);
  89430. var b = new Node(csg.polygons);
  89431. a.invert();
  89432. b.clipTo(a);
  89433. b.invert();
  89434. a.clipTo(b);
  89435. b.clipTo(a);
  89436. a.build(b.allPolygons());
  89437. a.invert();
  89438. this.polygons = a.allPolygons();
  89439. };
  89440. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  89441. // not modified.
  89442. CSG.prototype.inverse = function () {
  89443. var csg = this.clone();
  89444. csg.inverseInPlace();
  89445. return csg;
  89446. };
  89447. CSG.prototype.inverseInPlace = function () {
  89448. this.polygons.map(function (p) { p.flip(); });
  89449. };
  89450. // This is used to keep meshes transformations so they can be restored
  89451. // when we build back a Babylon Mesh
  89452. // NB : All CSG operations are performed in world coordinates
  89453. CSG.prototype.copyTransformAttributes = function (csg) {
  89454. this.matrix = csg.matrix;
  89455. this.position = csg.position;
  89456. this.rotation = csg.rotation;
  89457. this.scaling = csg.scaling;
  89458. this.rotationQuaternion = csg.rotationQuaternion;
  89459. return this;
  89460. };
  89461. // Build Raw mesh from CSG
  89462. // Coordinates here are in world space
  89463. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  89464. var matrix = this.matrix.clone();
  89465. matrix.invert();
  89466. 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;
  89467. if (keepSubMeshes) {
  89468. // Sort Polygons, since subMeshes are indices range
  89469. polygons.sort(function (a, b) {
  89470. if (a.shared.meshId === b.shared.meshId) {
  89471. return a.shared.subMeshId - b.shared.subMeshId;
  89472. }
  89473. else {
  89474. return a.shared.meshId - b.shared.meshId;
  89475. }
  89476. });
  89477. }
  89478. for (var i = 0, il = polygons.length; i < il; i++) {
  89479. polygon = polygons[i];
  89480. // Building SubMeshes
  89481. if (!subMesh_dict[polygon.shared.meshId]) {
  89482. subMesh_dict[polygon.shared.meshId] = {};
  89483. }
  89484. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  89485. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  89486. indexStart: +Infinity,
  89487. indexEnd: -Infinity,
  89488. materialIndex: polygon.shared.materialIndex
  89489. };
  89490. }
  89491. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  89492. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  89493. polygonIndices[0] = 0;
  89494. polygonIndices[1] = j - 1;
  89495. polygonIndices[2] = j;
  89496. for (var k = 0; k < 3; k++) {
  89497. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  89498. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  89499. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  89500. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  89501. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  89502. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  89503. // Check if 2 points can be merged
  89504. if (!(typeof vertex_idx !== 'undefined' &&
  89505. normals[vertex_idx * 3] === localNormal.x &&
  89506. normals[vertex_idx * 3 + 1] === localNormal.y &&
  89507. normals[vertex_idx * 3 + 2] === localNormal.z &&
  89508. uvs[vertex_idx * 2] === uv.x &&
  89509. uvs[vertex_idx * 2 + 1] === uv.y)) {
  89510. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  89511. uvs.push(uv.x, uv.y);
  89512. normals.push(normal.x, normal.y, normal.z);
  89513. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  89514. }
  89515. indices.push(vertex_idx);
  89516. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  89517. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  89518. currentIndex++;
  89519. }
  89520. }
  89521. }
  89522. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  89523. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  89524. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  89525. mesh.setIndices(indices, null);
  89526. if (keepSubMeshes) {
  89527. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  89528. var materialIndexOffset = 0, materialMaxIndex;
  89529. mesh.subMeshes = new Array();
  89530. for (var m in subMesh_dict) {
  89531. materialMaxIndex = -1;
  89532. for (var sm in subMesh_dict[m]) {
  89533. subMesh_obj = subMesh_dict[m][sm];
  89534. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  89535. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  89536. }
  89537. materialIndexOffset += ++materialMaxIndex;
  89538. }
  89539. }
  89540. return mesh;
  89541. };
  89542. // Build Mesh from CSG taking material and transforms into account
  89543. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  89544. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  89545. mesh.material = material;
  89546. mesh.position.copyFrom(this.position);
  89547. mesh.rotation.copyFrom(this.rotation);
  89548. if (this.rotationQuaternion) {
  89549. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  89550. }
  89551. mesh.scaling.copyFrom(this.scaling);
  89552. mesh.computeWorldMatrix(true);
  89553. return mesh;
  89554. };
  89555. return CSG;
  89556. }());
  89557. BABYLON.CSG = CSG;
  89558. })(BABYLON || (BABYLON = {}));
  89559. //# sourceMappingURL=babylon.csg.js.map
  89560. var BABYLON;
  89561. (function (BABYLON) {
  89562. var LensFlare = /** @class */ (function () {
  89563. function LensFlare(size, position, color, imgUrl, system) {
  89564. this.size = size;
  89565. this.position = position;
  89566. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89567. this.color = color || new BABYLON.Color3(1, 1, 1);
  89568. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  89569. this._system = system;
  89570. system.lensFlares.push(this);
  89571. }
  89572. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  89573. return new LensFlare(size, position, color, imgUrl, system);
  89574. };
  89575. LensFlare.prototype.dispose = function () {
  89576. if (this.texture) {
  89577. this.texture.dispose();
  89578. }
  89579. // Remove from scene
  89580. var index = this._system.lensFlares.indexOf(this);
  89581. this._system.lensFlares.splice(index, 1);
  89582. };
  89583. ;
  89584. return LensFlare;
  89585. }());
  89586. BABYLON.LensFlare = LensFlare;
  89587. })(BABYLON || (BABYLON = {}));
  89588. //# sourceMappingURL=babylon.lensFlare.js.map
  89589. var BABYLON;
  89590. (function (BABYLON) {
  89591. // Adds the parser to the scene parsers.
  89592. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  89593. // Lens flares
  89594. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  89595. if (!container.lensFlareSystems) {
  89596. container.lensFlareSystems = new Array();
  89597. }
  89598. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  89599. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  89600. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  89601. container.lensFlareSystems.push(lf);
  89602. }
  89603. }
  89604. });
  89605. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  89606. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  89607. if (this.lensFlareSystems[index].name === name) {
  89608. return this.lensFlareSystems[index];
  89609. }
  89610. }
  89611. return null;
  89612. };
  89613. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  89614. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  89615. if (this.lensFlareSystems[index].id === id) {
  89616. return this.lensFlareSystems[index];
  89617. }
  89618. }
  89619. return null;
  89620. };
  89621. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  89622. var index = this.lensFlareSystems.indexOf(toRemove);
  89623. if (index !== -1) {
  89624. this.lensFlareSystems.splice(index, 1);
  89625. }
  89626. return index;
  89627. };
  89628. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  89629. this.lensFlareSystems.push(newLensFlareSystem);
  89630. };
  89631. /**
  89632. * Defines the lens flare scene component responsible to manage any lens flares
  89633. * in a given scene.
  89634. */
  89635. var LensFlareSystemSceneComponent = /** @class */ (function () {
  89636. /**
  89637. * Creates a new instance of the component for the given scene
  89638. * @param scene Defines the scene to register the component in
  89639. */
  89640. function LensFlareSystemSceneComponent(scene) {
  89641. /**
  89642. * The component name helpfull to identify the component in the list of scene components.
  89643. */
  89644. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  89645. this.scene = scene;
  89646. scene.lensFlareSystems = new Array();
  89647. }
  89648. /**
  89649. * Registers the component in a given scene
  89650. */
  89651. LensFlareSystemSceneComponent.prototype.register = function () {
  89652. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  89653. };
  89654. /**
  89655. * Rebuilds the elements related to this component in case of
  89656. * context lost for instance.
  89657. */
  89658. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  89659. // Nothing to do for lens flare
  89660. };
  89661. /**
  89662. * Adds all the element from the container to the scene
  89663. * @param container the container holding the elements
  89664. */
  89665. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  89666. var _this = this;
  89667. if (!container.lensFlareSystems) {
  89668. return;
  89669. }
  89670. container.lensFlareSystems.forEach(function (o) {
  89671. _this.scene.addLensFlareSystem(o);
  89672. });
  89673. };
  89674. /**
  89675. * Removes all the elements in the container from the scene
  89676. * @param container contains the elements to remove
  89677. */
  89678. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  89679. var _this = this;
  89680. if (!container.lensFlareSystems) {
  89681. return;
  89682. }
  89683. container.lensFlareSystems.forEach(function (o) {
  89684. _this.scene.removeLensFlareSystem(o);
  89685. });
  89686. };
  89687. /**
  89688. * Serializes the component data to the specified json object
  89689. * @param serializationObject The object to serialize to
  89690. */
  89691. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  89692. // Lens flares
  89693. serializationObject.lensFlareSystems = [];
  89694. var lensFlareSystems = this.scene.lensFlareSystems;
  89695. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  89696. var lensFlareSystem = lensFlareSystems_1[_i];
  89697. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  89698. }
  89699. };
  89700. /**
  89701. * Disposes the component and the associated ressources.
  89702. */
  89703. LensFlareSystemSceneComponent.prototype.dispose = function () {
  89704. var lensFlareSystems = this.scene.lensFlareSystems;
  89705. while (lensFlareSystems.length) {
  89706. lensFlareSystems[0].dispose();
  89707. }
  89708. };
  89709. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  89710. // Lens flares
  89711. if (this.scene.lensFlaresEnabled) {
  89712. var lensFlareSystems = this.scene.lensFlareSystems;
  89713. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  89714. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  89715. var lensFlareSystem = lensFlareSystems_2[_i];
  89716. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  89717. lensFlareSystem.render();
  89718. }
  89719. }
  89720. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  89721. }
  89722. };
  89723. return LensFlareSystemSceneComponent;
  89724. }());
  89725. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  89726. })(BABYLON || (BABYLON = {}));
  89727. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  89728. var BABYLON;
  89729. (function (BABYLON) {
  89730. var LensFlareSystem = /** @class */ (function () {
  89731. function LensFlareSystem(name, emitter, scene) {
  89732. this.name = name;
  89733. this.lensFlares = new Array();
  89734. this.borderLimit = 300;
  89735. this.viewportBorder = 0;
  89736. this.layerMask = 0x0FFFFFFF;
  89737. this._vertexBuffers = {};
  89738. this._isEnabled = true;
  89739. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89740. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  89741. if (!component) {
  89742. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  89743. scene._addComponent(component);
  89744. }
  89745. this._emitter = emitter;
  89746. this.id = name;
  89747. scene.lensFlareSystems.push(this);
  89748. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  89749. var engine = scene.getEngine();
  89750. // VBO
  89751. var vertices = [];
  89752. vertices.push(1, 1);
  89753. vertices.push(-1, 1);
  89754. vertices.push(-1, -1);
  89755. vertices.push(1, -1);
  89756. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89757. // Indices
  89758. var indices = [];
  89759. indices.push(0);
  89760. indices.push(1);
  89761. indices.push(2);
  89762. indices.push(0);
  89763. indices.push(2);
  89764. indices.push(3);
  89765. this._indexBuffer = engine.createIndexBuffer(indices);
  89766. // Effects
  89767. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  89768. }
  89769. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  89770. get: function () {
  89771. return this._isEnabled;
  89772. },
  89773. set: function (value) {
  89774. this._isEnabled = value;
  89775. },
  89776. enumerable: true,
  89777. configurable: true
  89778. });
  89779. LensFlareSystem.prototype.getScene = function () {
  89780. return this._scene;
  89781. };
  89782. LensFlareSystem.prototype.getEmitter = function () {
  89783. return this._emitter;
  89784. };
  89785. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  89786. this._emitter = newEmitter;
  89787. };
  89788. LensFlareSystem.prototype.getEmitterPosition = function () {
  89789. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  89790. };
  89791. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  89792. var position = this.getEmitterPosition();
  89793. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  89794. this._positionX = position.x;
  89795. this._positionY = position.y;
  89796. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  89797. if (this.viewportBorder > 0) {
  89798. globalViewport.x -= this.viewportBorder;
  89799. globalViewport.y -= this.viewportBorder;
  89800. globalViewport.width += this.viewportBorder * 2;
  89801. globalViewport.height += this.viewportBorder * 2;
  89802. position.x += this.viewportBorder;
  89803. position.y += this.viewportBorder;
  89804. this._positionX += this.viewportBorder;
  89805. this._positionY += this.viewportBorder;
  89806. }
  89807. if (position.z > 0) {
  89808. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  89809. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  89810. return true;
  89811. }
  89812. return true;
  89813. }
  89814. return false;
  89815. };
  89816. /** @hidden */
  89817. LensFlareSystem.prototype._isVisible = function () {
  89818. if (!this._isEnabled || !this._scene.activeCamera) {
  89819. return false;
  89820. }
  89821. var emitterPosition = this.getEmitterPosition();
  89822. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  89823. var distance = direction.length();
  89824. direction.normalize();
  89825. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  89826. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  89827. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  89828. };
  89829. LensFlareSystem.prototype.render = function () {
  89830. if (!this._effect.isReady() || !this._scene.activeCamera)
  89831. return false;
  89832. var engine = this._scene.getEngine();
  89833. var viewport = this._scene.activeCamera.viewport;
  89834. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  89835. // Position
  89836. if (!this.computeEffectivePosition(globalViewport)) {
  89837. return false;
  89838. }
  89839. // Visibility
  89840. if (!this._isVisible()) {
  89841. return false;
  89842. }
  89843. // Intensity
  89844. var awayX;
  89845. var awayY;
  89846. if (this._positionX < this.borderLimit + globalViewport.x) {
  89847. awayX = this.borderLimit + globalViewport.x - this._positionX;
  89848. }
  89849. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  89850. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  89851. }
  89852. else {
  89853. awayX = 0;
  89854. }
  89855. if (this._positionY < this.borderLimit + globalViewport.y) {
  89856. awayY = this.borderLimit + globalViewport.y - this._positionY;
  89857. }
  89858. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  89859. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  89860. }
  89861. else {
  89862. awayY = 0;
  89863. }
  89864. var away = (awayX > awayY) ? awayX : awayY;
  89865. away -= this.viewportBorder;
  89866. if (away > this.borderLimit) {
  89867. away = this.borderLimit;
  89868. }
  89869. var intensity = 1.0 - (away / this.borderLimit);
  89870. if (intensity < 0) {
  89871. return false;
  89872. }
  89873. if (intensity > 1.0) {
  89874. intensity = 1.0;
  89875. }
  89876. if (this.viewportBorder > 0) {
  89877. globalViewport.x += this.viewportBorder;
  89878. globalViewport.y += this.viewportBorder;
  89879. globalViewport.width -= this.viewportBorder * 2;
  89880. globalViewport.height -= this.viewportBorder * 2;
  89881. this._positionX -= this.viewportBorder;
  89882. this._positionY -= this.viewportBorder;
  89883. }
  89884. // Position
  89885. var centerX = globalViewport.x + globalViewport.width / 2;
  89886. var centerY = globalViewport.y + globalViewport.height / 2;
  89887. var distX = centerX - this._positionX;
  89888. var distY = centerY - this._positionY;
  89889. // Effects
  89890. engine.enableEffect(this._effect);
  89891. engine.setState(false);
  89892. engine.setDepthBuffer(false);
  89893. // VBOs
  89894. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  89895. // Flares
  89896. for (var index = 0; index < this.lensFlares.length; index++) {
  89897. var flare = this.lensFlares[index];
  89898. engine.setAlphaMode(flare.alphaMode);
  89899. var x = centerX - (distX * flare.position);
  89900. var y = centerY - (distY * flare.position);
  89901. var cw = flare.size;
  89902. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  89903. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  89904. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  89905. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  89906. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  89907. // Texture
  89908. this._effect.setTexture("textureSampler", flare.texture);
  89909. // Color
  89910. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  89911. // Draw order
  89912. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89913. }
  89914. engine.setDepthBuffer(true);
  89915. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89916. return true;
  89917. };
  89918. LensFlareSystem.prototype.dispose = function () {
  89919. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89920. if (vertexBuffer) {
  89921. vertexBuffer.dispose();
  89922. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89923. }
  89924. if (this._indexBuffer) {
  89925. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89926. this._indexBuffer = null;
  89927. }
  89928. while (this.lensFlares.length) {
  89929. this.lensFlares[0].dispose();
  89930. }
  89931. // Remove from scene
  89932. var index = this._scene.lensFlareSystems.indexOf(this);
  89933. this._scene.lensFlareSystems.splice(index, 1);
  89934. };
  89935. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  89936. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  89937. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  89938. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  89939. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  89940. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  89941. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  89942. var parsedFlare = parsedLensFlareSystem.flares[index];
  89943. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  89944. }
  89945. return lensFlareSystem;
  89946. };
  89947. LensFlareSystem.prototype.serialize = function () {
  89948. var serializationObject = {};
  89949. serializationObject.id = this.id;
  89950. serializationObject.name = this.name;
  89951. serializationObject.emitterId = this.getEmitter().id;
  89952. serializationObject.borderLimit = this.borderLimit;
  89953. serializationObject.flares = [];
  89954. for (var index = 0; index < this.lensFlares.length; index++) {
  89955. var flare = this.lensFlares[index];
  89956. serializationObject.flares.push({
  89957. size: flare.size,
  89958. position: flare.position,
  89959. color: flare.color.asArray(),
  89960. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  89961. });
  89962. }
  89963. return serializationObject;
  89964. };
  89965. return LensFlareSystem;
  89966. }());
  89967. BABYLON.LensFlareSystem = LensFlareSystem;
  89968. })(BABYLON || (BABYLON = {}));
  89969. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  89970. var BABYLON;
  89971. (function (BABYLON) {
  89972. /**
  89973. * This is a holder class for the physics joint created by the physics plugin.
  89974. * It holds a set of functions to control the underlying joint.
  89975. */
  89976. var PhysicsJoint = /** @class */ (function () {
  89977. function PhysicsJoint(type, jointData) {
  89978. this.type = type;
  89979. this.jointData = jointData;
  89980. jointData.nativeParams = jointData.nativeParams || {};
  89981. }
  89982. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  89983. get: function () {
  89984. return this._physicsJoint;
  89985. },
  89986. set: function (newJoint) {
  89987. if (this._physicsJoint) {
  89988. //remove from the wolrd
  89989. }
  89990. this._physicsJoint = newJoint;
  89991. },
  89992. enumerable: true,
  89993. configurable: true
  89994. });
  89995. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  89996. set: function (physicsPlugin) {
  89997. this._physicsPlugin = physicsPlugin;
  89998. },
  89999. enumerable: true,
  90000. configurable: true
  90001. });
  90002. /**
  90003. * Execute a function that is physics-plugin specific.
  90004. * @param {Function} func the function that will be executed.
  90005. * It accepts two parameters: the physics world and the physics joint.
  90006. */
  90007. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  90008. func(this._physicsPlugin.world, this._physicsJoint);
  90009. };
  90010. //TODO check if the native joints are the same
  90011. //Joint Types
  90012. PhysicsJoint.DistanceJoint = 0;
  90013. PhysicsJoint.HingeJoint = 1;
  90014. PhysicsJoint.BallAndSocketJoint = 2;
  90015. PhysicsJoint.WheelJoint = 3;
  90016. PhysicsJoint.SliderJoint = 4;
  90017. //OIMO
  90018. PhysicsJoint.PrismaticJoint = 5;
  90019. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  90020. PhysicsJoint.UniversalJoint = 6;
  90021. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  90022. //Cannon
  90023. //Similar to a Ball-Joint. Different in params
  90024. PhysicsJoint.PointToPointJoint = 8;
  90025. //Cannon only at the moment
  90026. PhysicsJoint.SpringJoint = 9;
  90027. PhysicsJoint.LockJoint = 10;
  90028. return PhysicsJoint;
  90029. }());
  90030. BABYLON.PhysicsJoint = PhysicsJoint;
  90031. /**
  90032. * A class representing a physics distance joint.
  90033. */
  90034. var DistanceJoint = /** @class */ (function (_super) {
  90035. __extends(DistanceJoint, _super);
  90036. function DistanceJoint(jointData) {
  90037. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  90038. }
  90039. /**
  90040. * Update the predefined distance.
  90041. */
  90042. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  90043. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  90044. };
  90045. return DistanceJoint;
  90046. }(PhysicsJoint));
  90047. BABYLON.DistanceJoint = DistanceJoint;
  90048. var MotorEnabledJoint = /** @class */ (function (_super) {
  90049. __extends(MotorEnabledJoint, _super);
  90050. function MotorEnabledJoint(type, jointData) {
  90051. return _super.call(this, type, jointData) || this;
  90052. }
  90053. /**
  90054. * Set the motor values.
  90055. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90056. * @param {number} force the force to apply
  90057. * @param {number} maxForce max force for this motor.
  90058. */
  90059. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  90060. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  90061. };
  90062. /**
  90063. * Set the motor's limits.
  90064. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90065. */
  90066. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  90067. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  90068. };
  90069. return MotorEnabledJoint;
  90070. }(PhysicsJoint));
  90071. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  90072. /**
  90073. * This class represents a single hinge physics joint
  90074. */
  90075. var HingeJoint = /** @class */ (function (_super) {
  90076. __extends(HingeJoint, _super);
  90077. function HingeJoint(jointData) {
  90078. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  90079. }
  90080. /**
  90081. * Set the motor values.
  90082. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90083. * @param {number} force the force to apply
  90084. * @param {number} maxForce max force for this motor.
  90085. */
  90086. HingeJoint.prototype.setMotor = function (force, maxForce) {
  90087. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  90088. };
  90089. /**
  90090. * Set the motor's limits.
  90091. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90092. */
  90093. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  90094. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  90095. };
  90096. return HingeJoint;
  90097. }(MotorEnabledJoint));
  90098. BABYLON.HingeJoint = HingeJoint;
  90099. /**
  90100. * This class represents a dual hinge physics joint (same as wheel joint)
  90101. */
  90102. var Hinge2Joint = /** @class */ (function (_super) {
  90103. __extends(Hinge2Joint, _super);
  90104. function Hinge2Joint(jointData) {
  90105. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  90106. }
  90107. /**
  90108. * Set the motor values.
  90109. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90110. * @param {number} force the force to apply
  90111. * @param {number} maxForce max force for this motor.
  90112. * @param {motorIndex} the motor's index, 0 or 1.
  90113. */
  90114. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  90115. if (motorIndex === void 0) { motorIndex = 0; }
  90116. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  90117. };
  90118. /**
  90119. * Set the motor limits.
  90120. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90121. * @param {number} upperLimit the upper limit
  90122. * @param {number} lowerLimit lower limit
  90123. * @param {motorIndex} the motor's index, 0 or 1.
  90124. */
  90125. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  90126. if (motorIndex === void 0) { motorIndex = 0; }
  90127. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  90128. };
  90129. return Hinge2Joint;
  90130. }(MotorEnabledJoint));
  90131. BABYLON.Hinge2Joint = Hinge2Joint;
  90132. })(BABYLON || (BABYLON = {}));
  90133. //# sourceMappingURL=babylon.physicsJoint.js.map
  90134. var BABYLON;
  90135. (function (BABYLON) {
  90136. var PhysicsImpostor = /** @class */ (function () {
  90137. function PhysicsImpostor(object, type, _options, _scene) {
  90138. if (_options === void 0) { _options = { mass: 0 }; }
  90139. var _this = this;
  90140. this.object = object;
  90141. this.type = type;
  90142. this._options = _options;
  90143. this._scene = _scene;
  90144. this._bodyUpdateRequired = false;
  90145. this._onBeforePhysicsStepCallbacks = new Array();
  90146. this._onAfterPhysicsStepCallbacks = new Array();
  90147. this._onPhysicsCollideCallbacks = [];
  90148. this._deltaPosition = BABYLON.Vector3.Zero();
  90149. this._isDisposed = false;
  90150. //temp variables for parent rotation calculations
  90151. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  90152. this._tmpQuat = new BABYLON.Quaternion();
  90153. this._tmpQuat2 = new BABYLON.Quaternion();
  90154. /**
  90155. * this function is executed by the physics engine.
  90156. */
  90157. this.beforeStep = function () {
  90158. if (!_this._physicsEngine) {
  90159. return;
  90160. }
  90161. _this.object.translate(_this._deltaPosition, -1);
  90162. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  90163. _this.object.computeWorldMatrix(false);
  90164. if (_this.object.parent && _this.object.rotationQuaternion) {
  90165. _this.getParentsRotation();
  90166. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  90167. }
  90168. else {
  90169. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  90170. }
  90171. if (!_this._options.disableBidirectionalTransformation) {
  90172. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  90173. }
  90174. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  90175. func(_this);
  90176. });
  90177. };
  90178. /**
  90179. * this function is executed by the physics engine.
  90180. */
  90181. this.afterStep = function () {
  90182. if (!_this._physicsEngine) {
  90183. return;
  90184. }
  90185. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  90186. func(_this);
  90187. });
  90188. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  90189. // object has now its world rotation. needs to be converted to local.
  90190. if (_this.object.parent && _this.object.rotationQuaternion) {
  90191. _this.getParentsRotation();
  90192. _this._tmpQuat.conjugateInPlace();
  90193. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  90194. }
  90195. // take the position set and make it the absolute position of this object.
  90196. _this.object.setAbsolutePosition(_this.object.position);
  90197. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  90198. _this.object.translate(_this._deltaPosition, 1);
  90199. };
  90200. /**
  90201. * Legacy collision detection event support
  90202. */
  90203. this.onCollideEvent = null;
  90204. //event and body object due to cannon's event-based architecture.
  90205. this.onCollide = function (e) {
  90206. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  90207. return;
  90208. }
  90209. if (!_this._physicsEngine) {
  90210. return;
  90211. }
  90212. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  90213. if (otherImpostor) {
  90214. // Legacy collision detection event support
  90215. if (_this.onCollideEvent) {
  90216. _this.onCollideEvent(_this, otherImpostor);
  90217. }
  90218. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  90219. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  90220. }).forEach(function (obj) {
  90221. obj.callback(_this, otherImpostor);
  90222. });
  90223. }
  90224. };
  90225. //sanity check!
  90226. if (!this.object) {
  90227. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  90228. return;
  90229. }
  90230. //legacy support for old syntax.
  90231. if (!this._scene && object.getScene) {
  90232. this._scene = object.getScene();
  90233. }
  90234. if (!this._scene) {
  90235. return;
  90236. }
  90237. this._physicsEngine = this._scene.getPhysicsEngine();
  90238. if (!this._physicsEngine) {
  90239. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  90240. }
  90241. else {
  90242. //set the object's quaternion, if not set
  90243. if (!this.object.rotationQuaternion) {
  90244. if (this.object.rotation) {
  90245. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  90246. }
  90247. else {
  90248. this.object.rotationQuaternion = new BABYLON.Quaternion();
  90249. }
  90250. }
  90251. //default options params
  90252. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  90253. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  90254. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  90255. this._joints = [];
  90256. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  90257. if (!this.object.parent || this._options.ignoreParent) {
  90258. this._init();
  90259. }
  90260. else if (this.object.parent.physicsImpostor) {
  90261. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  90262. }
  90263. }
  90264. }
  90265. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  90266. get: function () {
  90267. return this._isDisposed;
  90268. },
  90269. enumerable: true,
  90270. configurable: true
  90271. });
  90272. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  90273. get: function () {
  90274. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  90275. },
  90276. set: function (value) {
  90277. this.setMass(value);
  90278. },
  90279. enumerable: true,
  90280. configurable: true
  90281. });
  90282. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  90283. get: function () {
  90284. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  90285. },
  90286. set: function (value) {
  90287. if (!this._physicsEngine) {
  90288. return;
  90289. }
  90290. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  90291. },
  90292. enumerable: true,
  90293. configurable: true
  90294. });
  90295. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  90296. get: function () {
  90297. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  90298. },
  90299. set: function (value) {
  90300. if (!this._physicsEngine) {
  90301. return;
  90302. }
  90303. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  90304. },
  90305. enumerable: true,
  90306. configurable: true
  90307. });
  90308. /**
  90309. * This function will completly initialize this impostor.
  90310. * It will create a new body - but only if this mesh has no parent.
  90311. * If it has, this impostor will not be used other than to define the impostor
  90312. * of the child mesh.
  90313. * @hidden
  90314. */
  90315. PhysicsImpostor.prototype._init = function () {
  90316. if (!this._physicsEngine) {
  90317. return;
  90318. }
  90319. this._physicsEngine.removeImpostor(this);
  90320. this.physicsBody = null;
  90321. this._parent = this._parent || this._getPhysicsParent();
  90322. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  90323. this._physicsEngine.addImpostor(this);
  90324. }
  90325. };
  90326. PhysicsImpostor.prototype._getPhysicsParent = function () {
  90327. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  90328. var parentMesh = this.object.parent;
  90329. return parentMesh.physicsImpostor;
  90330. }
  90331. return null;
  90332. };
  90333. /**
  90334. * Should a new body be generated.
  90335. */
  90336. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  90337. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  90338. };
  90339. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  90340. this.forceUpdate();
  90341. };
  90342. /**
  90343. * Force a regeneration of this or the parent's impostor's body.
  90344. * Use under cautious - This will remove all joints already implemented.
  90345. */
  90346. PhysicsImpostor.prototype.forceUpdate = function () {
  90347. this._init();
  90348. if (this.parent && !this._options.ignoreParent) {
  90349. this.parent.forceUpdate();
  90350. }
  90351. };
  90352. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  90353. /*public get mesh(): AbstractMesh {
  90354. return this._mesh;
  90355. }*/
  90356. /**
  90357. * Gets the body that holds this impostor. Either its own, or its parent.
  90358. */
  90359. get: function () {
  90360. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  90361. },
  90362. /**
  90363. * Set the physics body. Used mainly by the physics engine/plugin
  90364. */
  90365. set: function (physicsBody) {
  90366. if (this._physicsBody && this._physicsEngine) {
  90367. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  90368. }
  90369. this._physicsBody = physicsBody;
  90370. this.resetUpdateFlags();
  90371. },
  90372. enumerable: true,
  90373. configurable: true
  90374. });
  90375. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  90376. get: function () {
  90377. return !this._options.ignoreParent && this._parent ? this._parent : null;
  90378. },
  90379. set: function (value) {
  90380. this._parent = value;
  90381. },
  90382. enumerable: true,
  90383. configurable: true
  90384. });
  90385. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  90386. this._bodyUpdateRequired = false;
  90387. };
  90388. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  90389. if (this.object.getBoundingInfo) {
  90390. var q = this.object.rotationQuaternion;
  90391. //reset rotation
  90392. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  90393. //calculate the world matrix with no rotation
  90394. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  90395. var boundingInfo = this.object.getBoundingInfo();
  90396. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  90397. //bring back the rotation
  90398. this.object.rotationQuaternion = q;
  90399. //calculate the world matrix with the new rotation
  90400. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  90401. return size;
  90402. }
  90403. else {
  90404. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  90405. }
  90406. };
  90407. PhysicsImpostor.prototype.getObjectCenter = function () {
  90408. if (this.object.getBoundingInfo) {
  90409. var boundingInfo = this.object.getBoundingInfo();
  90410. return boundingInfo.boundingBox.centerWorld;
  90411. }
  90412. else {
  90413. return this.object.position;
  90414. }
  90415. };
  90416. /**
  90417. * Get a specific parametes from the options parameter.
  90418. */
  90419. PhysicsImpostor.prototype.getParam = function (paramName) {
  90420. return this._options[paramName];
  90421. };
  90422. /**
  90423. * Sets a specific parameter in the options given to the physics plugin
  90424. */
  90425. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  90426. this._options[paramName] = value;
  90427. this._bodyUpdateRequired = true;
  90428. };
  90429. /**
  90430. * Specifically change the body's mass option. Won't recreate the physics body object
  90431. */
  90432. PhysicsImpostor.prototype.setMass = function (mass) {
  90433. if (this.getParam("mass") !== mass) {
  90434. this.setParam("mass", mass);
  90435. }
  90436. if (this._physicsEngine) {
  90437. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  90438. }
  90439. };
  90440. PhysicsImpostor.prototype.getLinearVelocity = function () {
  90441. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  90442. };
  90443. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  90444. if (this._physicsEngine) {
  90445. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  90446. }
  90447. };
  90448. PhysicsImpostor.prototype.getAngularVelocity = function () {
  90449. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  90450. };
  90451. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  90452. if (this._physicsEngine) {
  90453. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  90454. }
  90455. };
  90456. /**
  90457. * Execute a function with the physics plugin native code.
  90458. * Provide a function the will have two variables - the world object and the physics body object.
  90459. */
  90460. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  90461. if (this._physicsEngine) {
  90462. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  90463. }
  90464. };
  90465. /**
  90466. * Register a function that will be executed before the physics world is stepping forward.
  90467. */
  90468. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  90469. this._onBeforePhysicsStepCallbacks.push(func);
  90470. };
  90471. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  90472. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  90473. if (index > -1) {
  90474. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  90475. }
  90476. else {
  90477. BABYLON.Tools.Warn("Function to remove was not found");
  90478. }
  90479. };
  90480. /**
  90481. * Register a function that will be executed after the physics step
  90482. */
  90483. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  90484. this._onAfterPhysicsStepCallbacks.push(func);
  90485. };
  90486. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  90487. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  90488. if (index > -1) {
  90489. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  90490. }
  90491. else {
  90492. BABYLON.Tools.Warn("Function to remove was not found");
  90493. }
  90494. };
  90495. /**
  90496. * register a function that will be executed when this impostor collides against a different body.
  90497. */
  90498. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  90499. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  90500. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  90501. };
  90502. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  90503. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  90504. var index = -1;
  90505. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  90506. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  90507. // chcek the arrays match
  90508. var sameList = cbDef.otherImpostors.every(function (impostor) {
  90509. return collidedAgainstList.indexOf(impostor) > -1;
  90510. });
  90511. if (sameList) {
  90512. index = idx;
  90513. }
  90514. return sameList;
  90515. }
  90516. return false;
  90517. });
  90518. if (found) {
  90519. this._onPhysicsCollideCallbacks.splice(index, 1);
  90520. }
  90521. else {
  90522. BABYLON.Tools.Warn("Function to remove was not found");
  90523. }
  90524. };
  90525. PhysicsImpostor.prototype.getParentsRotation = function () {
  90526. var parent = this.object.parent;
  90527. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  90528. while (parent) {
  90529. if (parent.rotationQuaternion) {
  90530. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  90531. }
  90532. else {
  90533. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  90534. }
  90535. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  90536. parent = parent.parent;
  90537. }
  90538. return this._tmpQuat;
  90539. };
  90540. /**
  90541. * Apply a force
  90542. */
  90543. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  90544. if (this._physicsEngine) {
  90545. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  90546. }
  90547. return this;
  90548. };
  90549. /**
  90550. * Apply an impulse
  90551. */
  90552. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  90553. if (this._physicsEngine) {
  90554. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  90555. }
  90556. return this;
  90557. };
  90558. /**
  90559. * A help function to create a joint.
  90560. */
  90561. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  90562. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  90563. this.addJoint(otherImpostor, joint);
  90564. return this;
  90565. };
  90566. /**
  90567. * Add a joint to this impostor with a different impostor.
  90568. */
  90569. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  90570. this._joints.push({
  90571. otherImpostor: otherImpostor,
  90572. joint: joint
  90573. });
  90574. if (this._physicsEngine) {
  90575. this._physicsEngine.addJoint(this, otherImpostor, joint);
  90576. }
  90577. return this;
  90578. };
  90579. /**
  90580. * Will keep this body still, in a sleep mode.
  90581. */
  90582. PhysicsImpostor.prototype.sleep = function () {
  90583. if (this._physicsEngine) {
  90584. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  90585. }
  90586. return this;
  90587. };
  90588. /**
  90589. * Wake the body up.
  90590. */
  90591. PhysicsImpostor.prototype.wakeUp = function () {
  90592. if (this._physicsEngine) {
  90593. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  90594. }
  90595. return this;
  90596. };
  90597. PhysicsImpostor.prototype.clone = function (newObject) {
  90598. if (!newObject)
  90599. return null;
  90600. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  90601. };
  90602. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  90603. var _this = this;
  90604. //no dispose if no physics engine is available.
  90605. if (!this._physicsEngine) {
  90606. return;
  90607. }
  90608. this._joints.forEach(function (j) {
  90609. if (_this._physicsEngine) {
  90610. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  90611. }
  90612. });
  90613. //dispose the physics body
  90614. this._physicsEngine.removeImpostor(this);
  90615. if (this.parent) {
  90616. this.parent.forceUpdate();
  90617. }
  90618. else {
  90619. /*this._object.getChildMeshes().forEach(function(mesh) {
  90620. if (mesh.physicsImpostor) {
  90621. if (disposeChildren) {
  90622. mesh.physicsImpostor.dispose();
  90623. mesh.physicsImpostor = null;
  90624. }
  90625. }
  90626. })*/
  90627. }
  90628. this._isDisposed = true;
  90629. };
  90630. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  90631. this._deltaPosition.copyFrom(position);
  90632. };
  90633. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  90634. if (!this._deltaRotation) {
  90635. this._deltaRotation = new BABYLON.Quaternion();
  90636. }
  90637. this._deltaRotation.copyFrom(rotation);
  90638. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  90639. };
  90640. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  90641. if (this._physicsEngine) {
  90642. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  90643. }
  90644. return this;
  90645. };
  90646. PhysicsImpostor.prototype.getRadius = function () {
  90647. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  90648. };
  90649. /**
  90650. * Sync a bone with this impostor
  90651. * @param bone The bone to sync to the impostor.
  90652. * @param boneMesh The mesh that the bone is influencing.
  90653. * @param jointPivot The pivot of the joint / bone in local space.
  90654. * @param distToJoint Optional distance from the impostor to the joint.
  90655. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  90656. */
  90657. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  90658. var tempVec = PhysicsImpostor._tmpVecs[0];
  90659. var mesh = this.object;
  90660. if (mesh.rotationQuaternion) {
  90661. if (adjustRotation) {
  90662. var tempQuat = PhysicsImpostor._tmpQuat;
  90663. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  90664. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  90665. }
  90666. else {
  90667. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  90668. }
  90669. }
  90670. tempVec.x = 0;
  90671. tempVec.y = 0;
  90672. tempVec.z = 0;
  90673. if (jointPivot) {
  90674. tempVec.x = jointPivot.x;
  90675. tempVec.y = jointPivot.y;
  90676. tempVec.z = jointPivot.z;
  90677. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  90678. if (distToJoint === undefined || distToJoint === null) {
  90679. distToJoint = jointPivot.length();
  90680. }
  90681. tempVec.x *= distToJoint;
  90682. tempVec.y *= distToJoint;
  90683. tempVec.z *= distToJoint;
  90684. }
  90685. if (bone.getParent()) {
  90686. tempVec.addInPlace(mesh.getAbsolutePosition());
  90687. bone.setAbsolutePosition(tempVec, boneMesh);
  90688. }
  90689. else {
  90690. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  90691. boneMesh.position.x -= tempVec.x;
  90692. boneMesh.position.y -= tempVec.y;
  90693. boneMesh.position.z -= tempVec.z;
  90694. }
  90695. };
  90696. /**
  90697. * Sync impostor to a bone
  90698. * @param bone The bone that the impostor will be synced to.
  90699. * @param boneMesh The mesh that the bone is influencing.
  90700. * @param jointPivot The pivot of the joint / bone in local space.
  90701. * @param distToJoint Optional distance from the impostor to the joint.
  90702. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  90703. * @param boneAxis Optional vector3 axis the bone is aligned with
  90704. */
  90705. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  90706. var mesh = this.object;
  90707. if (mesh.rotationQuaternion) {
  90708. if (adjustRotation) {
  90709. var tempQuat = PhysicsImpostor._tmpQuat;
  90710. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  90711. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  90712. }
  90713. else {
  90714. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  90715. }
  90716. }
  90717. var pos = PhysicsImpostor._tmpVecs[0];
  90718. var boneDir = PhysicsImpostor._tmpVecs[1];
  90719. if (!boneAxis) {
  90720. boneAxis = PhysicsImpostor._tmpVecs[2];
  90721. boneAxis.x = 0;
  90722. boneAxis.y = 1;
  90723. boneAxis.z = 0;
  90724. }
  90725. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  90726. bone.getAbsolutePositionToRef(boneMesh, pos);
  90727. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  90728. distToJoint = jointPivot.length();
  90729. }
  90730. if (distToJoint !== undefined && distToJoint !== null) {
  90731. pos.x += boneDir.x * distToJoint;
  90732. pos.y += boneDir.y * distToJoint;
  90733. pos.z += boneDir.z * distToJoint;
  90734. }
  90735. mesh.setAbsolutePosition(pos);
  90736. };
  90737. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  90738. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  90739. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90740. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  90741. //Impostor types
  90742. PhysicsImpostor.NoImpostor = 0;
  90743. PhysicsImpostor.SphereImpostor = 1;
  90744. PhysicsImpostor.BoxImpostor = 2;
  90745. PhysicsImpostor.PlaneImpostor = 3;
  90746. PhysicsImpostor.MeshImpostor = 4;
  90747. PhysicsImpostor.CylinderImpostor = 7;
  90748. PhysicsImpostor.ParticleImpostor = 8;
  90749. PhysicsImpostor.HeightmapImpostor = 9;
  90750. return PhysicsImpostor;
  90751. }());
  90752. BABYLON.PhysicsImpostor = PhysicsImpostor;
  90753. })(BABYLON || (BABYLON = {}));
  90754. //# sourceMappingURL=babylon.physicsImpostor.js.map
  90755. var BABYLON;
  90756. (function (BABYLON) {
  90757. /**
  90758. * Class used to control physics engine
  90759. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  90760. */
  90761. var PhysicsEngine = /** @class */ (function () {
  90762. /**
  90763. * Creates a new Physics Engine
  90764. * @param gravity defines the gravity vector used by the simulation
  90765. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  90766. */
  90767. function PhysicsEngine(gravity, _physicsPlugin) {
  90768. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  90769. this._physicsPlugin = _physicsPlugin;
  90770. this._impostors = [];
  90771. this._joints = [];
  90772. if (!this._physicsPlugin.isSupported()) {
  90773. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  90774. + "Please make sure it is included.");
  90775. }
  90776. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  90777. this.setGravity(gravity);
  90778. this.setTimeStep();
  90779. }
  90780. /**
  90781. * Sets the gravity vector used by the simulation
  90782. * @param gravity defines the gravity vector to use
  90783. */
  90784. PhysicsEngine.prototype.setGravity = function (gravity) {
  90785. this.gravity = gravity;
  90786. this._physicsPlugin.setGravity(this.gravity);
  90787. };
  90788. /**
  90789. * Set the time step of the physics engine.
  90790. * Default is 1/60.
  90791. * To slow it down, enter 1/600 for example.
  90792. * To speed it up, 1/30
  90793. * @param newTimeStep defines the new timestep to apply to this world.
  90794. */
  90795. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  90796. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  90797. this._physicsPlugin.setTimeStep(newTimeStep);
  90798. };
  90799. /**
  90800. * Get the time step of the physics engine.
  90801. * @returns the current time step
  90802. */
  90803. PhysicsEngine.prototype.getTimeStep = function () {
  90804. return this._physicsPlugin.getTimeStep();
  90805. };
  90806. /**
  90807. * Release all resources
  90808. */
  90809. PhysicsEngine.prototype.dispose = function () {
  90810. this._impostors.forEach(function (impostor) {
  90811. impostor.dispose();
  90812. });
  90813. this._physicsPlugin.dispose();
  90814. };
  90815. /**
  90816. * Gets the name of the current physics plugin
  90817. * @returns the name of the plugin
  90818. */
  90819. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  90820. return this._physicsPlugin.name;
  90821. };
  90822. /**
  90823. * Adding a new impostor for the impostor tracking.
  90824. * This will be done by the impostor itself.
  90825. * @param impostor the impostor to add
  90826. */
  90827. PhysicsEngine.prototype.addImpostor = function (impostor) {
  90828. impostor.uniqueId = this._impostors.push(impostor);
  90829. //if no parent, generate the body
  90830. if (!impostor.parent) {
  90831. this._physicsPlugin.generatePhysicsBody(impostor);
  90832. }
  90833. };
  90834. /**
  90835. * Remove an impostor from the engine.
  90836. * This impostor and its mesh will not longer be updated by the physics engine.
  90837. * @param impostor the impostor to remove
  90838. */
  90839. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  90840. var index = this._impostors.indexOf(impostor);
  90841. if (index > -1) {
  90842. var removed = this._impostors.splice(index, 1);
  90843. //Is it needed?
  90844. if (removed.length) {
  90845. //this will also remove it from the world.
  90846. removed[0].physicsBody = null;
  90847. }
  90848. }
  90849. };
  90850. /**
  90851. * Add a joint to the physics engine
  90852. * @param mainImpostor defines the main impostor to which the joint is added.
  90853. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  90854. * @param joint defines the joint that will connect both impostors.
  90855. */
  90856. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  90857. var impostorJoint = {
  90858. mainImpostor: mainImpostor,
  90859. connectedImpostor: connectedImpostor,
  90860. joint: joint
  90861. };
  90862. joint.physicsPlugin = this._physicsPlugin;
  90863. this._joints.push(impostorJoint);
  90864. this._physicsPlugin.generateJoint(impostorJoint);
  90865. };
  90866. /**
  90867. * Removes a joint from the simulation
  90868. * @param mainImpostor defines the impostor used with the joint
  90869. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  90870. * @param joint defines the joint to remove
  90871. */
  90872. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  90873. var matchingJoints = this._joints.filter(function (impostorJoint) {
  90874. return (impostorJoint.connectedImpostor === connectedImpostor
  90875. && impostorJoint.joint === joint
  90876. && impostorJoint.mainImpostor === mainImpostor);
  90877. });
  90878. if (matchingJoints.length) {
  90879. this._physicsPlugin.removeJoint(matchingJoints[0]);
  90880. //TODO remove it from the list as well
  90881. }
  90882. };
  90883. /**
  90884. * Called by the scene. No need to call it.
  90885. * @param delta defines the timespam between frames
  90886. */
  90887. PhysicsEngine.prototype._step = function (delta) {
  90888. var _this = this;
  90889. //check if any mesh has no body / requires an update
  90890. this._impostors.forEach(function (impostor) {
  90891. if (impostor.isBodyInitRequired()) {
  90892. _this._physicsPlugin.generatePhysicsBody(impostor);
  90893. }
  90894. });
  90895. if (delta > 0.1) {
  90896. delta = 0.1;
  90897. }
  90898. else if (delta <= 0) {
  90899. delta = 1.0 / 60.0;
  90900. }
  90901. this._physicsPlugin.executeStep(delta, this._impostors);
  90902. };
  90903. /**
  90904. * Gets the current plugin used to run the simulation
  90905. * @returns current plugin
  90906. */
  90907. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  90908. return this._physicsPlugin;
  90909. };
  90910. /**
  90911. * Gets the list of physic impostors
  90912. * @returns an array of PhysicsImpostor
  90913. */
  90914. PhysicsEngine.prototype.getImpostors = function () {
  90915. return this._impostors;
  90916. };
  90917. /**
  90918. * Gets the impostor for a physics enabled object
  90919. * @param object defines the object impersonated by the impostor
  90920. * @returns the PhysicsImpostor or null if not found
  90921. */
  90922. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  90923. for (var i = 0; i < this._impostors.length; ++i) {
  90924. if (this._impostors[i].object === object) {
  90925. return this._impostors[i];
  90926. }
  90927. }
  90928. return null;
  90929. };
  90930. /**
  90931. * Gets the impostor for a physics body object
  90932. * @param body defines physics body used by the impostor
  90933. * @returns the PhysicsImpostor or null if not found
  90934. */
  90935. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  90936. for (var i = 0; i < this._impostors.length; ++i) {
  90937. if (this._impostors[i].physicsBody === body) {
  90938. return this._impostors[i];
  90939. }
  90940. }
  90941. return null;
  90942. };
  90943. /**
  90944. * Global value used to control the smallest number supported by the simulation
  90945. */
  90946. PhysicsEngine.Epsilon = 0.001;
  90947. return PhysicsEngine;
  90948. }());
  90949. BABYLON.PhysicsEngine = PhysicsEngine;
  90950. })(BABYLON || (BABYLON = {}));
  90951. //# sourceMappingURL=babylon.physicsEngine.js.map
  90952. var BABYLON;
  90953. (function (BABYLON) {
  90954. var PhysicsHelper = /** @class */ (function () {
  90955. function PhysicsHelper(scene) {
  90956. this._scene = scene;
  90957. this._physicsEngine = this._scene.getPhysicsEngine();
  90958. if (!this._physicsEngine) {
  90959. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  90960. }
  90961. }
  90962. /**
  90963. * @param {Vector3} origin the origin of the explosion
  90964. * @param {number} radius the explosion radius
  90965. * @param {number} strength the explosion strength
  90966. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  90967. */
  90968. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  90969. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  90970. if (!this._physicsEngine) {
  90971. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  90972. return null;
  90973. }
  90974. var impostors = this._physicsEngine.getImpostors();
  90975. if (impostors.length === 0) {
  90976. return null;
  90977. }
  90978. var event = new PhysicsRadialExplosionEvent(this._scene);
  90979. impostors.forEach(function (impostor) {
  90980. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  90981. if (!impostorForceAndContactPoint) {
  90982. return;
  90983. }
  90984. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  90985. });
  90986. event.dispose(false);
  90987. return event;
  90988. };
  90989. /**
  90990. * @param {Vector3} origin the origin of the explosion
  90991. * @param {number} radius the explosion radius
  90992. * @param {number} strength the explosion strength
  90993. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  90994. */
  90995. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  90996. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  90997. if (!this._physicsEngine) {
  90998. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  90999. return null;
  91000. }
  91001. var impostors = this._physicsEngine.getImpostors();
  91002. if (impostors.length === 0) {
  91003. return null;
  91004. }
  91005. var event = new PhysicsRadialExplosionEvent(this._scene);
  91006. impostors.forEach(function (impostor) {
  91007. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  91008. if (!impostorForceAndContactPoint) {
  91009. return;
  91010. }
  91011. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91012. });
  91013. event.dispose(false);
  91014. return event;
  91015. };
  91016. /**
  91017. * @param {Vector3} origin the origin of the explosion
  91018. * @param {number} radius the explosion radius
  91019. * @param {number} strength the explosion strength
  91020. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91021. */
  91022. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  91023. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91024. if (!this._physicsEngine) {
  91025. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91026. return null;
  91027. }
  91028. var impostors = this._physicsEngine.getImpostors();
  91029. if (impostors.length === 0) {
  91030. return null;
  91031. }
  91032. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  91033. event.dispose(false);
  91034. return event;
  91035. };
  91036. /**
  91037. * @param {Vector3} origin the origin of the updraft
  91038. * @param {number} radius the radius of the updraft
  91039. * @param {number} strength the strength of the updraft
  91040. * @param {number} height the height of the updraft
  91041. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  91042. */
  91043. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  91044. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  91045. if (!this._physicsEngine) {
  91046. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91047. return null;
  91048. }
  91049. if (this._physicsEngine.getImpostors().length === 0) {
  91050. return null;
  91051. }
  91052. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  91053. event.dispose(false);
  91054. return event;
  91055. };
  91056. /**
  91057. * @param {Vector3} origin the of the vortex
  91058. * @param {number} radius the radius of the vortex
  91059. * @param {number} strength the strength of the vortex
  91060. * @param {number} height the height of the vortex
  91061. */
  91062. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  91063. if (!this._physicsEngine) {
  91064. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91065. return null;
  91066. }
  91067. if (this._physicsEngine.getImpostors().length === 0) {
  91068. return null;
  91069. }
  91070. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  91071. event.dispose(false);
  91072. return event;
  91073. };
  91074. return PhysicsHelper;
  91075. }());
  91076. BABYLON.PhysicsHelper = PhysicsHelper;
  91077. /***** Radial explosion *****/
  91078. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  91079. function PhysicsRadialExplosionEvent(scene) {
  91080. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  91081. this._rays = [];
  91082. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  91083. this._scene = scene;
  91084. }
  91085. /**
  91086. * Returns the data related to the radial explosion event (sphere & rays).
  91087. * @returns {PhysicsRadialExplosionEventData}
  91088. */
  91089. PhysicsRadialExplosionEvent.prototype.getData = function () {
  91090. this._dataFetched = true;
  91091. return {
  91092. sphere: this._sphere,
  91093. rays: this._rays,
  91094. };
  91095. };
  91096. /**
  91097. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  91098. * @param impostor
  91099. * @param {Vector3} origin the origin of the explosion
  91100. * @param {number} radius the explosion radius
  91101. * @param {number} strength the explosion strength
  91102. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  91103. * @returns {Nullable<PhysicsForceAndContactPoint>}
  91104. */
  91105. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  91106. if (impostor.mass === 0) {
  91107. return null;
  91108. }
  91109. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  91110. return null;
  91111. }
  91112. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  91113. return null;
  91114. }
  91115. var impostorObjectCenter = impostor.getObjectCenter();
  91116. var direction = impostorObjectCenter.subtract(origin);
  91117. var ray = new BABYLON.Ray(origin, direction, radius);
  91118. this._rays.push(ray);
  91119. var hit = ray.intersectsMesh(impostor.object);
  91120. var contactPoint = hit.pickedPoint;
  91121. if (!contactPoint) {
  91122. return null;
  91123. }
  91124. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  91125. if (distanceFromOrigin > radius) {
  91126. return null;
  91127. }
  91128. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  91129. ? strength
  91130. : strength * (1 - (distanceFromOrigin / radius));
  91131. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  91132. return { force: force, contactPoint: contactPoint };
  91133. };
  91134. /**
  91135. * Disposes the sphere.
  91136. * @param {bolean} force
  91137. */
  91138. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  91139. var _this = this;
  91140. if (force === void 0) { force = true; }
  91141. if (force) {
  91142. this._sphere.dispose();
  91143. }
  91144. else {
  91145. setTimeout(function () {
  91146. if (!_this._dataFetched) {
  91147. _this._sphere.dispose();
  91148. }
  91149. }, 0);
  91150. }
  91151. };
  91152. /*** Helpers ***/
  91153. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  91154. if (!this._sphere) {
  91155. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  91156. this._sphere.isVisible = false;
  91157. }
  91158. };
  91159. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  91160. var impostorObject = impostor.object;
  91161. this._prepareSphere();
  91162. this._sphere.position = origin;
  91163. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  91164. this._sphere._updateBoundingInfo();
  91165. this._sphere.computeWorldMatrix(true);
  91166. return this._sphere.intersectsMesh(impostorObject, true);
  91167. };
  91168. return PhysicsRadialExplosionEvent;
  91169. }());
  91170. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  91171. /***** Gravitational Field *****/
  91172. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  91173. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  91174. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91175. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91176. this._physicsHelper = physicsHelper;
  91177. this._scene = scene;
  91178. this._origin = origin;
  91179. this._radius = radius;
  91180. this._strength = strength;
  91181. this._falloff = falloff;
  91182. this._tickCallback = this._tick.bind(this);
  91183. }
  91184. /**
  91185. * Returns the data related to the gravitational field event (sphere).
  91186. * @returns {PhysicsGravitationalFieldEventData}
  91187. */
  91188. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  91189. this._dataFetched = true;
  91190. return {
  91191. sphere: this._sphere,
  91192. };
  91193. };
  91194. /**
  91195. * Enables the gravitational field.
  91196. */
  91197. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  91198. this._tickCallback.call(this);
  91199. this._scene.registerBeforeRender(this._tickCallback);
  91200. };
  91201. /**
  91202. * Disables the gravitational field.
  91203. */
  91204. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  91205. this._scene.unregisterBeforeRender(this._tickCallback);
  91206. };
  91207. /**
  91208. * Disposes the sphere.
  91209. * @param {bolean} force
  91210. */
  91211. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  91212. var _this = this;
  91213. if (force === void 0) { force = true; }
  91214. if (force) {
  91215. this._sphere.dispose();
  91216. }
  91217. else {
  91218. setTimeout(function () {
  91219. if (!_this._dataFetched) {
  91220. _this._sphere.dispose();
  91221. }
  91222. }, 0);
  91223. }
  91224. };
  91225. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  91226. // Since the params won't change, we fetch the event only once
  91227. if (this._sphere) {
  91228. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  91229. }
  91230. else {
  91231. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  91232. if (radialExplosionEvent) {
  91233. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  91234. }
  91235. }
  91236. };
  91237. return PhysicsGravitationalFieldEvent;
  91238. }());
  91239. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  91240. /***** Updraft *****/
  91241. var PhysicsUpdraftEvent = /** @class */ (function () {
  91242. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  91243. this._scene = _scene;
  91244. this._origin = _origin;
  91245. this._radius = _radius;
  91246. this._strength = _strength;
  91247. this._height = _height;
  91248. this._updraftMode = _updraftMode;
  91249. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  91250. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  91251. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  91252. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91253. this._physicsEngine = this._scene.getPhysicsEngine();
  91254. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  91255. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  91256. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  91257. this._originDirection = this._origin.subtract(this._originTop).normalize();
  91258. }
  91259. this._tickCallback = this._tick.bind(this);
  91260. }
  91261. /**
  91262. * Returns the data related to the updraft event (cylinder).
  91263. * @returns {PhysicsUpdraftEventData}
  91264. */
  91265. PhysicsUpdraftEvent.prototype.getData = function () {
  91266. this._dataFetched = true;
  91267. return {
  91268. cylinder: this._cylinder,
  91269. };
  91270. };
  91271. /**
  91272. * Enables the updraft.
  91273. */
  91274. PhysicsUpdraftEvent.prototype.enable = function () {
  91275. this._tickCallback.call(this);
  91276. this._scene.registerBeforeRender(this._tickCallback);
  91277. };
  91278. /**
  91279. * Disables the cortex.
  91280. */
  91281. PhysicsUpdraftEvent.prototype.disable = function () {
  91282. this._scene.unregisterBeforeRender(this._tickCallback);
  91283. };
  91284. /**
  91285. * Disposes the sphere.
  91286. * @param {bolean} force
  91287. */
  91288. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  91289. var _this = this;
  91290. if (force === void 0) { force = true; }
  91291. if (force) {
  91292. this._cylinder.dispose();
  91293. }
  91294. else {
  91295. setTimeout(function () {
  91296. if (!_this._dataFetched) {
  91297. _this._cylinder.dispose();
  91298. }
  91299. }, 0);
  91300. }
  91301. };
  91302. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  91303. if (impostor.mass === 0) {
  91304. return null;
  91305. }
  91306. if (!this._intersectsWithCylinder(impostor)) {
  91307. return null;
  91308. }
  91309. var impostorObjectCenter = impostor.getObjectCenter();
  91310. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  91311. var direction = this._originDirection;
  91312. }
  91313. else {
  91314. var direction = impostorObjectCenter.subtract(this._originTop);
  91315. }
  91316. var multiplier = this._strength * -1;
  91317. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  91318. return { force: force, contactPoint: impostorObjectCenter };
  91319. };
  91320. PhysicsUpdraftEvent.prototype._tick = function () {
  91321. var _this = this;
  91322. this._physicsEngine.getImpostors().forEach(function (impostor) {
  91323. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  91324. if (!impostorForceAndContactPoint) {
  91325. return;
  91326. }
  91327. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91328. });
  91329. };
  91330. /*** Helpers ***/
  91331. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  91332. if (!this._cylinder) {
  91333. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  91334. height: this._height,
  91335. diameter: this._radius * 2,
  91336. }, this._scene);
  91337. this._cylinder.isVisible = false;
  91338. }
  91339. };
  91340. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  91341. var impostorObject = impostor.object;
  91342. this._prepareCylinder();
  91343. this._cylinder.position = this._cylinderPosition;
  91344. return this._cylinder.intersectsMesh(impostorObject, true);
  91345. };
  91346. return PhysicsUpdraftEvent;
  91347. }());
  91348. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  91349. /***** Vortex *****/
  91350. var PhysicsVortexEvent = /** @class */ (function () {
  91351. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  91352. this._scene = _scene;
  91353. this._origin = _origin;
  91354. this._radius = _radius;
  91355. this._strength = _strength;
  91356. this._height = _height;
  91357. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  91358. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  91359. this._updraftMultiplier = 0.02;
  91360. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  91361. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91362. this._physicsEngine = this._scene.getPhysicsEngine();
  91363. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  91364. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  91365. this._tickCallback = this._tick.bind(this);
  91366. }
  91367. /**
  91368. * Returns the data related to the vortex event (cylinder).
  91369. * @returns {PhysicsVortexEventData}
  91370. */
  91371. PhysicsVortexEvent.prototype.getData = function () {
  91372. this._dataFetched = true;
  91373. return {
  91374. cylinder: this._cylinder,
  91375. };
  91376. };
  91377. /**
  91378. * Enables the vortex.
  91379. */
  91380. PhysicsVortexEvent.prototype.enable = function () {
  91381. this._tickCallback.call(this);
  91382. this._scene.registerBeforeRender(this._tickCallback);
  91383. };
  91384. /**
  91385. * Disables the cortex.
  91386. */
  91387. PhysicsVortexEvent.prototype.disable = function () {
  91388. this._scene.unregisterBeforeRender(this._tickCallback);
  91389. };
  91390. /**
  91391. * Disposes the sphere.
  91392. * @param {bolean} force
  91393. */
  91394. PhysicsVortexEvent.prototype.dispose = function (force) {
  91395. var _this = this;
  91396. if (force === void 0) { force = true; }
  91397. if (force) {
  91398. this._cylinder.dispose();
  91399. }
  91400. else {
  91401. setTimeout(function () {
  91402. if (!_this._dataFetched) {
  91403. _this._cylinder.dispose();
  91404. }
  91405. }, 0);
  91406. }
  91407. };
  91408. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  91409. if (impostor.mass === 0) {
  91410. return null;
  91411. }
  91412. if (!this._intersectsWithCylinder(impostor)) {
  91413. return null;
  91414. }
  91415. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  91416. return null;
  91417. }
  91418. var impostorObjectCenter = impostor.getObjectCenter();
  91419. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  91420. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  91421. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  91422. var hit = ray.intersectsMesh(impostor.object);
  91423. var contactPoint = hit.pickedPoint;
  91424. if (!contactPoint) {
  91425. return null;
  91426. }
  91427. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  91428. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  91429. var directionToOrigin = contactPoint.normalize();
  91430. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  91431. directionToOrigin = directionToOrigin.negate();
  91432. }
  91433. // TODO: find a more physically based solution
  91434. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  91435. var forceX = directionToOrigin.x * this._strength / 8;
  91436. var forceY = directionToOrigin.y * this._updraftMultiplier;
  91437. var forceZ = directionToOrigin.z * this._strength / 8;
  91438. }
  91439. else {
  91440. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  91441. var forceY = this._originTop.y * this._updraftMultiplier;
  91442. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  91443. }
  91444. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  91445. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  91446. return { force: force, contactPoint: impostorObjectCenter };
  91447. };
  91448. PhysicsVortexEvent.prototype._tick = function () {
  91449. var _this = this;
  91450. this._physicsEngine.getImpostors().forEach(function (impostor) {
  91451. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  91452. if (!impostorForceAndContactPoint) {
  91453. return;
  91454. }
  91455. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91456. });
  91457. };
  91458. /*** Helpers ***/
  91459. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  91460. if (!this._cylinder) {
  91461. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  91462. height: this._height,
  91463. diameter: this._radius * 2,
  91464. }, this._scene);
  91465. this._cylinder.isVisible = false;
  91466. }
  91467. };
  91468. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  91469. var impostorObject = impostor.object;
  91470. this._prepareCylinder();
  91471. this._cylinder.position = this._cylinderPosition;
  91472. return this._cylinder.intersectsMesh(impostorObject, true);
  91473. };
  91474. return PhysicsVortexEvent;
  91475. }());
  91476. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  91477. /***** Enums *****/
  91478. /**
  91479. * The strenght of the force in correspondence to the distance of the affected object
  91480. */
  91481. var PhysicsRadialImpulseFalloff;
  91482. (function (PhysicsRadialImpulseFalloff) {
  91483. /** Defines that impulse is constant in strength across it's whole radius */
  91484. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  91485. /** DEfines that impulse gets weaker if it's further from the origin */
  91486. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  91487. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  91488. /**
  91489. * The strenght of the force in correspondence to the distance of the affected object
  91490. */
  91491. var PhysicsUpdraftMode;
  91492. (function (PhysicsUpdraftMode) {
  91493. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  91494. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  91495. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  91496. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  91497. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  91498. })(BABYLON || (BABYLON = {}));
  91499. //# sourceMappingURL=babylon.physicsHelper.js.map
  91500. var BABYLON;
  91501. (function (BABYLON) {
  91502. var CannonJSPlugin = /** @class */ (function () {
  91503. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  91504. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  91505. if (iterations === void 0) { iterations = 10; }
  91506. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  91507. this.name = "CannonJSPlugin";
  91508. this._physicsMaterials = new Array();
  91509. this._fixedTimeStep = 1 / 60;
  91510. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  91511. this.BJSCANNON = CANNON;
  91512. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  91513. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  91514. this._tmpPosition = BABYLON.Vector3.Zero();
  91515. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  91516. this._tmpUnityRotation = new BABYLON.Quaternion();
  91517. if (!this.isSupported()) {
  91518. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  91519. return;
  91520. }
  91521. this._extendNamespace();
  91522. this.world = new this.BJSCANNON.World();
  91523. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  91524. this.world.solver.iterations = iterations;
  91525. }
  91526. CannonJSPlugin.prototype.setGravity = function (gravity) {
  91527. this.world.gravity.copy(gravity);
  91528. };
  91529. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  91530. this._fixedTimeStep = timeStep;
  91531. };
  91532. CannonJSPlugin.prototype.getTimeStep = function () {
  91533. return this._fixedTimeStep;
  91534. };
  91535. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  91536. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  91537. };
  91538. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  91539. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  91540. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  91541. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  91542. };
  91543. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  91544. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  91545. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  91546. impostor.physicsBody.applyForce(impulse, worldPoint);
  91547. };
  91548. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  91549. //parent-child relationship. Does this impostor has a parent impostor?
  91550. if (impostor.parent) {
  91551. if (impostor.physicsBody) {
  91552. this.removePhysicsBody(impostor);
  91553. //TODO is that needed?
  91554. impostor.forceUpdate();
  91555. }
  91556. return;
  91557. }
  91558. //should a new body be created for this impostor?
  91559. if (impostor.isBodyInitRequired()) {
  91560. var shape = this._createShape(impostor);
  91561. //unregister events, if body is being changed
  91562. var oldBody = impostor.physicsBody;
  91563. if (oldBody) {
  91564. this.removePhysicsBody(impostor);
  91565. }
  91566. //create the body and material
  91567. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  91568. var bodyCreationObject = {
  91569. mass: impostor.getParam("mass"),
  91570. material: material
  91571. };
  91572. // A simple extend, in case native options were used.
  91573. var nativeOptions = impostor.getParam("nativeOptions");
  91574. for (var key in nativeOptions) {
  91575. if (nativeOptions.hasOwnProperty(key)) {
  91576. bodyCreationObject[key] = nativeOptions[key];
  91577. }
  91578. }
  91579. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  91580. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  91581. this.world.addEventListener("preStep", impostor.beforeStep);
  91582. this.world.addEventListener("postStep", impostor.afterStep);
  91583. impostor.physicsBody.addShape(shape);
  91584. this.world.add(impostor.physicsBody);
  91585. //try to keep the body moving in the right direction by taking old properties.
  91586. //Should be tested!
  91587. if (oldBody) {
  91588. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  91589. impostor.physicsBody[param].copy(oldBody[param]);
  91590. });
  91591. }
  91592. this._processChildMeshes(impostor);
  91593. }
  91594. //now update the body's transformation
  91595. this._updatePhysicsBodyTransformation(impostor);
  91596. };
  91597. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  91598. var _this = this;
  91599. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  91600. var currentRotation = mainImpostor.object.rotationQuaternion;
  91601. if (meshChildren.length) {
  91602. var processMesh = function (localPosition, mesh) {
  91603. if (!currentRotation || !mesh.rotationQuaternion) {
  91604. return;
  91605. }
  91606. var childImpostor = mesh.getPhysicsImpostor();
  91607. if (childImpostor) {
  91608. var parent = childImpostor.parent;
  91609. if (parent !== mainImpostor) {
  91610. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  91611. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  91612. if (childImpostor.physicsBody) {
  91613. _this.removePhysicsBody(childImpostor);
  91614. childImpostor.physicsBody = null;
  91615. }
  91616. childImpostor.parent = mainImpostor;
  91617. childImpostor.resetUpdateFlags();
  91618. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  91619. //Add the mass of the children.
  91620. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  91621. }
  91622. }
  91623. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  91624. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  91625. };
  91626. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  91627. }
  91628. };
  91629. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  91630. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  91631. this.world.removeEventListener("preStep", impostor.beforeStep);
  91632. this.world.removeEventListener("postStep", impostor.afterStep);
  91633. this.world.remove(impostor.physicsBody);
  91634. };
  91635. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  91636. var mainBody = impostorJoint.mainImpostor.physicsBody;
  91637. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  91638. if (!mainBody || !connectedBody) {
  91639. return;
  91640. }
  91641. var constraint;
  91642. var jointData = impostorJoint.joint.jointData;
  91643. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  91644. var constraintData = {
  91645. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  91646. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  91647. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  91648. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  91649. maxForce: jointData.nativeParams.maxForce,
  91650. collideConnected: !!jointData.collision
  91651. };
  91652. switch (impostorJoint.joint.type) {
  91653. case BABYLON.PhysicsJoint.HingeJoint:
  91654. case BABYLON.PhysicsJoint.Hinge2Joint:
  91655. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  91656. break;
  91657. case BABYLON.PhysicsJoint.DistanceJoint:
  91658. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  91659. break;
  91660. case BABYLON.PhysicsJoint.SpringJoint:
  91661. var springData = jointData;
  91662. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  91663. restLength: springData.length,
  91664. stiffness: springData.stiffness,
  91665. damping: springData.damping,
  91666. localAnchorA: constraintData.pivotA,
  91667. localAnchorB: constraintData.pivotB
  91668. });
  91669. break;
  91670. case BABYLON.PhysicsJoint.LockJoint:
  91671. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  91672. break;
  91673. case BABYLON.PhysicsJoint.PointToPointJoint:
  91674. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  91675. default:
  91676. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  91677. break;
  91678. }
  91679. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  91680. constraint.collideConnected = !!jointData.collision;
  91681. impostorJoint.joint.physicsJoint = constraint;
  91682. //don't add spring as constraint, as it is not one.
  91683. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  91684. this.world.addConstraint(constraint);
  91685. }
  91686. else {
  91687. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  91688. constraint.applyForce();
  91689. };
  91690. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  91691. }
  91692. };
  91693. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  91694. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  91695. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  91696. }
  91697. else {
  91698. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  91699. }
  91700. };
  91701. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  91702. var index;
  91703. var mat;
  91704. for (index = 0; index < this._physicsMaterials.length; index++) {
  91705. mat = this._physicsMaterials[index];
  91706. if (mat.friction === friction && mat.restitution === restitution) {
  91707. return mat;
  91708. }
  91709. }
  91710. var currentMat = new this.BJSCANNON.Material(name);
  91711. currentMat.friction = friction;
  91712. currentMat.restitution = restitution;
  91713. this._physicsMaterials.push(currentMat);
  91714. return currentMat;
  91715. };
  91716. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  91717. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  91718. };
  91719. CannonJSPlugin.prototype._createShape = function (impostor) {
  91720. var object = impostor.object;
  91721. var returnValue;
  91722. var extendSize = impostor.getObjectExtendSize();
  91723. switch (impostor.type) {
  91724. case BABYLON.PhysicsImpostor.SphereImpostor:
  91725. var radiusX = extendSize.x;
  91726. var radiusY = extendSize.y;
  91727. var radiusZ = extendSize.z;
  91728. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  91729. break;
  91730. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  91731. case BABYLON.PhysicsImpostor.CylinderImpostor:
  91732. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  91733. break;
  91734. case BABYLON.PhysicsImpostor.BoxImpostor:
  91735. var box = extendSize.scale(0.5);
  91736. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  91737. break;
  91738. case BABYLON.PhysicsImpostor.PlaneImpostor:
  91739. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  91740. returnValue = new this.BJSCANNON.Plane();
  91741. break;
  91742. case BABYLON.PhysicsImpostor.MeshImpostor:
  91743. // should transform the vertex data to world coordinates!!
  91744. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  91745. var rawFaces = object.getIndices ? object.getIndices() : [];
  91746. if (!rawVerts)
  91747. return;
  91748. // get only scale! so the object could transform correctly.
  91749. var oldPosition = object.position.clone();
  91750. var oldRotation = object.rotation && object.rotation.clone();
  91751. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  91752. object.position.copyFromFloats(0, 0, 0);
  91753. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  91754. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  91755. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  91756. var transform = object.computeWorldMatrix(true);
  91757. // convert rawVerts to object space
  91758. var temp = new Array();
  91759. var index;
  91760. for (index = 0; index < rawVerts.length; index += 3) {
  91761. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  91762. }
  91763. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  91764. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  91765. //now set back the transformation!
  91766. object.position.copyFrom(oldPosition);
  91767. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  91768. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  91769. break;
  91770. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  91771. var oldPosition2 = object.position.clone();
  91772. var oldRotation2 = object.rotation && object.rotation.clone();
  91773. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  91774. object.position.copyFromFloats(0, 0, 0);
  91775. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  91776. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  91777. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  91778. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  91779. returnValue = this._createHeightmap(object);
  91780. object.position.copyFrom(oldPosition2);
  91781. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  91782. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  91783. object.computeWorldMatrix(true);
  91784. break;
  91785. case BABYLON.PhysicsImpostor.ParticleImpostor:
  91786. returnValue = new this.BJSCANNON.Particle();
  91787. break;
  91788. }
  91789. return returnValue;
  91790. };
  91791. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  91792. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91793. var transform = object.computeWorldMatrix(true);
  91794. // convert rawVerts to object space
  91795. var temp = new Array();
  91796. var index;
  91797. for (index = 0; index < pos.length; index += 3) {
  91798. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  91799. }
  91800. pos = temp;
  91801. var matrix = new Array();
  91802. //For now pointDepth will not be used and will be automatically calculated.
  91803. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  91804. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  91805. var boundingInfo = object.getBoundingInfo();
  91806. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  91807. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  91808. var elementSize = dim * 2 / arraySize;
  91809. for (var i = 0; i < pos.length; i = i + 3) {
  91810. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  91811. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  91812. var y = -pos[i + 2] + minY;
  91813. if (!matrix[x]) {
  91814. matrix[x] = [];
  91815. }
  91816. if (!matrix[x][z]) {
  91817. matrix[x][z] = y;
  91818. }
  91819. matrix[x][z] = Math.max(y, matrix[x][z]);
  91820. }
  91821. for (var x = 0; x <= arraySize; ++x) {
  91822. if (!matrix[x]) {
  91823. var loc = 1;
  91824. while (!matrix[(x + loc) % arraySize]) {
  91825. loc++;
  91826. }
  91827. matrix[x] = matrix[(x + loc) % arraySize].slice();
  91828. //console.log("missing x", x);
  91829. }
  91830. for (var z = 0; z <= arraySize; ++z) {
  91831. if (!matrix[x][z]) {
  91832. var loc = 1;
  91833. var newValue;
  91834. while (newValue === undefined) {
  91835. newValue = matrix[x][(z + loc++) % arraySize];
  91836. }
  91837. matrix[x][z] = newValue;
  91838. }
  91839. }
  91840. }
  91841. var shape = new this.BJSCANNON.Heightfield(matrix, {
  91842. elementSize: elementSize
  91843. });
  91844. //For future reference, needed for body transformation
  91845. shape.minY = minY;
  91846. return shape;
  91847. };
  91848. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  91849. var object = impostor.object;
  91850. //make sure it is updated...
  91851. object.computeWorldMatrix && object.computeWorldMatrix(true);
  91852. // The delta between the mesh position and the mesh bounding box center
  91853. var bInfo = object.getBoundingInfo();
  91854. if (!bInfo)
  91855. return;
  91856. var center = impostor.getObjectCenter();
  91857. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  91858. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  91859. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  91860. this._tmpPosition.copyFrom(center);
  91861. var quaternion = object.rotationQuaternion;
  91862. if (!quaternion) {
  91863. return;
  91864. }
  91865. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  91866. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  91867. //-90 DEG in X, precalculated
  91868. quaternion = quaternion.multiply(this._minus90X);
  91869. //Invert! (Precalculated, 90 deg in X)
  91870. //No need to clone. this will never change.
  91871. impostor.setDeltaRotation(this._plus90X);
  91872. }
  91873. //If it is a heightfield, if should be centered.
  91874. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  91875. var mesh = object;
  91876. var boundingInfo = mesh.getBoundingInfo();
  91877. //calculate the correct body position:
  91878. var rotationQuaternion = mesh.rotationQuaternion;
  91879. mesh.rotationQuaternion = this._tmpUnityRotation;
  91880. mesh.computeWorldMatrix(true);
  91881. //get original center with no rotation
  91882. var c = center.clone();
  91883. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  91884. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  91885. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  91886. mesh.setPreTransformMatrix(p);
  91887. mesh.computeWorldMatrix(true);
  91888. //calculate the translation
  91889. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  91890. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  91891. //add it inverted to the delta
  91892. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  91893. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  91894. //rotation is back
  91895. mesh.rotationQuaternion = rotationQuaternion;
  91896. mesh.setPreTransformMatrix(oldPivot);
  91897. mesh.computeWorldMatrix(true);
  91898. }
  91899. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  91900. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  91901. //this._tmpPosition.copyFrom(object.position);
  91902. }
  91903. impostor.setDeltaPosition(this._tmpDeltaPosition);
  91904. //Now update the impostor object
  91905. impostor.physicsBody.position.copy(this._tmpPosition);
  91906. impostor.physicsBody.quaternion.copy(quaternion);
  91907. };
  91908. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  91909. impostor.object.position.copyFrom(impostor.physicsBody.position);
  91910. if (impostor.object.rotationQuaternion) {
  91911. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  91912. }
  91913. };
  91914. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  91915. impostor.physicsBody.position.copy(newPosition);
  91916. impostor.physicsBody.quaternion.copy(newRotation);
  91917. };
  91918. CannonJSPlugin.prototype.isSupported = function () {
  91919. return this.BJSCANNON !== undefined;
  91920. };
  91921. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  91922. impostor.physicsBody.velocity.copy(velocity);
  91923. };
  91924. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  91925. impostor.physicsBody.angularVelocity.copy(velocity);
  91926. };
  91927. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  91928. var v = impostor.physicsBody.velocity;
  91929. if (!v) {
  91930. return null;
  91931. }
  91932. return new BABYLON.Vector3(v.x, v.y, v.z);
  91933. };
  91934. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  91935. var v = impostor.physicsBody.angularVelocity;
  91936. if (!v) {
  91937. return null;
  91938. }
  91939. return new BABYLON.Vector3(v.x, v.y, v.z);
  91940. };
  91941. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  91942. impostor.physicsBody.mass = mass;
  91943. impostor.physicsBody.updateMassProperties();
  91944. };
  91945. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  91946. return impostor.physicsBody.mass;
  91947. };
  91948. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  91949. return impostor.physicsBody.material.friction;
  91950. };
  91951. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  91952. impostor.physicsBody.material.friction = friction;
  91953. };
  91954. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  91955. return impostor.physicsBody.material.restitution;
  91956. };
  91957. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  91958. impostor.physicsBody.material.restitution = restitution;
  91959. };
  91960. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  91961. impostor.physicsBody.sleep();
  91962. };
  91963. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  91964. impostor.physicsBody.wakeUp();
  91965. };
  91966. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  91967. joint.physicsJoint.distance = maxDistance;
  91968. };
  91969. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  91970. // if (!motorIndex) {
  91971. // joint.physicsJoint.enableMotor();
  91972. // }
  91973. // }
  91974. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  91975. // if (!motorIndex) {
  91976. // joint.physicsJoint.disableMotor();
  91977. // }
  91978. // }
  91979. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  91980. if (!motorIndex) {
  91981. joint.physicsJoint.enableMotor();
  91982. joint.physicsJoint.setMotorSpeed(speed);
  91983. if (maxForce) {
  91984. this.setLimit(joint, maxForce);
  91985. }
  91986. }
  91987. };
  91988. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  91989. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  91990. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  91991. };
  91992. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  91993. var body = impostor.physicsBody;
  91994. mesh.position.x = body.position.x;
  91995. mesh.position.y = body.position.y;
  91996. mesh.position.z = body.position.z;
  91997. if (mesh.rotationQuaternion) {
  91998. mesh.rotationQuaternion.x = body.quaternion.x;
  91999. mesh.rotationQuaternion.y = body.quaternion.y;
  92000. mesh.rotationQuaternion.z = body.quaternion.z;
  92001. mesh.rotationQuaternion.w = body.quaternion.w;
  92002. }
  92003. };
  92004. CannonJSPlugin.prototype.getRadius = function (impostor) {
  92005. var shape = impostor.physicsBody.shapes[0];
  92006. return shape.boundingSphereRadius;
  92007. };
  92008. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  92009. var shape = impostor.physicsBody.shapes[0];
  92010. result.x = shape.halfExtents.x * 2;
  92011. result.y = shape.halfExtents.y * 2;
  92012. result.z = shape.halfExtents.z * 2;
  92013. };
  92014. CannonJSPlugin.prototype.dispose = function () {
  92015. };
  92016. CannonJSPlugin.prototype._extendNamespace = function () {
  92017. //this will force cannon to execute at least one step when using interpolation
  92018. var step_tmp1 = new this.BJSCANNON.Vec3();
  92019. var Engine = this.BJSCANNON;
  92020. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  92021. maxSubSteps = maxSubSteps || 10;
  92022. timeSinceLastCalled = timeSinceLastCalled || 0;
  92023. if (timeSinceLastCalled === 0) {
  92024. this.internalStep(dt);
  92025. this.time += dt;
  92026. }
  92027. else {
  92028. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  92029. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  92030. var t0 = performance.now();
  92031. for (var i = 0; i !== internalSteps; i++) {
  92032. this.internalStep(dt);
  92033. if (performance.now() - t0 > dt * 1000) {
  92034. break;
  92035. }
  92036. }
  92037. this.time += timeSinceLastCalled;
  92038. var h = this.time % dt;
  92039. var h_div_dt = h / dt;
  92040. var interpvelo = step_tmp1;
  92041. var bodies = this.bodies;
  92042. for (var j = 0; j !== bodies.length; j++) {
  92043. var b = bodies[j];
  92044. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  92045. b.position.vsub(b.previousPosition, interpvelo);
  92046. interpvelo.scale(h_div_dt, interpvelo);
  92047. b.position.vadd(interpvelo, b.interpolatedPosition);
  92048. }
  92049. else {
  92050. b.interpolatedPosition.copy(b.position);
  92051. b.interpolatedQuaternion.copy(b.quaternion);
  92052. }
  92053. }
  92054. }
  92055. };
  92056. };
  92057. return CannonJSPlugin;
  92058. }());
  92059. BABYLON.CannonJSPlugin = CannonJSPlugin;
  92060. })(BABYLON || (BABYLON = {}));
  92061. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  92062. var BABYLON;
  92063. (function (BABYLON) {
  92064. var OimoJSPlugin = /** @class */ (function () {
  92065. function OimoJSPlugin(iterations) {
  92066. this.name = "OimoJSPlugin";
  92067. this._tmpImpostorsArray = [];
  92068. this._tmpPositionVector = BABYLON.Vector3.Zero();
  92069. this.BJSOIMO = OIMO;
  92070. this.world = new this.BJSOIMO.World({
  92071. iterations: iterations
  92072. });
  92073. this.world.clear();
  92074. }
  92075. OimoJSPlugin.prototype.setGravity = function (gravity) {
  92076. this.world.gravity.copy(gravity);
  92077. };
  92078. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  92079. this.world.timeStep = timeStep;
  92080. };
  92081. OimoJSPlugin.prototype.getTimeStep = function () {
  92082. return this.world.timeStep;
  92083. };
  92084. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  92085. var _this = this;
  92086. impostors.forEach(function (impostor) {
  92087. impostor.beforeStep();
  92088. });
  92089. this.world.step();
  92090. impostors.forEach(function (impostor) {
  92091. impostor.afterStep();
  92092. //update the ordered impostors array
  92093. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  92094. });
  92095. //check for collisions
  92096. var contact = this.world.contacts;
  92097. while (contact !== null) {
  92098. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  92099. contact = contact.next;
  92100. continue;
  92101. }
  92102. //is this body colliding with any other? get the impostor
  92103. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  92104. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  92105. if (!mainImpostor || !collidingImpostor) {
  92106. contact = contact.next;
  92107. continue;
  92108. }
  92109. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  92110. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  92111. contact = contact.next;
  92112. }
  92113. };
  92114. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  92115. var mass = impostor.physicsBody.mass;
  92116. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  92117. };
  92118. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  92119. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  92120. this.applyImpulse(impostor, force, contactPoint);
  92121. };
  92122. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  92123. var _this = this;
  92124. //parent-child relationship. Does this impostor has a parent impostor?
  92125. if (impostor.parent) {
  92126. if (impostor.physicsBody) {
  92127. this.removePhysicsBody(impostor);
  92128. //TODO is that needed?
  92129. impostor.forceUpdate();
  92130. }
  92131. return;
  92132. }
  92133. if (impostor.isBodyInitRequired()) {
  92134. var bodyConfig = {
  92135. name: impostor.uniqueId,
  92136. //Oimo must have mass, also for static objects.
  92137. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  92138. size: [],
  92139. type: [],
  92140. pos: [],
  92141. posShape: [],
  92142. rot: [],
  92143. rotShape: [],
  92144. move: impostor.getParam("mass") !== 0,
  92145. density: impostor.getParam("mass"),
  92146. friction: impostor.getParam("friction"),
  92147. restitution: impostor.getParam("restitution"),
  92148. //Supporting older versions of Oimo
  92149. world: this.world
  92150. };
  92151. var impostors = [impostor];
  92152. var addToArray = function (parent) {
  92153. if (!parent.getChildMeshes)
  92154. return;
  92155. parent.getChildMeshes().forEach(function (m) {
  92156. if (m.physicsImpostor) {
  92157. impostors.push(m.physicsImpostor);
  92158. //m.physicsImpostor._init();
  92159. }
  92160. });
  92161. };
  92162. addToArray(impostor.object);
  92163. var checkWithEpsilon_1 = function (value) {
  92164. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  92165. };
  92166. var globalQuaternion_1 = new BABYLON.Quaternion();
  92167. impostors.forEach(function (i) {
  92168. if (!i.object.rotationQuaternion) {
  92169. return;
  92170. }
  92171. //get the correct bounding box
  92172. var oldQuaternion = i.object.rotationQuaternion;
  92173. globalQuaternion_1 = oldQuaternion.clone();
  92174. var rot = oldQuaternion.toEulerAngles();
  92175. var extendSize = i.getObjectExtendSize();
  92176. var radToDeg = 57.295779513082320876;
  92177. if (i === impostor) {
  92178. var center = impostor.getObjectCenter();
  92179. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  92180. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  92181. //Can also use Array.prototype.push.apply
  92182. bodyConfig.pos.push(center.x);
  92183. bodyConfig.pos.push(center.y);
  92184. bodyConfig.pos.push(center.z);
  92185. bodyConfig.posShape.push(0, 0, 0);
  92186. //tmp solution
  92187. bodyConfig.rot.push(0);
  92188. bodyConfig.rot.push(0);
  92189. bodyConfig.rot.push(0);
  92190. bodyConfig.rotShape.push(0, 0, 0);
  92191. }
  92192. else {
  92193. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  92194. bodyConfig.posShape.push(localPosition.x);
  92195. bodyConfig.posShape.push(localPosition.y);
  92196. bodyConfig.posShape.push(localPosition.z);
  92197. bodyConfig.pos.push(0, 0, 0);
  92198. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  92199. bodyConfig.rot.push(0);
  92200. bodyConfig.rot.push(0);
  92201. bodyConfig.rot.push(0);
  92202. bodyConfig.rotShape.push(rot.x * radToDeg);
  92203. bodyConfig.rotShape.push(rot.y * radToDeg);
  92204. bodyConfig.rotShape.push(rot.z * radToDeg);
  92205. }
  92206. // register mesh
  92207. switch (i.type) {
  92208. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92209. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  92210. case BABYLON.PhysicsImpostor.SphereImpostor:
  92211. var radiusX = extendSize.x;
  92212. var radiusY = extendSize.y;
  92213. var radiusZ = extendSize.z;
  92214. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  92215. bodyConfig.type.push('sphere');
  92216. //due to the way oimo works with compounds, add 3 times
  92217. bodyConfig.size.push(size);
  92218. bodyConfig.size.push(size);
  92219. bodyConfig.size.push(size);
  92220. break;
  92221. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92222. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  92223. var sizeY = checkWithEpsilon_1(extendSize.y);
  92224. bodyConfig.type.push('cylinder');
  92225. bodyConfig.size.push(sizeX);
  92226. bodyConfig.size.push(sizeY);
  92227. //due to the way oimo works with compounds, add one more value.
  92228. bodyConfig.size.push(sizeY);
  92229. break;
  92230. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92231. case BABYLON.PhysicsImpostor.BoxImpostor:
  92232. default:
  92233. var sizeX = checkWithEpsilon_1(extendSize.x);
  92234. var sizeY = checkWithEpsilon_1(extendSize.y);
  92235. var sizeZ = checkWithEpsilon_1(extendSize.z);
  92236. bodyConfig.type.push('box');
  92237. //if (i === impostor) {
  92238. bodyConfig.size.push(sizeX);
  92239. bodyConfig.size.push(sizeY);
  92240. bodyConfig.size.push(sizeZ);
  92241. //} else {
  92242. // bodyConfig.size.push(0,0,0);
  92243. //}
  92244. break;
  92245. }
  92246. //actually not needed, but hey...
  92247. i.object.rotationQuaternion = oldQuaternion;
  92248. });
  92249. impostor.physicsBody = this.world.add(bodyConfig);
  92250. // set the quaternion, ignoring the previously defined (euler) rotation
  92251. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  92252. // update with delta 0, so the body will reveive the new rotation.
  92253. impostor.physicsBody.updatePosition(0);
  92254. }
  92255. else {
  92256. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  92257. }
  92258. impostor.setDeltaPosition(this._tmpPositionVector);
  92259. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  92260. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  92261. };
  92262. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92263. //impostor.physicsBody.dispose();
  92264. //Same as : (older oimo versions)
  92265. this.world.removeRigidBody(impostor.physicsBody);
  92266. };
  92267. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92268. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92269. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92270. if (!mainBody || !connectedBody) {
  92271. return;
  92272. }
  92273. var jointData = impostorJoint.joint.jointData;
  92274. var options = jointData.nativeParams || {};
  92275. var type;
  92276. var nativeJointData = {
  92277. body1: mainBody,
  92278. body2: connectedBody,
  92279. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  92280. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  92281. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  92282. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  92283. min: options.min,
  92284. max: options.max,
  92285. collision: options.collision || jointData.collision,
  92286. spring: options.spring,
  92287. //supporting older version of Oimo
  92288. world: this.world
  92289. };
  92290. switch (impostorJoint.joint.type) {
  92291. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92292. type = "jointBall";
  92293. break;
  92294. case BABYLON.PhysicsJoint.SpringJoint:
  92295. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  92296. var springData = jointData;
  92297. nativeJointData.min = springData.length || nativeJointData.min;
  92298. //Max should also be set, just make sure it is at least min
  92299. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  92300. case BABYLON.PhysicsJoint.DistanceJoint:
  92301. type = "jointDistance";
  92302. nativeJointData.max = jointData.maxDistance;
  92303. break;
  92304. case BABYLON.PhysicsJoint.PrismaticJoint:
  92305. type = "jointPrisme";
  92306. break;
  92307. case BABYLON.PhysicsJoint.SliderJoint:
  92308. type = "jointSlide";
  92309. break;
  92310. case BABYLON.PhysicsJoint.WheelJoint:
  92311. type = "jointWheel";
  92312. break;
  92313. case BABYLON.PhysicsJoint.HingeJoint:
  92314. default:
  92315. type = "jointHinge";
  92316. break;
  92317. }
  92318. nativeJointData.type = type;
  92319. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  92320. };
  92321. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92322. //Bug in Oimo prevents us from disposing a joint in the playground
  92323. //joint.joint.physicsJoint.dispose();
  92324. //So we will bruteforce it!
  92325. try {
  92326. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  92327. }
  92328. catch (e) {
  92329. BABYLON.Tools.Warn(e);
  92330. }
  92331. };
  92332. OimoJSPlugin.prototype.isSupported = function () {
  92333. return this.BJSOIMO !== undefined;
  92334. };
  92335. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92336. if (!impostor.physicsBody.sleeping) {
  92337. //TODO check that
  92338. /*if (impostor.physicsBody.shapes.next) {
  92339. var parentShape = this._getLastShape(impostor.physicsBody);
  92340. impostor.object.position.copyFrom(parentShape.position);
  92341. console.log(parentShape.position);
  92342. } else {*/
  92343. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  92344. //}
  92345. if (impostor.object.rotationQuaternion) {
  92346. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  92347. }
  92348. }
  92349. };
  92350. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92351. var body = impostor.physicsBody;
  92352. body.position.copy(newPosition);
  92353. body.orientation.copy(newRotation);
  92354. body.syncShapes();
  92355. body.awake();
  92356. };
  92357. /*private _getLastShape(body: any): any {
  92358. var lastShape = body.shapes;
  92359. while (lastShape.next) {
  92360. lastShape = lastShape.next;
  92361. }
  92362. return lastShape;
  92363. }*/
  92364. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92365. impostor.physicsBody.linearVelocity.copy(velocity);
  92366. };
  92367. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92368. impostor.physicsBody.angularVelocity.copy(velocity);
  92369. };
  92370. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92371. var v = impostor.physicsBody.linearVelocity;
  92372. if (!v) {
  92373. return null;
  92374. }
  92375. return new BABYLON.Vector3(v.x, v.y, v.z);
  92376. };
  92377. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92378. var v = impostor.physicsBody.angularVelocity;
  92379. if (!v) {
  92380. return null;
  92381. }
  92382. return new BABYLON.Vector3(v.x, v.y, v.z);
  92383. };
  92384. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92385. var staticBody = mass === 0;
  92386. //this will actually set the body's density and not its mass.
  92387. //But this is how oimo treats the mass variable.
  92388. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  92389. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  92390. };
  92391. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  92392. return impostor.physicsBody.shapes.density;
  92393. };
  92394. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  92395. return impostor.physicsBody.shapes.friction;
  92396. };
  92397. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92398. impostor.physicsBody.shapes.friction = friction;
  92399. };
  92400. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92401. return impostor.physicsBody.shapes.restitution;
  92402. };
  92403. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92404. impostor.physicsBody.shapes.restitution = restitution;
  92405. };
  92406. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  92407. impostor.physicsBody.sleep();
  92408. };
  92409. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  92410. impostor.physicsBody.awake();
  92411. };
  92412. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92413. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  92414. if (minDistance !== void 0) {
  92415. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  92416. }
  92417. };
  92418. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  92419. //TODO separate rotational and transational motors.
  92420. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  92421. if (motor) {
  92422. motor.setMotor(speed, maxForce);
  92423. }
  92424. };
  92425. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  92426. //TODO separate rotational and transational motors.
  92427. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  92428. if (motor) {
  92429. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  92430. }
  92431. };
  92432. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  92433. var body = impostor.physicsBody;
  92434. mesh.position.x = body.position.x;
  92435. mesh.position.y = body.position.y;
  92436. mesh.position.z = body.position.z;
  92437. if (mesh.rotationQuaternion) {
  92438. mesh.rotationQuaternion.x = body.orientation.x;
  92439. mesh.rotationQuaternion.y = body.orientation.y;
  92440. mesh.rotationQuaternion.z = body.orientation.z;
  92441. mesh.rotationQuaternion.w = body.orientation.s;
  92442. }
  92443. };
  92444. OimoJSPlugin.prototype.getRadius = function (impostor) {
  92445. return impostor.physicsBody.shapes.radius;
  92446. };
  92447. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  92448. var shape = impostor.physicsBody.shapes;
  92449. result.x = shape.halfWidth * 2;
  92450. result.y = shape.halfHeight * 2;
  92451. result.z = shape.halfDepth * 2;
  92452. };
  92453. OimoJSPlugin.prototype.dispose = function () {
  92454. this.world.clear();
  92455. };
  92456. return OimoJSPlugin;
  92457. }());
  92458. BABYLON.OimoJSPlugin = OimoJSPlugin;
  92459. })(BABYLON || (BABYLON = {}));
  92460. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  92461. var BABYLON;
  92462. (function (BABYLON) {
  92463. /**
  92464. * Gets the current physics engine
  92465. * @returns a IPhysicsEngine or null if none attached
  92466. */
  92467. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  92468. return this._physicsEngine;
  92469. };
  92470. /**
  92471. * Enables physics to the current scene
  92472. * @param gravity defines the scene's gravity for the physics engine
  92473. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  92474. * @return a boolean indicating if the physics engine was initialized
  92475. */
  92476. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  92477. if (gravity === void 0) { gravity = null; }
  92478. if (this._physicsEngine) {
  92479. return true;
  92480. }
  92481. // Register the component to the scene
  92482. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  92483. if (!component) {
  92484. component = new PhysicsEngineSceneComponent(this);
  92485. this._addComponent(component);
  92486. }
  92487. try {
  92488. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  92489. return true;
  92490. }
  92491. catch (e) {
  92492. BABYLON.Tools.Error(e.message);
  92493. return false;
  92494. }
  92495. };
  92496. /**
  92497. * Disables and disposes the physics engine associated with the scene
  92498. */
  92499. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  92500. if (!this._physicsEngine) {
  92501. return;
  92502. }
  92503. this._physicsEngine.dispose();
  92504. this._physicsEngine = null;
  92505. };
  92506. /**
  92507. * Gets a boolean indicating if there is an active physics engine
  92508. * @returns a boolean indicating if there is an active physics engine
  92509. */
  92510. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  92511. return this._physicsEngine !== undefined;
  92512. };
  92513. /**
  92514. * Deletes a physics compound impostor
  92515. * @param compound defines the compound to delete
  92516. */
  92517. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  92518. var mesh = compound.parts[0].mesh;
  92519. if (mesh.physicsImpostor) {
  92520. mesh.physicsImpostor.dispose( /*true*/);
  92521. mesh.physicsImpostor = null;
  92522. }
  92523. };
  92524. /** @hidden */
  92525. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  92526. if (this._physicsEngine) {
  92527. this.onBeforePhysicsObservable.notifyObservers(this);
  92528. this._physicsEngine._step(step / 1000);
  92529. this.onAfterPhysicsObservable.notifyObservers(this);
  92530. }
  92531. };
  92532. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  92533. get: function () {
  92534. return this._physicsImpostor;
  92535. },
  92536. set: function (value) {
  92537. var _this = this;
  92538. if (this._physicsImpostor === value) {
  92539. return;
  92540. }
  92541. if (this._disposePhysicsObserver) {
  92542. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  92543. }
  92544. this._physicsImpostor = value;
  92545. if (value) {
  92546. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  92547. // Physics
  92548. if (_this.physicsImpostor) {
  92549. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  92550. _this.physicsImpostor = null;
  92551. }
  92552. });
  92553. }
  92554. },
  92555. enumerable: true,
  92556. configurable: true
  92557. });
  92558. /**
  92559. * Gets the current physics impostor
  92560. * @see http://doc.babylonjs.com/features/physics_engine
  92561. * @returns a physics impostor or null
  92562. */
  92563. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  92564. return this.physicsImpostor;
  92565. };
  92566. /**
  92567. * Apply a physic impulse to the mesh
  92568. * @param force defines the force to apply
  92569. * @param contactPoint defines where to apply the force
  92570. * @returns the current mesh
  92571. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  92572. */
  92573. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  92574. if (!this.physicsImpostor) {
  92575. return this;
  92576. }
  92577. this.physicsImpostor.applyImpulse(force, contactPoint);
  92578. return this;
  92579. };
  92580. /**
  92581. * Creates a physic joint between two meshes
  92582. * @param otherMesh defines the other mesh to use
  92583. * @param pivot1 defines the pivot to use on this mesh
  92584. * @param pivot2 defines the pivot to use on the other mesh
  92585. * @param options defines additional options (can be plugin dependent)
  92586. * @returns the current mesh
  92587. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  92588. */
  92589. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  92590. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  92591. return this;
  92592. }
  92593. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  92594. mainPivot: pivot1,
  92595. connectedPivot: pivot2,
  92596. nativeParams: options
  92597. });
  92598. return this;
  92599. };
  92600. /**
  92601. * Defines the physics engine scene component responsible to manage a physics engine
  92602. */
  92603. var PhysicsEngineSceneComponent = /** @class */ (function () {
  92604. /**
  92605. * Creates a new instance of the component for the given scene
  92606. * @param scene Defines the scene to register the component in
  92607. */
  92608. function PhysicsEngineSceneComponent(scene) {
  92609. var _this = this;
  92610. /**
  92611. * The component name helpful to identify the component in the list of scene components.
  92612. */
  92613. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  92614. this.scene = scene;
  92615. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  92616. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  92617. // Replace the function used to get the deterministic frame time
  92618. this.scene.getDeterministicFrameTime = function () {
  92619. if (_this.scene._physicsEngine) {
  92620. return _this.scene._physicsEngine.getTimeStep() * 1000;
  92621. }
  92622. return 1000.0 / 60.0;
  92623. };
  92624. }
  92625. /**
  92626. * Registers the component in a given scene
  92627. */
  92628. PhysicsEngineSceneComponent.prototype.register = function () {
  92629. };
  92630. /**
  92631. * Rebuilds the elements related to this component in case of
  92632. * context lost for instance.
  92633. */
  92634. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  92635. // Nothing to do for this component
  92636. };
  92637. /**
  92638. * Disposes the component and the associated ressources
  92639. */
  92640. PhysicsEngineSceneComponent.prototype.dispose = function () {
  92641. this.scene.onBeforePhysicsObservable.clear();
  92642. this.scene.onAfterPhysicsObservable.clear();
  92643. if (this.scene._physicsEngine) {
  92644. this.scene.disablePhysicsEngine();
  92645. }
  92646. };
  92647. return PhysicsEngineSceneComponent;
  92648. }());
  92649. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  92650. })(BABYLON || (BABYLON = {}));
  92651. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  92652. var BABYLON;
  92653. (function (BABYLON) {
  92654. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  92655. // All values and structures referenced from:
  92656. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  92657. var DDS_MAGIC = 0x20534444;
  92658. var
  92659. //DDSD_CAPS = 0x1,
  92660. //DDSD_HEIGHT = 0x2,
  92661. //DDSD_WIDTH = 0x4,
  92662. //DDSD_PITCH = 0x8,
  92663. //DDSD_PIXELFORMAT = 0x1000,
  92664. DDSD_MIPMAPCOUNT = 0x20000;
  92665. //DDSD_LINEARSIZE = 0x80000,
  92666. //DDSD_DEPTH = 0x800000;
  92667. // var DDSCAPS_COMPLEX = 0x8,
  92668. // DDSCAPS_MIPMAP = 0x400000,
  92669. // DDSCAPS_TEXTURE = 0x1000;
  92670. var DDSCAPS2_CUBEMAP = 0x200;
  92671. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  92672. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  92673. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  92674. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  92675. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  92676. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  92677. // DDSCAPS2_VOLUME = 0x200000;
  92678. var
  92679. //DDPF_ALPHAPIXELS = 0x1,
  92680. //DDPF_ALPHA = 0x2,
  92681. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  92682. //DDPF_YUV = 0x200,
  92683. DDPF_LUMINANCE = 0x20000;
  92684. function FourCCToInt32(value) {
  92685. return value.charCodeAt(0) +
  92686. (value.charCodeAt(1) << 8) +
  92687. (value.charCodeAt(2) << 16) +
  92688. (value.charCodeAt(3) << 24);
  92689. }
  92690. function Int32ToFourCC(value) {
  92691. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  92692. }
  92693. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  92694. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  92695. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  92696. var FOURCC_DX10 = FourCCToInt32("DX10");
  92697. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  92698. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  92699. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  92700. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  92701. var headerLengthInt = 31; // The header length in 32 bit ints
  92702. // Offsets into the header array
  92703. var off_magic = 0;
  92704. var off_size = 1;
  92705. var off_flags = 2;
  92706. var off_height = 3;
  92707. var off_width = 4;
  92708. var off_mipmapCount = 7;
  92709. var off_pfFlags = 20;
  92710. var off_pfFourCC = 21;
  92711. var off_RGBbpp = 22;
  92712. var off_RMask = 23;
  92713. var off_GMask = 24;
  92714. var off_BMask = 25;
  92715. var off_AMask = 26;
  92716. // var off_caps1 = 27;
  92717. var off_caps2 = 28;
  92718. // var off_caps3 = 29;
  92719. // var off_caps4 = 30;
  92720. var off_dxgiFormat = 32;
  92721. ;
  92722. var DDSTools = /** @class */ (function () {
  92723. function DDSTools() {
  92724. }
  92725. DDSTools.GetDDSInfo = function (arrayBuffer) {
  92726. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  92727. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  92728. var mipmapCount = 1;
  92729. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  92730. mipmapCount = Math.max(1, header[off_mipmapCount]);
  92731. }
  92732. var fourCC = header[off_pfFourCC];
  92733. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  92734. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92735. switch (fourCC) {
  92736. case FOURCC_D3DFMT_R16G16B16A16F:
  92737. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92738. break;
  92739. case FOURCC_D3DFMT_R32G32B32A32F:
  92740. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92741. break;
  92742. case FOURCC_DX10:
  92743. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  92744. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92745. break;
  92746. }
  92747. }
  92748. return {
  92749. width: header[off_width],
  92750. height: header[off_height],
  92751. mipmapCount: mipmapCount,
  92752. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  92753. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  92754. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  92755. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  92756. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  92757. dxgiFormat: dxgiFormat,
  92758. textureType: textureType
  92759. };
  92760. };
  92761. DDSTools._ToHalfFloat = function (value) {
  92762. if (!DDSTools._FloatView) {
  92763. DDSTools._FloatView = new Float32Array(1);
  92764. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  92765. }
  92766. DDSTools._FloatView[0] = value;
  92767. var x = DDSTools._Int32View[0];
  92768. var bits = (x >> 16) & 0x8000; /* Get the sign */
  92769. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  92770. var e = (x >> 23) & 0xff; /* Using int is faster here */
  92771. /* If zero, or denormal, or exponent underflows too much for a denormal
  92772. * half, return signed zero. */
  92773. if (e < 103) {
  92774. return bits;
  92775. }
  92776. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  92777. if (e > 142) {
  92778. bits |= 0x7c00;
  92779. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  92780. * not Inf, so make sure we set one mantissa bit too. */
  92781. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  92782. return bits;
  92783. }
  92784. /* If exponent underflows but not too much, return a denormal */
  92785. if (e < 113) {
  92786. m |= 0x0800;
  92787. /* Extra rounding may overflow and set mantissa to 0 and exponent
  92788. * to 1, which is OK. */
  92789. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  92790. return bits;
  92791. }
  92792. bits |= ((e - 112) << 10) | (m >> 1);
  92793. bits += m & 1;
  92794. return bits;
  92795. };
  92796. DDSTools._FromHalfFloat = function (value) {
  92797. var s = (value & 0x8000) >> 15;
  92798. var e = (value & 0x7C00) >> 10;
  92799. var f = value & 0x03FF;
  92800. if (e === 0) {
  92801. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  92802. }
  92803. else if (e == 0x1F) {
  92804. return f ? NaN : ((s ? -1 : 1) * Infinity);
  92805. }
  92806. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  92807. };
  92808. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92809. var destArray = new Float32Array(dataLength);
  92810. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  92811. var index = 0;
  92812. for (var y = 0; y < height; y++) {
  92813. for (var x = 0; x < width; x++) {
  92814. var srcPos = (x + y * width) * 4;
  92815. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  92816. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  92817. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  92818. if (DDSTools.StoreLODInAlphaChannel) {
  92819. destArray[index + 3] = lod;
  92820. }
  92821. else {
  92822. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  92823. }
  92824. index += 4;
  92825. }
  92826. }
  92827. return destArray;
  92828. };
  92829. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92830. if (DDSTools.StoreLODInAlphaChannel) {
  92831. var destArray = new Uint16Array(dataLength);
  92832. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  92833. var index = 0;
  92834. for (var y = 0; y < height; y++) {
  92835. for (var x = 0; x < width; x++) {
  92836. var srcPos = (x + y * width) * 4;
  92837. destArray[index] = srcData[srcPos];
  92838. destArray[index + 1] = srcData[srcPos + 1];
  92839. destArray[index + 2] = srcData[srcPos + 2];
  92840. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  92841. index += 4;
  92842. }
  92843. }
  92844. return destArray;
  92845. }
  92846. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  92847. };
  92848. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92849. if (DDSTools.StoreLODInAlphaChannel) {
  92850. var destArray = new Float32Array(dataLength);
  92851. var srcData = new Float32Array(arrayBuffer, dataOffset);
  92852. var index = 0;
  92853. for (var y = 0; y < height; y++) {
  92854. for (var x = 0; x < width; x++) {
  92855. var srcPos = (x + y * width) * 4;
  92856. destArray[index] = srcData[srcPos];
  92857. destArray[index + 1] = srcData[srcPos + 1];
  92858. destArray[index + 2] = srcData[srcPos + 2];
  92859. destArray[index + 3] = lod;
  92860. index += 4;
  92861. }
  92862. }
  92863. return destArray;
  92864. }
  92865. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  92866. };
  92867. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92868. var destArray = new Uint8Array(dataLength);
  92869. var srcData = new Float32Array(arrayBuffer, dataOffset);
  92870. var index = 0;
  92871. for (var y = 0; y < height; y++) {
  92872. for (var x = 0; x < width; x++) {
  92873. var srcPos = (x + y * width) * 4;
  92874. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  92875. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  92876. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  92877. if (DDSTools.StoreLODInAlphaChannel) {
  92878. destArray[index + 3] = lod;
  92879. }
  92880. else {
  92881. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  92882. }
  92883. index += 4;
  92884. }
  92885. }
  92886. return destArray;
  92887. };
  92888. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92889. var destArray = new Uint8Array(dataLength);
  92890. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  92891. var index = 0;
  92892. for (var y = 0; y < height; y++) {
  92893. for (var x = 0; x < width; x++) {
  92894. var srcPos = (x + y * width) * 4;
  92895. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  92896. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  92897. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  92898. if (DDSTools.StoreLODInAlphaChannel) {
  92899. destArray[index + 3] = lod;
  92900. }
  92901. else {
  92902. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  92903. }
  92904. index += 4;
  92905. }
  92906. }
  92907. return destArray;
  92908. };
  92909. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  92910. var byteArray = new Uint8Array(dataLength);
  92911. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  92912. var index = 0;
  92913. for (var y = 0; y < height; y++) {
  92914. for (var x = 0; x < width; x++) {
  92915. var srcPos = (x + y * width) * 4;
  92916. byteArray[index] = srcData[srcPos + rOffset];
  92917. byteArray[index + 1] = srcData[srcPos + gOffset];
  92918. byteArray[index + 2] = srcData[srcPos + bOffset];
  92919. byteArray[index + 3] = srcData[srcPos + aOffset];
  92920. index += 4;
  92921. }
  92922. }
  92923. return byteArray;
  92924. };
  92925. DDSTools._ExtractLongWordOrder = function (value) {
  92926. if (value === 0 || value === 255 || value === -16777216) {
  92927. return 0;
  92928. }
  92929. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  92930. };
  92931. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  92932. var byteArray = new Uint8Array(dataLength);
  92933. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  92934. var index = 0;
  92935. for (var y = 0; y < height; y++) {
  92936. for (var x = 0; x < width; x++) {
  92937. var srcPos = (x + y * width) * 3;
  92938. byteArray[index] = srcData[srcPos + rOffset];
  92939. byteArray[index + 1] = srcData[srcPos + gOffset];
  92940. byteArray[index + 2] = srcData[srcPos + bOffset];
  92941. index += 3;
  92942. }
  92943. }
  92944. return byteArray;
  92945. };
  92946. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  92947. var byteArray = new Uint8Array(dataLength);
  92948. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  92949. var index = 0;
  92950. for (var y = 0; y < height; y++) {
  92951. for (var x = 0; x < width; x++) {
  92952. var srcPos = (x + y * width);
  92953. byteArray[index] = srcData[srcPos];
  92954. index++;
  92955. }
  92956. }
  92957. return byteArray;
  92958. };
  92959. /**
  92960. * Uploads DDS Levels to a Babylon Texture
  92961. * @hidden
  92962. */
  92963. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  92964. if (lodIndex === void 0) { lodIndex = -1; }
  92965. var sphericalPolynomialFaces = null;
  92966. if (info.sphericalPolynomial) {
  92967. sphericalPolynomialFaces = new Array();
  92968. }
  92969. var ext = engine.getCaps().s3tc;
  92970. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  92971. var fourCC, width, height, dataLength = 0, dataOffset;
  92972. var byteArray, mipmapCount, mip;
  92973. var internalCompressedFormat = 0;
  92974. var blockBytes = 1;
  92975. if (header[off_magic] !== DDS_MAGIC) {
  92976. BABYLON.Tools.Error("Invalid magic number in DDS header");
  92977. return;
  92978. }
  92979. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  92980. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  92981. return;
  92982. }
  92983. if (info.isCompressed && !ext) {
  92984. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  92985. return;
  92986. }
  92987. var bpp = header[off_RGBbpp];
  92988. dataOffset = header[off_size] + 4;
  92989. var computeFormats = false;
  92990. if (info.isFourCC) {
  92991. fourCC = header[off_pfFourCC];
  92992. switch (fourCC) {
  92993. case FOURCC_DXT1:
  92994. blockBytes = 8;
  92995. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  92996. break;
  92997. case FOURCC_DXT3:
  92998. blockBytes = 16;
  92999. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  93000. break;
  93001. case FOURCC_DXT5:
  93002. blockBytes = 16;
  93003. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  93004. break;
  93005. case FOURCC_D3DFMT_R16G16B16A16F:
  93006. computeFormats = true;
  93007. break;
  93008. case FOURCC_D3DFMT_R32G32B32A32F:
  93009. computeFormats = true;
  93010. break;
  93011. case FOURCC_DX10:
  93012. // There is an additionnal header so dataOffset need to be changed
  93013. dataOffset += 5 * 4; // 5 uints
  93014. var supported = false;
  93015. switch (info.dxgiFormat) {
  93016. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  93017. computeFormats = true;
  93018. supported = true;
  93019. break;
  93020. case DXGI_FORMAT_B8G8R8X8_UNORM:
  93021. info.isRGB = true;
  93022. info.isFourCC = false;
  93023. bpp = 32;
  93024. supported = true;
  93025. break;
  93026. }
  93027. if (supported) {
  93028. break;
  93029. }
  93030. default:
  93031. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  93032. return;
  93033. }
  93034. }
  93035. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  93036. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  93037. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  93038. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  93039. if (computeFormats) {
  93040. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  93041. }
  93042. mipmapCount = 1;
  93043. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  93044. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93045. }
  93046. for (var face = 0; face < faces; face++) {
  93047. width = header[off_width];
  93048. height = header[off_height];
  93049. for (mip = 0; mip < mipmapCount; ++mip) {
  93050. if (lodIndex === -1 || lodIndex === mip) {
  93051. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  93052. var i = (lodIndex === -1) ? mip : 0;
  93053. if (!info.isCompressed && info.isFourCC) {
  93054. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  93055. dataLength = width * height * 4;
  93056. var floatArray = null;
  93057. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  93058. if (bpp === 128) {
  93059. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93060. if (sphericalPolynomialFaces && i == 0) {
  93061. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93062. }
  93063. }
  93064. else if (bpp === 64) {
  93065. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93066. if (sphericalPolynomialFaces && i == 0) {
  93067. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93068. }
  93069. }
  93070. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93071. }
  93072. else {
  93073. if (bpp === 128) {
  93074. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93075. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93076. if (sphericalPolynomialFaces && i == 0) {
  93077. sphericalPolynomialFaces.push(floatArray);
  93078. }
  93079. }
  93080. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  93081. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93082. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93083. if (sphericalPolynomialFaces && i == 0) {
  93084. sphericalPolynomialFaces.push(floatArray);
  93085. }
  93086. }
  93087. else { // 64
  93088. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93089. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93090. if (sphericalPolynomialFaces && i == 0) {
  93091. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93092. }
  93093. }
  93094. }
  93095. if (floatArray) {
  93096. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  93097. }
  93098. }
  93099. else if (info.isRGB) {
  93100. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93101. if (bpp === 24) {
  93102. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  93103. dataLength = width * height * 3;
  93104. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  93105. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93106. }
  93107. else { // 32
  93108. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  93109. dataLength = width * height * 4;
  93110. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  93111. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93112. }
  93113. }
  93114. else if (info.isLuminance) {
  93115. var unpackAlignment = engine._getUnpackAlignement();
  93116. var unpaddedRowSize = width;
  93117. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  93118. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  93119. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  93120. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  93121. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93122. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93123. }
  93124. else {
  93125. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  93126. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  93127. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93128. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  93129. }
  93130. }
  93131. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  93132. width *= 0.5;
  93133. height *= 0.5;
  93134. width = Math.max(1.0, width);
  93135. height = Math.max(1.0, height);
  93136. }
  93137. if (currentFace !== undefined) {
  93138. // Loading a single face
  93139. break;
  93140. }
  93141. }
  93142. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  93143. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  93144. size: header[off_width],
  93145. right: sphericalPolynomialFaces[0],
  93146. left: sphericalPolynomialFaces[1],
  93147. up: sphericalPolynomialFaces[2],
  93148. down: sphericalPolynomialFaces[3],
  93149. front: sphericalPolynomialFaces[4],
  93150. back: sphericalPolynomialFaces[5],
  93151. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  93152. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  93153. gammaSpace: false,
  93154. });
  93155. }
  93156. else {
  93157. info.sphericalPolynomial = undefined;
  93158. }
  93159. };
  93160. DDSTools.StoreLODInAlphaChannel = false;
  93161. return DDSTools;
  93162. }());
  93163. BABYLON.DDSTools = DDSTools;
  93164. })(BABYLON || (BABYLON = {}));
  93165. //# sourceMappingURL=babylon.dds.js.map
  93166. var BABYLON;
  93167. (function (BABYLON) {
  93168. /**
  93169. * Implementation of the DDS Texture Loader.
  93170. */
  93171. var DDSTextureLoader = /** @class */ (function () {
  93172. function DDSTextureLoader() {
  93173. /**
  93174. * Defines wether the loader supports cascade loading the different faces.
  93175. */
  93176. this.supportCascades = true;
  93177. }
  93178. /**
  93179. * This returns if the loader support the current file information.
  93180. * @param extension defines the file extension of the file being loaded
  93181. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93182. * @param fallback defines the fallback internal texture if any
  93183. * @param isBase64 defines whether the texture is encoded as a base64
  93184. * @param isBuffer defines whether the texture data are stored as a buffer
  93185. * @returns true if the loader can load the specified file
  93186. */
  93187. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93188. return extension.indexOf(".dds") === 0;
  93189. };
  93190. /**
  93191. * Transform the url before loading if required.
  93192. * @param rootUrl the url of the texture
  93193. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93194. * @returns the transformed texture
  93195. */
  93196. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93197. return rootUrl;
  93198. };
  93199. /**
  93200. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93201. * @param rootUrl the url of the texture
  93202. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93203. * @returns the fallback texture
  93204. */
  93205. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93206. return null;
  93207. };
  93208. /**
  93209. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93210. * @param data contains the texture data
  93211. * @param texture defines the BabylonJS internal texture
  93212. * @param createPolynomials will be true if polynomials have been requested
  93213. * @param onLoad defines the callback to trigger once the texture is ready
  93214. * @param onError defines the callback to trigger in case of error
  93215. */
  93216. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  93217. var engine = texture.getEngine();
  93218. var info;
  93219. var loadMipmap = false;
  93220. if (Array.isArray(imgs)) {
  93221. for (var index = 0; index < imgs.length; index++) {
  93222. var data_1 = imgs[index];
  93223. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  93224. texture.width = info.width;
  93225. texture.height = info.height;
  93226. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  93227. engine._unpackFlipY(info.isCompressed);
  93228. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  93229. if (!info.isFourCC && info.mipmapCount === 1) {
  93230. engine.generateMipMapsForCubemap(texture);
  93231. }
  93232. }
  93233. }
  93234. else {
  93235. var data = imgs;
  93236. info = BABYLON.DDSTools.GetDDSInfo(data);
  93237. texture.width = info.width;
  93238. texture.height = info.height;
  93239. if (createPolynomials) {
  93240. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  93241. }
  93242. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  93243. engine._unpackFlipY(info.isCompressed);
  93244. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  93245. if (!info.isFourCC && info.mipmapCount === 1) {
  93246. engine.generateMipMapsForCubemap(texture);
  93247. }
  93248. }
  93249. engine._setCubeMapTextureParams(loadMipmap);
  93250. texture.isReady = true;
  93251. if (onLoad) {
  93252. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  93253. }
  93254. };
  93255. /**
  93256. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93257. * @param data contains the texture data
  93258. * @param texture defines the BabylonJS internal texture
  93259. * @param callback defines the method to call once ready to upload
  93260. */
  93261. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  93262. var info = BABYLON.DDSTools.GetDDSInfo(data);
  93263. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  93264. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  93265. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  93266. });
  93267. };
  93268. return DDSTextureLoader;
  93269. }());
  93270. // Register the loader.
  93271. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  93272. })(BABYLON || (BABYLON = {}));
  93273. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  93274. var BABYLON;
  93275. (function (BABYLON) {
  93276. /*
  93277. * Based on jsTGALoader - Javascript loader for TGA file
  93278. * By Vincent Thibault
  93279. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  93280. */
  93281. var TGATools = /** @class */ (function () {
  93282. function TGATools() {
  93283. }
  93284. TGATools.GetTGAHeader = function (data) {
  93285. var offset = 0;
  93286. var header = {
  93287. id_length: data[offset++],
  93288. colormap_type: data[offset++],
  93289. image_type: data[offset++],
  93290. colormap_index: data[offset++] | data[offset++] << 8,
  93291. colormap_length: data[offset++] | data[offset++] << 8,
  93292. colormap_size: data[offset++],
  93293. origin: [
  93294. data[offset++] | data[offset++] << 8,
  93295. data[offset++] | data[offset++] << 8
  93296. ],
  93297. width: data[offset++] | data[offset++] << 8,
  93298. height: data[offset++] | data[offset++] << 8,
  93299. pixel_size: data[offset++],
  93300. flags: data[offset++]
  93301. };
  93302. return header;
  93303. };
  93304. /**
  93305. * Uploads TGA content to a Babylon Texture
  93306. * @hidden
  93307. */
  93308. TGATools.UploadContent = function (texture, data) {
  93309. // Not enough data to contain header ?
  93310. if (data.length < 19) {
  93311. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  93312. return;
  93313. }
  93314. // Read Header
  93315. var offset = 18;
  93316. var header = TGATools.GetTGAHeader(data);
  93317. // Assume it's a valid Targa file.
  93318. if (header.id_length + offset > data.length) {
  93319. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  93320. return;
  93321. }
  93322. // Skip not needed data
  93323. offset += header.id_length;
  93324. var use_rle = false;
  93325. var use_pal = false;
  93326. var use_grey = false;
  93327. // Get some informations.
  93328. switch (header.image_type) {
  93329. case TGATools._TYPE_RLE_INDEXED:
  93330. use_rle = true;
  93331. case TGATools._TYPE_INDEXED:
  93332. use_pal = true;
  93333. break;
  93334. case TGATools._TYPE_RLE_RGB:
  93335. use_rle = true;
  93336. case TGATools._TYPE_RGB:
  93337. // use_rgb = true;
  93338. break;
  93339. case TGATools._TYPE_RLE_GREY:
  93340. use_rle = true;
  93341. case TGATools._TYPE_GREY:
  93342. use_grey = true;
  93343. break;
  93344. }
  93345. var pixel_data;
  93346. // var numAlphaBits = header.flags & 0xf;
  93347. var pixel_size = header.pixel_size >> 3;
  93348. var pixel_total = header.width * header.height * pixel_size;
  93349. // Read palettes
  93350. var palettes;
  93351. if (use_pal) {
  93352. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  93353. }
  93354. // Read LRE
  93355. if (use_rle) {
  93356. pixel_data = new Uint8Array(pixel_total);
  93357. var c, count, i;
  93358. var localOffset = 0;
  93359. var pixels = new Uint8Array(pixel_size);
  93360. while (offset < pixel_total && localOffset < pixel_total) {
  93361. c = data[offset++];
  93362. count = (c & 0x7f) + 1;
  93363. // RLE pixels
  93364. if (c & 0x80) {
  93365. // Bind pixel tmp array
  93366. for (i = 0; i < pixel_size; ++i) {
  93367. pixels[i] = data[offset++];
  93368. }
  93369. // Copy pixel array
  93370. for (i = 0; i < count; ++i) {
  93371. pixel_data.set(pixels, localOffset + i * pixel_size);
  93372. }
  93373. localOffset += pixel_size * count;
  93374. }
  93375. // Raw pixels
  93376. else {
  93377. count *= pixel_size;
  93378. for (i = 0; i < count; ++i) {
  93379. pixel_data[localOffset + i] = data[offset++];
  93380. }
  93381. localOffset += count;
  93382. }
  93383. }
  93384. }
  93385. // RAW Pixels
  93386. else {
  93387. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  93388. }
  93389. // Load to texture
  93390. var x_start, y_start, x_step, y_step, y_end, x_end;
  93391. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  93392. default:
  93393. case TGATools._ORIGIN_UL:
  93394. x_start = 0;
  93395. x_step = 1;
  93396. x_end = header.width;
  93397. y_start = 0;
  93398. y_step = 1;
  93399. y_end = header.height;
  93400. break;
  93401. case TGATools._ORIGIN_BL:
  93402. x_start = 0;
  93403. x_step = 1;
  93404. x_end = header.width;
  93405. y_start = header.height - 1;
  93406. y_step = -1;
  93407. y_end = -1;
  93408. break;
  93409. case TGATools._ORIGIN_UR:
  93410. x_start = header.width - 1;
  93411. x_step = -1;
  93412. x_end = -1;
  93413. y_start = 0;
  93414. y_step = 1;
  93415. y_end = header.height;
  93416. break;
  93417. case TGATools._ORIGIN_BR:
  93418. x_start = header.width - 1;
  93419. x_step = -1;
  93420. x_end = -1;
  93421. y_start = header.height - 1;
  93422. y_step = -1;
  93423. y_end = -1;
  93424. break;
  93425. }
  93426. // Load the specify method
  93427. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  93428. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  93429. var engine = texture.getEngine();
  93430. engine._uploadDataToTextureDirectly(texture, imageData);
  93431. };
  93432. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93433. var image = pixel_data, colormap = palettes;
  93434. var width = header.width, height = header.height;
  93435. var color, i = 0, x, y;
  93436. var imageData = new Uint8Array(width * height * 4);
  93437. for (y = y_start; y !== y_end; y += y_step) {
  93438. for (x = x_start; x !== x_end; x += x_step, i++) {
  93439. color = image[i];
  93440. imageData[(x + width * y) * 4 + 3] = 255;
  93441. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  93442. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  93443. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  93444. }
  93445. }
  93446. return imageData;
  93447. };
  93448. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93449. var image = pixel_data;
  93450. var width = header.width, height = header.height;
  93451. var color, i = 0, x, y;
  93452. var imageData = new Uint8Array(width * height * 4);
  93453. for (y = y_start; y !== y_end; y += y_step) {
  93454. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  93455. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  93456. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  93457. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  93458. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  93459. imageData[(x + width * y) * 4 + 0] = r;
  93460. imageData[(x + width * y) * 4 + 1] = g;
  93461. imageData[(x + width * y) * 4 + 2] = b;
  93462. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  93463. }
  93464. }
  93465. return imageData;
  93466. };
  93467. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93468. var image = pixel_data;
  93469. var width = header.width, height = header.height;
  93470. var i = 0, x, y;
  93471. var imageData = new Uint8Array(width * height * 4);
  93472. for (y = y_start; y !== y_end; y += y_step) {
  93473. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  93474. imageData[(x + width * y) * 4 + 3] = 255;
  93475. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93476. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  93477. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  93478. }
  93479. }
  93480. return imageData;
  93481. };
  93482. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93483. var image = pixel_data;
  93484. var width = header.width, height = header.height;
  93485. var i = 0, x, y;
  93486. var imageData = new Uint8Array(width * height * 4);
  93487. for (y = y_start; y !== y_end; y += y_step) {
  93488. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  93489. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93490. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  93491. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  93492. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  93493. }
  93494. }
  93495. return imageData;
  93496. };
  93497. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93498. var image = pixel_data;
  93499. var width = header.width, height = header.height;
  93500. var color, i = 0, x, y;
  93501. var imageData = new Uint8Array(width * height * 4);
  93502. for (y = y_start; y !== y_end; y += y_step) {
  93503. for (x = x_start; x !== x_end; x += x_step, i++) {
  93504. color = image[i];
  93505. imageData[(x + width * y) * 4 + 0] = color;
  93506. imageData[(x + width * y) * 4 + 1] = color;
  93507. imageData[(x + width * y) * 4 + 2] = color;
  93508. imageData[(x + width * y) * 4 + 3] = 255;
  93509. }
  93510. }
  93511. return imageData;
  93512. };
  93513. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93514. var image = pixel_data;
  93515. var width = header.width, height = header.height;
  93516. var i = 0, x, y;
  93517. var imageData = new Uint8Array(width * height * 4);
  93518. for (y = y_start; y !== y_end; y += y_step) {
  93519. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  93520. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  93521. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  93522. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93523. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  93524. }
  93525. }
  93526. return imageData;
  93527. };
  93528. //private static _TYPE_NO_DATA = 0;
  93529. TGATools._TYPE_INDEXED = 1;
  93530. TGATools._TYPE_RGB = 2;
  93531. TGATools._TYPE_GREY = 3;
  93532. TGATools._TYPE_RLE_INDEXED = 9;
  93533. TGATools._TYPE_RLE_RGB = 10;
  93534. TGATools._TYPE_RLE_GREY = 11;
  93535. TGATools._ORIGIN_MASK = 0x30;
  93536. TGATools._ORIGIN_SHIFT = 0x04;
  93537. TGATools._ORIGIN_BL = 0x00;
  93538. TGATools._ORIGIN_BR = 0x01;
  93539. TGATools._ORIGIN_UL = 0x02;
  93540. TGATools._ORIGIN_UR = 0x03;
  93541. return TGATools;
  93542. }());
  93543. BABYLON.TGATools = TGATools;
  93544. })(BABYLON || (BABYLON = {}));
  93545. //# sourceMappingURL=babylon.tga.js.map
  93546. var BABYLON;
  93547. (function (BABYLON) {
  93548. /**
  93549. * Implementation of the TGA Texture Loader.
  93550. */
  93551. var TGATextureLoader = /** @class */ (function () {
  93552. function TGATextureLoader() {
  93553. /**
  93554. * Defines wether the loader supports cascade loading the different faces.
  93555. */
  93556. this.supportCascades = false;
  93557. }
  93558. /**
  93559. * This returns if the loader support the current file information.
  93560. * @param extension defines the file extension of the file being loaded
  93561. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93562. * @param fallback defines the fallback internal texture if any
  93563. * @param isBase64 defines whether the texture is encoded as a base64
  93564. * @param isBuffer defines whether the texture data are stored as a buffer
  93565. * @returns true if the loader can load the specified file
  93566. */
  93567. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93568. return extension.indexOf(".tga") === 0;
  93569. };
  93570. /**
  93571. * Transform the url before loading if required.
  93572. * @param rootUrl the url of the texture
  93573. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93574. * @returns the transformed texture
  93575. */
  93576. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93577. return rootUrl;
  93578. };
  93579. /**
  93580. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93581. * @param rootUrl the url of the texture
  93582. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93583. * @returns the fallback texture
  93584. */
  93585. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93586. return null;
  93587. };
  93588. /**
  93589. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93590. * @param data contains the texture data
  93591. * @param texture defines the BabylonJS internal texture
  93592. * @param createPolynomials will be true if polynomials have been requested
  93593. * @param onLoad defines the callback to trigger once the texture is ready
  93594. * @param onError defines the callback to trigger in case of error
  93595. */
  93596. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93597. throw ".env not supported in Cube.";
  93598. };
  93599. /**
  93600. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93601. * @param data contains the texture data
  93602. * @param texture defines the BabylonJS internal texture
  93603. * @param callback defines the method to call once ready to upload
  93604. */
  93605. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  93606. var uintData = new Uint8Array(data);
  93607. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  93608. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  93609. BABYLON.TGATools.UploadContent(texture, uintData);
  93610. });
  93611. };
  93612. return TGATextureLoader;
  93613. }());
  93614. // Register the loader.
  93615. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  93616. })(BABYLON || (BABYLON = {}));
  93617. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  93618. var BABYLON;
  93619. (function (BABYLON) {
  93620. /**
  93621. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  93622. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  93623. */
  93624. var KhronosTextureContainer = /** @class */ (function () {
  93625. /**
  93626. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  93627. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  93628. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  93629. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  93630. */
  93631. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  93632. this.arrayBuffer = arrayBuffer;
  93633. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  93634. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  93635. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  93636. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  93637. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  93638. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  93639. BABYLON.Tools.Error("texture missing KTX identifier");
  93640. return;
  93641. }
  93642. // load the reset of the header in native 32 bit int
  93643. var header = new Int32Array(this.arrayBuffer, 12, 13);
  93644. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  93645. var oppositeEndianess = header[0] === 0x01020304;
  93646. // read all the header elements in order they exist in the file, without modification (sans endainness)
  93647. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  93648. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  93649. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  93650. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  93651. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  93652. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  93653. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  93654. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  93655. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  93656. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  93657. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  93658. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  93659. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  93660. if (this.glType !== 0) {
  93661. BABYLON.Tools.Error("only compressed formats currently supported");
  93662. return;
  93663. }
  93664. else {
  93665. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  93666. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  93667. }
  93668. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  93669. BABYLON.Tools.Error("only 2D textures currently supported");
  93670. return;
  93671. }
  93672. if (this.numberOfArrayElements !== 0) {
  93673. BABYLON.Tools.Error("texture arrays not currently supported");
  93674. return;
  93675. }
  93676. if (this.numberOfFaces !== facesExpected) {
  93677. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  93678. return;
  93679. }
  93680. // we now have a completely validated file, so could use existence of loadType as success
  93681. // would need to make this more elaborate & adjust checks above to support more than one load type
  93682. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  93683. }
  93684. // not as fast hardware based, but will probably never need to use
  93685. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  93686. return ((val & 0xFF) << 24)
  93687. | ((val & 0xFF00) << 8)
  93688. | ((val >> 8) & 0xFF00)
  93689. | ((val >> 24) & 0xFF);
  93690. };
  93691. /**
  93692. * Uploads KTX content to a Babylon Texture.
  93693. * It is assumed that the texture has already been created & is currently bound
  93694. * @hidden
  93695. */
  93696. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  93697. switch (this.loadType) {
  93698. case KhronosTextureContainer.COMPRESSED_2D:
  93699. this._upload2DCompressedLevels(texture, loadMipmaps);
  93700. break;
  93701. case KhronosTextureContainer.TEX_2D:
  93702. case KhronosTextureContainer.COMPRESSED_3D:
  93703. case KhronosTextureContainer.TEX_3D:
  93704. }
  93705. };
  93706. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  93707. // initialize width & height for level 1
  93708. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  93709. var width = this.pixelWidth;
  93710. var height = this.pixelHeight;
  93711. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  93712. for (var level = 0; level < mipmapCount; level++) {
  93713. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  93714. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  93715. for (var face = 0; face < this.numberOfFaces; face++) {
  93716. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  93717. var engine = texture.getEngine();
  93718. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  93719. dataOffset += imageSize; // add size of the image for the next face/mipmap
  93720. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  93721. }
  93722. width = Math.max(1.0, width * 0.5);
  93723. height = Math.max(1.0, height * 0.5);
  93724. }
  93725. };
  93726. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  93727. // load types
  93728. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  93729. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  93730. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  93731. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  93732. return KhronosTextureContainer;
  93733. }());
  93734. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  93735. })(BABYLON || (BABYLON = {}));
  93736. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  93737. var BABYLON;
  93738. (function (BABYLON) {
  93739. /**
  93740. * Implementation of the KTX Texture Loader.
  93741. */
  93742. var KTXTextureLoader = /** @class */ (function () {
  93743. function KTXTextureLoader() {
  93744. /**
  93745. * Defines wether the loader supports cascade loading the different faces.
  93746. */
  93747. this.supportCascades = false;
  93748. }
  93749. /**
  93750. * This returns if the loader support the current file information.
  93751. * @param extension defines the file extension of the file being loaded
  93752. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93753. * @param fallback defines the fallback internal texture if any
  93754. * @param isBase64 defines whether the texture is encoded as a base64
  93755. * @param isBuffer defines whether the texture data are stored as a buffer
  93756. * @returns true if the loader can load the specified file
  93757. */
  93758. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93759. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  93760. return true;
  93761. }
  93762. return false;
  93763. };
  93764. /**
  93765. * Transform the url before loading if required.
  93766. * @param rootUrl the url of the texture
  93767. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93768. * @returns the transformed texture
  93769. */
  93770. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93771. var lastDot = rootUrl.lastIndexOf('.');
  93772. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  93773. };
  93774. /**
  93775. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93776. * @param rootUrl the url of the texture
  93777. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93778. * @returns the fallback texture
  93779. */
  93780. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93781. // remove the format appended to the rootUrl in the original createCubeTexture call.
  93782. var exp = new RegExp("" + textureFormatInUse + "$");
  93783. return rootUrl.replace(exp, "");
  93784. };
  93785. /**
  93786. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93787. * @param data contains the texture data
  93788. * @param texture defines the BabylonJS internal texture
  93789. * @param createPolynomials will be true if polynomials have been requested
  93790. * @param onLoad defines the callback to trigger once the texture is ready
  93791. * @param onError defines the callback to trigger in case of error
  93792. */
  93793. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93794. if (Array.isArray(data)) {
  93795. return;
  93796. }
  93797. var engine = texture.getEngine();
  93798. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  93799. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  93800. engine._unpackFlipY(true);
  93801. ktx.uploadLevels(texture, texture.generateMipMaps);
  93802. texture.width = ktx.pixelWidth;
  93803. texture.height = ktx.pixelHeight;
  93804. engine._setCubeMapTextureParams(loadMipmap);
  93805. texture.isReady = true;
  93806. };
  93807. /**
  93808. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93809. * @param data contains the texture data
  93810. * @param texture defines the BabylonJS internal texture
  93811. * @param callback defines the method to call once ready to upload
  93812. */
  93813. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  93814. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  93815. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  93816. ktx.uploadLevels(texture, texture.generateMipMaps);
  93817. });
  93818. };
  93819. return KTXTextureLoader;
  93820. }());
  93821. // Register the loader.
  93822. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  93823. })(BABYLON || (BABYLON = {}));
  93824. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  93825. var BABYLON;
  93826. (function (BABYLON) {
  93827. /**
  93828. * Sets of helpers addressing the serialization and deserialization of environment texture
  93829. * stored in a BabylonJS env file.
  93830. * Those files are usually stored as .env files.
  93831. */
  93832. var EnvironmentTextureTools = /** @class */ (function () {
  93833. function EnvironmentTextureTools() {
  93834. }
  93835. /**
  93836. * Gets the environment info from an env file.
  93837. * @param data The array buffer containing the .env bytes.
  93838. * @returns the environment file info (the json header) if successfully parsed.
  93839. */
  93840. EnvironmentTextureTools.GetEnvInfo = function (data) {
  93841. var dataView = new DataView(data);
  93842. var pos = 0;
  93843. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  93844. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  93845. BABYLON.Tools.Error('Not a babylon environment map');
  93846. return null;
  93847. }
  93848. }
  93849. // Read json manifest - collect characters up to null terminator
  93850. var manifestString = '';
  93851. var charCode = 0x00;
  93852. while ((charCode = dataView.getUint8(pos++))) {
  93853. manifestString += String.fromCharCode(charCode);
  93854. }
  93855. var manifest = JSON.parse(manifestString);
  93856. if (manifest.specular) {
  93857. // Extend the header with the position of the payload.
  93858. manifest.specular.specularDataPosition = pos;
  93859. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  93860. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  93861. }
  93862. return manifest;
  93863. };
  93864. /**
  93865. * Creates an environment texture from a loaded cube texture.
  93866. * @param texture defines the cube texture to convert in env file
  93867. * @return a promise containing the environment data if succesfull.
  93868. */
  93869. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  93870. var _this = this;
  93871. var internalTexture = texture.getInternalTexture();
  93872. if (!internalTexture) {
  93873. return Promise.reject("The cube texture is invalid.");
  93874. }
  93875. if (!texture._prefiltered) {
  93876. return Promise.reject("The cube texture is invalid (not prefiltered).");
  93877. }
  93878. var engine = internalTexture.getEngine();
  93879. if (engine && engine.premultipliedAlpha) {
  93880. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  93881. }
  93882. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  93883. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  93884. }
  93885. var canvas = engine.getRenderingCanvas();
  93886. if (!canvas) {
  93887. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  93888. }
  93889. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93890. if (!engine.getCaps().textureFloatRender) {
  93891. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93892. if (!engine.getCaps().textureHalfFloatRender) {
  93893. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  93894. }
  93895. }
  93896. var cubeWidth = internalTexture.width;
  93897. var hostingScene = new BABYLON.Scene(engine);
  93898. var specularTextures = {};
  93899. var promises = [];
  93900. // Read and collect all mipmaps data from the cube.
  93901. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  93902. mipmapsCount = Math.round(mipmapsCount);
  93903. var _loop_1 = function (i) {
  93904. var faceWidth = Math.pow(2, mipmapsCount - i);
  93905. var _loop_2 = function (face) {
  93906. var data = texture.readPixels(face, i);
  93907. // Creates a temp texture with the face data.
  93908. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  93909. // And rgbdEncode them.
  93910. var promise = new Promise(function (resolve, reject) {
  93911. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  93912. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  93913. rgbdPostProcess.onApply = function (effect) {
  93914. effect._bindTexture("textureSampler", tempTexture);
  93915. };
  93916. // As the process needs to happen on the main canvas, keep track of the current size
  93917. var currentW = engine.getRenderWidth();
  93918. var currentH = engine.getRenderHeight();
  93919. // Set the desired size for the texture
  93920. engine.setSize(faceWidth, faceWidth);
  93921. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  93922. // Reading datas from WebGL
  93923. BABYLON.Tools.ToBlob(canvas, function (blob) {
  93924. var fileReader = new FileReader();
  93925. fileReader.onload = function (event) {
  93926. var arrayBuffer = event.target.result;
  93927. specularTextures[i * 6 + face] = arrayBuffer;
  93928. resolve();
  93929. };
  93930. fileReader.readAsArrayBuffer(blob);
  93931. });
  93932. // Reapply the previous canvas size
  93933. engine.setSize(currentW, currentH);
  93934. });
  93935. });
  93936. promises.push(promise);
  93937. };
  93938. // All faces of the cube.
  93939. for (var face = 0; face < 6; face++) {
  93940. _loop_2(face);
  93941. }
  93942. };
  93943. for (var i = 0; i <= mipmapsCount; i++) {
  93944. _loop_1(i);
  93945. }
  93946. // Once all the textures haves been collected as RGBD stored in PNGs
  93947. return Promise.all(promises).then(function () {
  93948. // We can delete the hosting scene keeping track of all the creation objects
  93949. hostingScene.dispose();
  93950. // Creates the json header for the env texture
  93951. var info = {
  93952. version: 1,
  93953. width: cubeWidth,
  93954. irradiance: _this._CreateEnvTextureIrradiance(texture),
  93955. specular: {
  93956. mipmaps: [],
  93957. lodGenerationScale: texture.lodGenerationScale
  93958. }
  93959. };
  93960. // Sets the specular image data information
  93961. var position = 0;
  93962. for (var i = 0; i <= mipmapsCount; i++) {
  93963. for (var face = 0; face < 6; face++) {
  93964. var byteLength = specularTextures[i * 6 + face].byteLength;
  93965. info.specular.mipmaps.push({
  93966. length: byteLength,
  93967. position: position
  93968. });
  93969. position += byteLength;
  93970. }
  93971. }
  93972. // Encode the JSON as an array buffer
  93973. var infoString = JSON.stringify(info);
  93974. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  93975. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  93976. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  93977. infoView[i] = infoString.charCodeAt(i);
  93978. }
  93979. // Ends up with a null terminator for easier parsing
  93980. infoView[infoString.length] = 0x00;
  93981. // Computes the final required size and creates the storage
  93982. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  93983. var finalBuffer = new ArrayBuffer(totalSize);
  93984. var finalBufferView = new Uint8Array(finalBuffer);
  93985. var dataView = new DataView(finalBuffer);
  93986. // Copy the magic bytes identifying the file in
  93987. var pos = 0;
  93988. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  93989. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  93990. }
  93991. // Add the json info
  93992. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  93993. pos += infoBuffer.byteLength;
  93994. // Finally inserts the texture data
  93995. for (var i = 0; i <= mipmapsCount; i++) {
  93996. for (var face = 0; face < 6; face++) {
  93997. var dataBuffer = specularTextures[i * 6 + face];
  93998. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  93999. pos += dataBuffer.byteLength;
  94000. }
  94001. }
  94002. // Voila
  94003. return finalBuffer;
  94004. });
  94005. };
  94006. /**
  94007. * Creates a JSON representation of the spherical data.
  94008. * @param texture defines the texture containing the polynomials
  94009. * @return the JSON representation of the spherical info
  94010. */
  94011. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  94012. var polynmials = texture.sphericalPolynomial;
  94013. if (polynmials == null) {
  94014. return null;
  94015. }
  94016. return {
  94017. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  94018. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  94019. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  94020. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  94021. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  94022. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  94023. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  94024. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  94025. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  94026. };
  94027. };
  94028. /**
  94029. * Uploads the texture info contained in the env file to the GPU.
  94030. * @param texture defines the internal texture to upload to
  94031. * @param arrayBuffer defines the buffer cotaining the data to load
  94032. * @param info defines the texture info retrieved through the GetEnvInfo method
  94033. * @returns a promise
  94034. */
  94035. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  94036. if (info.version !== 1) {
  94037. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  94038. }
  94039. var specularInfo = info.specular;
  94040. if (!specularInfo) {
  94041. // Nothing else parsed so far
  94042. return Promise.resolve();
  94043. }
  94044. // Double checks the enclosed info
  94045. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  94046. mipmapsCount = Math.round(mipmapsCount) + 1;
  94047. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  94048. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  94049. }
  94050. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  94051. var imageData = new Array(mipmapsCount);
  94052. for (var i = 0; i < mipmapsCount; i++) {
  94053. imageData[i] = new Array(6);
  94054. for (var face = 0; face < 6; face++) {
  94055. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  94056. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  94057. }
  94058. }
  94059. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  94060. };
  94061. /**
  94062. * Uploads the levels of image data to the GPU.
  94063. * @param texture defines the internal texture to upload to
  94064. * @param imageData defines the array buffer views of image data [mipmap][face]
  94065. * @returns a promise
  94066. */
  94067. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  94068. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  94069. throw new Error("Texture size must be a power of two");
  94070. }
  94071. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  94072. // Gets everything ready.
  94073. var engine = texture.getEngine();
  94074. var expandTexture = false;
  94075. var generateNonLODTextures = false;
  94076. var rgbdPostProcess = null;
  94077. var cubeRtt = null;
  94078. var lodTextures = null;
  94079. var caps = engine.getCaps();
  94080. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94081. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94082. texture.generateMipMaps = true;
  94083. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  94084. // Add extra process if texture lod is not supported
  94085. if (!caps.textureLOD) {
  94086. expandTexture = false;
  94087. generateNonLODTextures = true;
  94088. lodTextures = {};
  94089. }
  94090. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  94091. else if (engine.webGLVersion < 2) {
  94092. expandTexture = false;
  94093. }
  94094. // If half float available we can uncompress the texture
  94095. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  94096. expandTexture = true;
  94097. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94098. }
  94099. // If full float available we can uncompress the texture
  94100. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  94101. expandTexture = true;
  94102. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94103. }
  94104. // Expand the texture if possible
  94105. if (expandTexture) {
  94106. // Simply run through the decode PP
  94107. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  94108. texture._isRGBD = false;
  94109. texture.invertY = false;
  94110. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  94111. generateDepthBuffer: false,
  94112. generateMipMaps: true,
  94113. generateStencilBuffer: false,
  94114. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  94115. type: texture.type,
  94116. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  94117. });
  94118. }
  94119. else {
  94120. texture._isRGBD = true;
  94121. texture.invertY = true;
  94122. // In case of missing support, applies the same patch than DDS files.
  94123. if (generateNonLODTextures) {
  94124. var mipSlices = 3;
  94125. var scale = texture._lodGenerationScale;
  94126. var offset = texture._lodGenerationOffset;
  94127. for (var i = 0; i < mipSlices; i++) {
  94128. //compute LOD from even spacing in smoothness (matching shader calculation)
  94129. var smoothness = i / (mipSlices - 1);
  94130. var roughness = 1 - smoothness;
  94131. var minLODIndex = offset; // roughness = 0
  94132. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  94133. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  94134. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  94135. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  94136. glTextureFromLod.isCube = true;
  94137. glTextureFromLod.invertY = true;
  94138. glTextureFromLod.generateMipMaps = false;
  94139. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  94140. // Wrap in a base texture for easy binding.
  94141. var lodTexture = new BABYLON.BaseTexture(null);
  94142. lodTexture.isCube = true;
  94143. lodTexture._texture = glTextureFromLod;
  94144. lodTextures[mipmapIndex] = lodTexture;
  94145. switch (i) {
  94146. case 0:
  94147. texture._lodTextureLow = lodTexture;
  94148. break;
  94149. case 1:
  94150. texture._lodTextureMid = lodTexture;
  94151. break;
  94152. case 2:
  94153. texture._lodTextureHigh = lodTexture;
  94154. break;
  94155. }
  94156. }
  94157. }
  94158. }
  94159. var promises = [];
  94160. var _loop_3 = function (i) {
  94161. var _loop_4 = function (face) {
  94162. // Constructs an image element from image data
  94163. var bytes = imageData[i][face];
  94164. var blob = new Blob([bytes], { type: 'image/png' });
  94165. var url = URL.createObjectURL(blob);
  94166. var image = new Image();
  94167. image.src = url;
  94168. // Enqueue promise to upload to the texture.
  94169. var promise = new Promise(function (resolve, reject) {
  94170. image.onload = function () {
  94171. if (expandTexture) {
  94172. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  94173. reject(message);
  94174. }, image);
  94175. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94176. // Uncompress the data to a RTT
  94177. rgbdPostProcess.onApply = function (effect) {
  94178. effect._bindTexture("textureSampler", tempTexture_1);
  94179. effect.setFloat2("scale", 1, 1);
  94180. };
  94181. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  94182. // Cleanup
  94183. engine.restoreDefaultFramebuffer();
  94184. tempTexture_1.dispose();
  94185. window.URL.revokeObjectURL(url);
  94186. resolve();
  94187. });
  94188. }
  94189. else {
  94190. engine._uploadImageToTexture(texture, image, face, i);
  94191. // Upload the face to the non lod texture support
  94192. if (generateNonLODTextures) {
  94193. var lodTexture = lodTextures[i];
  94194. if (lodTexture) {
  94195. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  94196. }
  94197. }
  94198. resolve();
  94199. }
  94200. };
  94201. image.onerror = function (error) {
  94202. reject(error);
  94203. };
  94204. });
  94205. promises.push(promise);
  94206. };
  94207. // All faces
  94208. for (var face = 0; face < 6; face++) {
  94209. _loop_4(face);
  94210. }
  94211. };
  94212. // All mipmaps up to provided number of images
  94213. for (var i = 0; i < imageData.length; i++) {
  94214. _loop_3(i);
  94215. }
  94216. // Fill remaining mipmaps with black textures.
  94217. if (imageData.length < mipmapsCount) {
  94218. var data = void 0;
  94219. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  94220. var dataLength = size * size * 4;
  94221. switch (texture.type) {
  94222. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  94223. data = new Uint8Array(dataLength);
  94224. break;
  94225. }
  94226. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  94227. data = new Uint16Array(dataLength);
  94228. break;
  94229. }
  94230. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  94231. data = new Float32Array(dataLength);
  94232. break;
  94233. }
  94234. }
  94235. for (var i = imageData.length; i < mipmapsCount; i++) {
  94236. for (var face = 0; face < 6; face++) {
  94237. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  94238. }
  94239. }
  94240. }
  94241. // Once all done, finishes the cleanup and return
  94242. return Promise.all(promises).then(function () {
  94243. // Release temp RTT.
  94244. if (cubeRtt) {
  94245. engine._releaseFramebufferObjects(cubeRtt);
  94246. cubeRtt._swapAndDie(texture);
  94247. }
  94248. // Release temp Post Process.
  94249. if (rgbdPostProcess) {
  94250. rgbdPostProcess.dispose();
  94251. }
  94252. // Flag internal texture as ready in case they are in use.
  94253. if (generateNonLODTextures) {
  94254. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  94255. texture._lodTextureHigh._texture.isReady = true;
  94256. }
  94257. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  94258. texture._lodTextureMid._texture.isReady = true;
  94259. }
  94260. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  94261. texture._lodTextureLow._texture.isReady = true;
  94262. }
  94263. }
  94264. });
  94265. };
  94266. /**
  94267. * Uploads spherical polynomials information to the texture.
  94268. * @param texture defines the texture we are trying to upload the information to
  94269. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  94270. */
  94271. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  94272. if (info.version !== 1) {
  94273. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  94274. }
  94275. var irradianceInfo = info.irradiance;
  94276. if (!irradianceInfo) {
  94277. return;
  94278. }
  94279. var sp = new BABYLON.SphericalPolynomial();
  94280. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  94281. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  94282. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  94283. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  94284. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  94285. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  94286. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  94287. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  94288. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  94289. texture._sphericalPolynomial = sp;
  94290. };
  94291. /**
  94292. * Magic number identifying the env file.
  94293. */
  94294. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  94295. return EnvironmentTextureTools;
  94296. }());
  94297. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  94298. })(BABYLON || (BABYLON = {}));
  94299. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  94300. var BABYLON;
  94301. (function (BABYLON) {
  94302. /**
  94303. * Implementation of the ENV Texture Loader.
  94304. */
  94305. var ENVTextureLoader = /** @class */ (function () {
  94306. function ENVTextureLoader() {
  94307. /**
  94308. * Defines wether the loader supports cascade loading the different faces.
  94309. */
  94310. this.supportCascades = false;
  94311. }
  94312. /**
  94313. * This returns if the loader support the current file information.
  94314. * @param extension defines the file extension of the file being loaded
  94315. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94316. * @param fallback defines the fallback internal texture if any
  94317. * @param isBase64 defines whether the texture is encoded as a base64
  94318. * @param isBuffer defines whether the texture data are stored as a buffer
  94319. * @returns true if the loader can load the specified file
  94320. */
  94321. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94322. return extension.indexOf(".env") === 0;
  94323. };
  94324. /**
  94325. * Transform the url before loading if required.
  94326. * @param rootUrl the url of the texture
  94327. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94328. * @returns the transformed texture
  94329. */
  94330. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94331. return rootUrl;
  94332. };
  94333. /**
  94334. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94335. * @param rootUrl the url of the texture
  94336. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94337. * @returns the fallback texture
  94338. */
  94339. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94340. return null;
  94341. };
  94342. /**
  94343. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94344. * @param data contains the texture data
  94345. * @param texture defines the BabylonJS internal texture
  94346. * @param createPolynomials will be true if polynomials have been requested
  94347. * @param onLoad defines the callback to trigger once the texture is ready
  94348. * @param onError defines the callback to trigger in case of error
  94349. */
  94350. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94351. if (Array.isArray(data)) {
  94352. return;
  94353. }
  94354. data = data;
  94355. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  94356. if (info) {
  94357. texture.width = info.width;
  94358. texture.height = info.width;
  94359. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  94360. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  94361. texture.isReady = true;
  94362. if (onLoad) {
  94363. onLoad();
  94364. }
  94365. });
  94366. }
  94367. else if (onError) {
  94368. onError("Can not parse the environment file", null);
  94369. }
  94370. };
  94371. /**
  94372. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94373. * @param data contains the texture data
  94374. * @param texture defines the BabylonJS internal texture
  94375. * @param callback defines the method to call once ready to upload
  94376. */
  94377. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  94378. throw ".env not supported in 2d.";
  94379. };
  94380. return ENVTextureLoader;
  94381. }());
  94382. // Register the loader.
  94383. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  94384. })(BABYLON || (BABYLON = {}));
  94385. //# sourceMappingURL=babylon.envTextureLoader.js.map
  94386. var BABYLON;
  94387. (function (BABYLON) {
  94388. /**
  94389. * Renders a layer on top of an existing scene
  94390. */
  94391. var UtilityLayerRenderer = /** @class */ (function () {
  94392. /**
  94393. * Instantiates a UtilityLayerRenderer
  94394. * @param originalScene the original scene that will be rendered on top of
  94395. */
  94396. function UtilityLayerRenderer(
  94397. /** the original scene that will be rendered on top of */
  94398. originalScene) {
  94399. var _this = this;
  94400. this.originalScene = originalScene;
  94401. this._pointerCaptures = {};
  94402. this._lastPointerEvents = {};
  94403. /**
  94404. * If the utility layer should automatically be rendered on top of existing scene
  94405. */
  94406. this.shouldRender = true;
  94407. /**
  94408. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  94409. */
  94410. this.onlyCheckPointerDownEvents = true;
  94411. /**
  94412. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  94413. */
  94414. this.processAllEvents = false;
  94415. /**
  94416. * Observable raised when the pointer move from the utility layer scene to the main scene
  94417. */
  94418. this.onPointerOutObservable = new BABYLON.Observable();
  94419. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  94420. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  94421. this.utilityLayerScene._allowPostProcessClearColor = false;
  94422. originalScene.getEngine().scenes.pop();
  94423. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  94424. this.utilityLayerScene.detachControl();
  94425. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  94426. if (!_this.processAllEvents) {
  94427. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  94428. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  94429. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  94430. return;
  94431. }
  94432. }
  94433. var pointerEvent = (prePointerInfo.event);
  94434. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  94435. _this._pointerCaptures[pointerEvent.pointerId] = false;
  94436. return;
  94437. }
  94438. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  94439. if (!prePointerInfo.ray && utilityScenePick) {
  94440. prePointerInfo.ray = utilityScenePick.ray;
  94441. }
  94442. // always fire the prepointer oversvable
  94443. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  94444. // allow every non pointer down event to flow to the utility layer
  94445. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  94446. if (!prePointerInfo.skipOnPointerObservable) {
  94447. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  94448. }
  94449. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  94450. _this._pointerCaptures[pointerEvent.pointerId] = false;
  94451. }
  94452. return;
  94453. }
  94454. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  94455. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  94456. if (utilityScenePick && utilityScenePick.hit) {
  94457. if (!prePointerInfo.skipOnPointerObservable) {
  94458. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  94459. }
  94460. prePointerInfo.skipOnPointerObservable = true;
  94461. }
  94462. }
  94463. else {
  94464. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  94465. var pointerEvent_1 = (prePointerInfo.event);
  94466. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  94467. if (originalScenePick && utilityScenePick) {
  94468. // No pick in utility scene
  94469. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  94470. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  94471. // We touched an utility mesh present in the main scene
  94472. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  94473. prePointerInfo.skipOnPointerObservable = true;
  94474. }
  94475. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94476. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  94477. }
  94478. }
  94479. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  94480. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  94481. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  94482. // If a previous utility layer set this, do not unset this
  94483. if (!prePointerInfo.skipOnPointerObservable) {
  94484. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  94485. }
  94486. }
  94487. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  94488. // We have a pick in both scenes but main is closer than utility
  94489. // We touched an utility mesh present in the main scene
  94490. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  94491. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  94492. prePointerInfo.skipOnPointerObservable = true;
  94493. }
  94494. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  94495. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  94496. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  94497. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  94498. }
  94499. }
  94500. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  94501. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  94502. }
  94503. }
  94504. }
  94505. });
  94506. // Render directly on top of existing scene without clearing
  94507. this.utilityLayerScene.autoClear = false;
  94508. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  94509. if (_this.shouldRender) {
  94510. _this.render();
  94511. }
  94512. });
  94513. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  94514. _this.dispose();
  94515. });
  94516. this._updateCamera();
  94517. }
  94518. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  94519. /**
  94520. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  94521. */
  94522. get: function () {
  94523. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  94524. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  94525. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  94526. UtilityLayerRenderer._DefaultUtilityLayer = null;
  94527. });
  94528. }
  94529. return UtilityLayerRenderer._DefaultUtilityLayer;
  94530. },
  94531. enumerable: true,
  94532. configurable: true
  94533. });
  94534. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  94535. /**
  94536. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  94537. */
  94538. get: function () {
  94539. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  94540. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  94541. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  94542. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  94543. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  94544. });
  94545. }
  94546. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  94547. },
  94548. enumerable: true,
  94549. configurable: true
  94550. });
  94551. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  94552. if (!prePointerInfo.skipOnPointerObservable) {
  94553. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  94554. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  94555. }
  94556. };
  94557. /**
  94558. * Renders the utility layers scene on top of the original scene
  94559. */
  94560. UtilityLayerRenderer.prototype.render = function () {
  94561. this._updateCamera();
  94562. if (this.utilityLayerScene.activeCamera) {
  94563. // Set the camera's scene to utility layers scene
  94564. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  94565. var camera = this.utilityLayerScene.activeCamera;
  94566. camera._scene = this.utilityLayerScene;
  94567. if (camera.leftCamera) {
  94568. camera.leftCamera._scene = this.utilityLayerScene;
  94569. }
  94570. if (camera.rightCamera) {
  94571. camera.rightCamera._scene = this.utilityLayerScene;
  94572. }
  94573. this.utilityLayerScene.render(false);
  94574. // Reset camera's scene back to original
  94575. camera._scene = oldScene;
  94576. if (camera.leftCamera) {
  94577. camera.leftCamera._scene = oldScene;
  94578. }
  94579. if (camera.rightCamera) {
  94580. camera.rightCamera._scene = oldScene;
  94581. }
  94582. }
  94583. };
  94584. /**
  94585. * Disposes of the renderer
  94586. */
  94587. UtilityLayerRenderer.prototype.dispose = function () {
  94588. this.onPointerOutObservable.clear();
  94589. if (this._afterRenderObserver) {
  94590. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  94591. }
  94592. if (this._sceneDisposeObserver) {
  94593. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94594. }
  94595. if (this._originalPointerObserver) {
  94596. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  94597. }
  94598. this.utilityLayerScene.dispose();
  94599. };
  94600. UtilityLayerRenderer.prototype._updateCamera = function () {
  94601. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  94602. };
  94603. UtilityLayerRenderer._DefaultUtilityLayer = null;
  94604. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  94605. return UtilityLayerRenderer;
  94606. }());
  94607. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  94608. })(BABYLON || (BABYLON = {}));
  94609. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  94610. //# sourceMappingURL=babylon.behavior.js.map
  94611. var BABYLON;
  94612. (function (BABYLON) {
  94613. /**
  94614. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  94615. */
  94616. var PointerDragBehavior = /** @class */ (function () {
  94617. /**
  94618. * Creates a pointer drag behavior that can be attached to a mesh
  94619. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  94620. */
  94621. function PointerDragBehavior(options) {
  94622. /**
  94623. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  94624. */
  94625. this.maxDragAngle = 0;
  94626. /**
  94627. * @hidden
  94628. */
  94629. this._useAlternatePickedPointAboveMaxDragAngle = false;
  94630. /**
  94631. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  94632. */
  94633. this.currentDraggingPointerID = -1;
  94634. /**
  94635. * If the behavior is currently in a dragging state
  94636. */
  94637. this.dragging = false;
  94638. /**
  94639. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  94640. */
  94641. this.dragDeltaRatio = 0.2;
  94642. /**
  94643. * If the drag plane orientation should be updated during the dragging (Default: true)
  94644. */
  94645. this.updateDragPlane = true;
  94646. // Debug mode will display drag planes to help visualize behavior
  94647. this._debugMode = false;
  94648. this._moving = false;
  94649. /**
  94650. * Fires each time the attached mesh is dragged with the pointer
  94651. * * delta between last drag position and current drag position in world space
  94652. * * dragDistance along the drag axis
  94653. * * dragPlaneNormal normal of the current drag plane used during the drag
  94654. * * dragPlanePoint in world space where the drag intersects the drag plane
  94655. */
  94656. this.onDragObservable = new BABYLON.Observable();
  94657. /**
  94658. * Fires each time a drag begins (eg. mouse down on mesh)
  94659. */
  94660. this.onDragStartObservable = new BABYLON.Observable();
  94661. /**
  94662. * Fires each time a drag ends (eg. mouse release after drag)
  94663. */
  94664. this.onDragEndObservable = new BABYLON.Observable();
  94665. /**
  94666. * If the attached mesh should be moved when dragged
  94667. */
  94668. this.moveAttached = true;
  94669. /**
  94670. * If the drag behavior will react to drag events (Default: true)
  94671. */
  94672. this.enabled = true;
  94673. /**
  94674. * If camera controls should be detached during the drag
  94675. */
  94676. this.detachCameraControls = true;
  94677. /**
  94678. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  94679. */
  94680. this.useObjectOrienationForDragging = true;
  94681. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94682. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  94683. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  94684. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  94685. this._attachedElement = null;
  94686. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  94687. this._lastPointerRay = {};
  94688. this._dragDelta = new BABYLON.Vector3();
  94689. // Variables to avoid instantiation in the below method
  94690. this._pointA = new BABYLON.Vector3(0, 0, 0);
  94691. this._pointB = new BABYLON.Vector3(0, 0, 0);
  94692. this._pointC = new BABYLON.Vector3(0, 0, 0);
  94693. this._lineA = new BABYLON.Vector3(0, 0, 0);
  94694. this._lineB = new BABYLON.Vector3(0, 0, 0);
  94695. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  94696. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  94697. this._options = options ? options : {};
  94698. var optionCount = 0;
  94699. if (this._options.dragAxis) {
  94700. optionCount++;
  94701. }
  94702. if (this._options.dragPlaneNormal) {
  94703. optionCount++;
  94704. }
  94705. if (optionCount > 1) {
  94706. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  94707. }
  94708. }
  94709. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  94710. /**
  94711. * The name of the behavior
  94712. */
  94713. get: function () {
  94714. return "PointerDrag";
  94715. },
  94716. enumerable: true,
  94717. configurable: true
  94718. });
  94719. /**
  94720. * Initializes the behavior
  94721. */
  94722. PointerDragBehavior.prototype.init = function () { };
  94723. /**
  94724. * Attaches the drag behavior the passed in mesh
  94725. * @param ownerNode The mesh that will be dragged around once attached
  94726. */
  94727. PointerDragBehavior.prototype.attach = function (ownerNode) {
  94728. var _this = this;
  94729. this._scene = ownerNode.getScene();
  94730. this._attachedNode = ownerNode;
  94731. // Initialize drag plane to not interfere with existing scene
  94732. if (!PointerDragBehavior._planeScene) {
  94733. if (this._debugMode) {
  94734. PointerDragBehavior._planeScene = this._scene;
  94735. }
  94736. else {
  94737. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  94738. PointerDragBehavior._planeScene.detachControl();
  94739. this._scene.getEngine().scenes.pop();
  94740. this._scene.onDisposeObservable.addOnce(function () {
  94741. PointerDragBehavior._planeScene.dispose();
  94742. PointerDragBehavior._planeScene = null;
  94743. });
  94744. }
  94745. }
  94746. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  94747. // State of the drag
  94748. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  94749. var pickPredicate = function (m) {
  94750. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  94751. };
  94752. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  94753. if (!_this.enabled) {
  94754. return;
  94755. }
  94756. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94757. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  94758. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  94759. }
  94760. }
  94761. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  94762. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  94763. _this.releaseDrag();
  94764. }
  94765. }
  94766. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  94767. var pointerId = pointerInfo.event.pointerId;
  94768. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  94769. if (!_this._lastPointerRay[pointerId]) {
  94770. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  94771. }
  94772. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  94773. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  94774. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  94775. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  94776. _this._moveDrag(pointerInfo.pickInfo.ray);
  94777. }
  94778. }
  94779. }
  94780. });
  94781. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  94782. if (_this._moving && _this.moveAttached) {
  94783. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  94784. // Slowly move mesh to avoid jitter
  94785. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  94786. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  94787. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  94788. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  94789. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  94790. }
  94791. });
  94792. };
  94793. PointerDragBehavior.prototype.releaseDrag = function () {
  94794. this.dragging = false;
  94795. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  94796. this.currentDraggingPointerID = -1;
  94797. this._moving = false;
  94798. // Reattach camera controls
  94799. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  94800. this._scene.activeCamera.attachControl(this._attachedElement, true);
  94801. }
  94802. };
  94803. /**
  94804. * Simulates the start of a pointer drag event on the behavior
  94805. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  94806. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  94807. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  94808. */
  94809. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  94810. if (pointerId === void 0) { pointerId = 1; }
  94811. this._startDrag(pointerId, fromRay, startPickedPoint);
  94812. if (this._lastPointerRay[pointerId]) {
  94813. // if there was a last pointer ray drag the object there
  94814. this._moveDrag(this._lastPointerRay[pointerId]);
  94815. }
  94816. };
  94817. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  94818. if (pointerId === void 0) { pointerId = 1; }
  94819. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  94820. return;
  94821. }
  94822. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  94823. // Create start ray from the camera to the object
  94824. if (fromRay) {
  94825. this._startDragRay.direction.copyFrom(fromRay.direction);
  94826. this._startDragRay.origin.copyFrom(fromRay.origin);
  94827. }
  94828. else {
  94829. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  94830. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  94831. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  94832. }
  94833. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  94834. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  94835. if (pickedPoint) {
  94836. this.dragging = true;
  94837. this.currentDraggingPointerID = pointerId;
  94838. this.lastDragPosition.copyFrom(pickedPoint);
  94839. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  94840. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  94841. // Detatch camera controls
  94842. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  94843. if (this._scene.activeCamera.inputs.attachedElement) {
  94844. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  94845. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  94846. }
  94847. else {
  94848. this._attachedElement = null;
  94849. }
  94850. }
  94851. }
  94852. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  94853. };
  94854. PointerDragBehavior.prototype._moveDrag = function (ray) {
  94855. this._moving = true;
  94856. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  94857. if (pickedPoint) {
  94858. if (this.updateDragPlane) {
  94859. this._updateDragPlanePosition(ray, pickedPoint);
  94860. }
  94861. var dragLength = 0;
  94862. // depending on the drag mode option drag accordingly
  94863. if (this._options.dragAxis) {
  94864. // Convert local drag axis to world
  94865. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  94866. // Project delta drag from the drag plane onto the drag axis
  94867. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  94868. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  94869. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  94870. }
  94871. else {
  94872. dragLength = this._dragDelta.length();
  94873. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  94874. }
  94875. this._targetPosition.addInPlace(this._dragDelta);
  94876. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  94877. this.lastDragPosition.copyFrom(pickedPoint);
  94878. }
  94879. };
  94880. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  94881. var _this = this;
  94882. if (!ray) {
  94883. return null;
  94884. }
  94885. // Calculate angle between plane normal and ray
  94886. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  94887. // Correct if ray is casted from oposite side
  94888. if (angle > Math.PI / 2) {
  94889. angle = Math.PI - angle;
  94890. }
  94891. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  94892. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  94893. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  94894. // Invert ray direction along the towards object axis
  94895. this._tmpVector.copyFrom(ray.direction);
  94896. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  94897. this._alternatePickedPoint.normalize();
  94898. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  94899. this._tmpVector.addInPlace(this._alternatePickedPoint);
  94900. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  94901. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  94902. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  94903. this._alternatePickedPoint.addInPlace(this._tmpVector);
  94904. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  94905. return this._alternatePickedPoint;
  94906. }
  94907. else {
  94908. return null;
  94909. }
  94910. }
  94911. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  94912. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  94913. return pickResult.pickedPoint;
  94914. }
  94915. else {
  94916. return null;
  94917. }
  94918. };
  94919. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  94920. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  94921. this._pointA.copyFrom(dragPlanePosition);
  94922. if (this._options.dragAxis) {
  94923. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  94924. // Calculate plane normal in direction of camera but perpendicular to drag axis
  94925. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  94926. ray.origin.subtractToRef(this._pointA, this._pointC);
  94927. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  94928. // Get perpendicular line from direction to camera and drag axis
  94929. this._pointB.subtractToRef(this._pointA, this._lineA);
  94930. this._pointC.subtractToRef(this._pointA, this._lineB);
  94931. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  94932. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  94933. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  94934. this._lookAt.normalize();
  94935. this._dragPlane.position.copyFrom(this._pointA);
  94936. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  94937. this._dragPlane.lookAt(this._lookAt);
  94938. }
  94939. else if (this._options.dragPlaneNormal) {
  94940. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  94941. this._dragPlane.position.copyFrom(this._pointA);
  94942. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  94943. this._dragPlane.lookAt(this._lookAt);
  94944. }
  94945. else {
  94946. this._dragPlane.position.copyFrom(this._pointA);
  94947. this._dragPlane.lookAt(ray.origin);
  94948. }
  94949. this._dragPlane.computeWorldMatrix(true);
  94950. };
  94951. /**
  94952. * Detaches the behavior from the mesh
  94953. */
  94954. PointerDragBehavior.prototype.detach = function () {
  94955. if (this._pointerObserver) {
  94956. this._scene.onPointerObservable.remove(this._pointerObserver);
  94957. }
  94958. if (this._beforeRenderObserver) {
  94959. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  94960. }
  94961. };
  94962. return PointerDragBehavior;
  94963. }());
  94964. BABYLON.PointerDragBehavior = PointerDragBehavior;
  94965. })(BABYLON || (BABYLON = {}));
  94966. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  94967. var BABYLON;
  94968. (function (BABYLON) {
  94969. /**
  94970. * A behavior that when attached to a mesh will allow the mesh to be scaled
  94971. */
  94972. var MultiPointerScaleBehavior = /** @class */ (function () {
  94973. function MultiPointerScaleBehavior() {
  94974. this._startDistance = 0;
  94975. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  94976. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  94977. this._sceneRenderObserver = null;
  94978. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  94979. this._dragBehaviorA.moveAttached = false;
  94980. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  94981. this._dragBehaviorB.moveAttached = false;
  94982. }
  94983. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  94984. /**
  94985. * The name of the behavior
  94986. */
  94987. get: function () {
  94988. return "MultiPointerScale";
  94989. },
  94990. enumerable: true,
  94991. configurable: true
  94992. });
  94993. /**
  94994. * Initializes the behavior
  94995. */
  94996. MultiPointerScaleBehavior.prototype.init = function () { };
  94997. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  94998. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  94999. };
  95000. /**
  95001. * Attaches the scale behavior the passed in mesh
  95002. * @param ownerNode The mesh that will be scaled around once attached
  95003. */
  95004. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  95005. var _this = this;
  95006. this._ownerNode = ownerNode;
  95007. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  95008. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  95009. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95010. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  95011. _this._dragBehaviorA.releaseDrag();
  95012. }
  95013. else {
  95014. _this._initialScale.copyFrom(ownerNode.scaling);
  95015. _this._startDistance = _this._getCurrentDistance();
  95016. }
  95017. }
  95018. });
  95019. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  95020. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95021. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  95022. _this._dragBehaviorB.releaseDrag();
  95023. }
  95024. else {
  95025. _this._initialScale.copyFrom(ownerNode.scaling);
  95026. _this._startDistance = _this._getCurrentDistance();
  95027. }
  95028. }
  95029. });
  95030. // Once both drag behaviors are active scale based on the distance between the two pointers
  95031. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  95032. behavior.onDragObservable.add(function () {
  95033. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95034. var ratio = _this._getCurrentDistance() / _this._startDistance;
  95035. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  95036. }
  95037. });
  95038. });
  95039. ownerNode.addBehavior(this._dragBehaviorA);
  95040. ownerNode.addBehavior(this._dragBehaviorB);
  95041. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  95042. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  95043. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95044. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  95045. if (change.length() > 0.01) {
  95046. ownerNode.scaling.addInPlace(change);
  95047. }
  95048. }
  95049. });
  95050. };
  95051. /**
  95052. * Detaches the behavior from the mesh
  95053. */
  95054. MultiPointerScaleBehavior.prototype.detach = function () {
  95055. var _this = this;
  95056. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  95057. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  95058. behavior.onDragStartObservable.clear();
  95059. behavior.onDragObservable.clear();
  95060. _this._ownerNode.removeBehavior(behavior);
  95061. });
  95062. };
  95063. return MultiPointerScaleBehavior;
  95064. }());
  95065. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  95066. })(BABYLON || (BABYLON = {}));
  95067. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  95068. var BABYLON;
  95069. (function (BABYLON) {
  95070. /**
  95071. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  95072. */
  95073. var SixDofDragBehavior = /** @class */ (function () {
  95074. function SixDofDragBehavior() {
  95075. this._sceneRenderObserver = null;
  95076. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95077. this._moving = false;
  95078. this._startingOrientation = new BABYLON.Quaternion();
  95079. /**
  95080. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  95081. */
  95082. this.zDragFactor = 3;
  95083. /**
  95084. * If the behavior is currently in a dragging state
  95085. */
  95086. this.dragging = false;
  95087. /**
  95088. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  95089. */
  95090. this.dragDeltaRatio = 0.2;
  95091. /**
  95092. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95093. */
  95094. this.currentDraggingPointerID = -1;
  95095. /**
  95096. * If camera controls should be detached during the drag
  95097. */
  95098. this.detachCameraControls = true;
  95099. /**
  95100. * Fires each time a drag starts
  95101. */
  95102. this.onDragStartObservable = new BABYLON.Observable();
  95103. /**
  95104. * Fires each time a drag ends (eg. mouse release after drag)
  95105. */
  95106. this.onDragEndObservable = new BABYLON.Observable();
  95107. }
  95108. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  95109. /**
  95110. * The name of the behavior
  95111. */
  95112. get: function () {
  95113. return "SixDofDrag";
  95114. },
  95115. enumerable: true,
  95116. configurable: true
  95117. });
  95118. /**
  95119. * Initializes the behavior
  95120. */
  95121. SixDofDragBehavior.prototype.init = function () { };
  95122. /**
  95123. * Attaches the scale behavior the passed in mesh
  95124. * @param ownerNode The mesh that will be scaled around once attached
  95125. */
  95126. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  95127. var _this = this;
  95128. this._ownerNode = ownerNode;
  95129. this._scene = this._ownerNode.getScene();
  95130. if (!SixDofDragBehavior._virtualScene) {
  95131. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  95132. this._scene.getEngine().scenes.pop();
  95133. }
  95134. var pickedMesh = null;
  95135. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  95136. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  95137. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  95138. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  95139. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  95140. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  95141. var pickPredicate = function (m) {
  95142. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  95143. };
  95144. var attachedElement = null;
  95145. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95146. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95147. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95148. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  95149. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  95150. }
  95151. pickedMesh = _this._ownerNode;
  95152. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  95153. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  95154. // Set position and orientation of the controller
  95155. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  95156. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  95157. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  95158. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95159. pickedMesh.computeWorldMatrix();
  95160. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  95161. if (!pickedMesh.rotationQuaternion) {
  95162. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  95163. }
  95164. var oldParent = pickedMesh.parent;
  95165. pickedMesh.setParent(null);
  95166. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  95167. pickedMesh.setParent(oldParent);
  95168. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  95169. // Update state
  95170. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  95171. _this.dragging = true;
  95172. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  95173. // Detatch camera controls
  95174. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  95175. if (_this._scene.activeCamera.inputs.attachedElement) {
  95176. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  95177. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  95178. }
  95179. else {
  95180. attachedElement = null;
  95181. }
  95182. }
  95183. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  95184. _this.onDragStartObservable.notifyObservers({});
  95185. }
  95186. }
  95187. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95188. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95189. _this.dragging = false;
  95190. _this._moving = false;
  95191. _this.currentDraggingPointerID = -1;
  95192. pickedMesh = null;
  95193. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95194. // Reattach camera controls
  95195. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  95196. _this._scene.activeCamera.attachControl(attachedElement, true);
  95197. }
  95198. _this.onDragEndObservable.notifyObservers({});
  95199. }
  95200. }
  95201. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95202. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  95203. var zDragFactor = _this.zDragFactor;
  95204. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  95205. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  95206. zDragFactor = 0;
  95207. }
  95208. // Calculate controller drag distance in controller space
  95209. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  95210. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  95211. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  95212. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  95213. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  95214. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  95215. if (_this._virtualDragMesh.position.z < 0) {
  95216. _this._virtualDragMesh.position.z = 0;
  95217. }
  95218. // Update the controller position
  95219. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  95220. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  95221. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95222. // Move the virtualObjectsPosition into the picked mesh's space if needed
  95223. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  95224. if (pickedMesh.parent) {
  95225. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  95226. }
  95227. if (!_this._moving) {
  95228. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  95229. }
  95230. _this._moving = true;
  95231. }
  95232. }
  95233. });
  95234. var tmpQuaternion = new BABYLON.Quaternion();
  95235. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  95236. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  95237. if (_this.dragging && _this._moving && pickedMesh) {
  95238. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  95239. // Slowly move mesh to avoid jitter
  95240. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  95241. // Get change in rotation
  95242. tmpQuaternion.copyFrom(_this._startingOrientation);
  95243. tmpQuaternion.x = -tmpQuaternion.x;
  95244. tmpQuaternion.y = -tmpQuaternion.y;
  95245. tmpQuaternion.z = -tmpQuaternion.z;
  95246. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  95247. // Convert change in rotation to only y axis rotation
  95248. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  95249. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  95250. // Slowly move mesh to avoid jitter
  95251. var oldParent = pickedMesh.parent;
  95252. pickedMesh.setParent(null);
  95253. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  95254. pickedMesh.setParent(oldParent);
  95255. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  95256. }
  95257. });
  95258. };
  95259. /**
  95260. * Detaches the behavior from the mesh
  95261. */
  95262. SixDofDragBehavior.prototype.detach = function () {
  95263. if (this._scene) {
  95264. this._scene.onPointerObservable.remove(this._pointerObserver);
  95265. }
  95266. if (this._ownerNode) {
  95267. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  95268. }
  95269. if (this._virtualOriginMesh) {
  95270. this._virtualOriginMesh.dispose();
  95271. }
  95272. if (this._virtualDragMesh) {
  95273. this._virtualDragMesh.dispose();
  95274. }
  95275. this.onDragEndObservable.clear();
  95276. this.onDragStartObservable.clear();
  95277. };
  95278. return SixDofDragBehavior;
  95279. }());
  95280. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  95281. })(BABYLON || (BABYLON = {}));
  95282. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  95283. var BABYLON;
  95284. (function (BABYLON) {
  95285. /**
  95286. * @hidden
  95287. */
  95288. var FaceDirectionInfo = /** @class */ (function () {
  95289. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  95290. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  95291. if (diff === void 0) { diff = 0; }
  95292. if (ignore === void 0) { ignore = false; }
  95293. this.direction = direction;
  95294. this.rotatedDirection = rotatedDirection;
  95295. this.diff = diff;
  95296. this.ignore = ignore;
  95297. }
  95298. return FaceDirectionInfo;
  95299. }());
  95300. /**
  95301. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  95302. */
  95303. var AttachToBoxBehavior = /** @class */ (function () {
  95304. /**
  95305. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  95306. * @param ui The transform node that should be attched to the mesh
  95307. */
  95308. function AttachToBoxBehavior(ui) {
  95309. this.ui = ui;
  95310. /**
  95311. * The name of the behavior
  95312. */
  95313. this.name = "AttachToBoxBehavior";
  95314. /**
  95315. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  95316. */
  95317. this.distanceAwayFromFace = 0.15;
  95318. /**
  95319. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  95320. */
  95321. this.distanceAwayFromBottomOfFace = 0.15;
  95322. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  95323. this._tmpMatrix = new BABYLON.Matrix();
  95324. this._tmpVector = new BABYLON.Vector3();
  95325. this._zeroVector = BABYLON.Vector3.Zero();
  95326. this._lookAtTmpMatrix = new BABYLON.Matrix();
  95327. /* Does nothing */
  95328. }
  95329. /**
  95330. * Initializes the behavior
  95331. */
  95332. AttachToBoxBehavior.prototype.init = function () {
  95333. /* Does nothing */
  95334. };
  95335. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  95336. var _this = this;
  95337. // Go over each face and calculate the angle between the face's normal and targetDirection
  95338. this._faceVectors.forEach(function (v) {
  95339. if (!_this._target.rotationQuaternion) {
  95340. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  95341. }
  95342. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  95343. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  95344. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  95345. });
  95346. // Return the face information of the one with the normal closeset to target direction
  95347. return this._faceVectors.reduce(function (min, p) {
  95348. if (min.ignore) {
  95349. return p;
  95350. }
  95351. else if (p.ignore) {
  95352. return min;
  95353. }
  95354. else {
  95355. return min.diff < p.diff ? min : p;
  95356. }
  95357. }, this._faceVectors[0]);
  95358. };
  95359. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  95360. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  95361. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  95362. this._lookAtTmpMatrix.invert();
  95363. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  95364. };
  95365. /**
  95366. * Attaches the AttachToBoxBehavior to the passed in mesh
  95367. * @param target The mesh that the specified node will be attached to
  95368. */
  95369. AttachToBoxBehavior.prototype.attach = function (target) {
  95370. var _this = this;
  95371. this._target = target;
  95372. this._scene = this._target.getScene();
  95373. // Every frame, update the app bars position
  95374. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95375. if (!_this._scene.activeCamera) {
  95376. return;
  95377. }
  95378. // Find the face closest to the cameras position
  95379. var cameraPos = _this._scene.activeCamera.position;
  95380. if (_this._scene.activeCamera.devicePosition) {
  95381. cameraPos = _this._scene.activeCamera.devicePosition;
  95382. }
  95383. var facing = _this._closestFace(cameraPos.subtract(target.position));
  95384. if (_this._scene.activeCamera.leftCamera) {
  95385. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  95386. }
  95387. else {
  95388. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  95389. }
  95390. // Get camera up direction
  95391. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  95392. // Ignore faces to not select a parrelel face for the up vector of the UI
  95393. _this._faceVectors.forEach(function (v) {
  95394. if (facing.direction.x && v.direction.x) {
  95395. v.ignore = true;
  95396. }
  95397. if (facing.direction.y && v.direction.y) {
  95398. v.ignore = true;
  95399. }
  95400. if (facing.direction.z && v.direction.z) {
  95401. v.ignore = true;
  95402. }
  95403. });
  95404. var facingUp = _this._closestFace(_this._tmpVector);
  95405. // Unignore faces
  95406. _this._faceVectors.forEach(function (v) {
  95407. v.ignore = false;
  95408. });
  95409. // Position the app bar on that face
  95410. _this.ui.position.copyFrom(target.position);
  95411. if (facing.direction.x) {
  95412. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95413. _this.ui.position.addInPlace(_this._tmpVector);
  95414. }
  95415. if (facing.direction.y) {
  95416. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95417. _this.ui.position.addInPlace(_this._tmpVector);
  95418. }
  95419. if (facing.direction.z) {
  95420. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95421. _this.ui.position.addInPlace(_this._tmpVector);
  95422. }
  95423. // Rotate to be oriented properly to the camera
  95424. if (!_this.ui.rotationQuaternion) {
  95425. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  95426. }
  95427. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  95428. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  95429. // Place ui the correct distance from the bottom of the mesh
  95430. if (facingUp.direction.x) {
  95431. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  95432. }
  95433. if (facingUp.direction.y) {
  95434. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  95435. }
  95436. if (facingUp.direction.z) {
  95437. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  95438. }
  95439. _this.ui.position.addInPlace(_this._tmpVector);
  95440. });
  95441. };
  95442. /**
  95443. * Detaches the behavior from the mesh
  95444. */
  95445. AttachToBoxBehavior.prototype.detach = function () {
  95446. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  95447. };
  95448. return AttachToBoxBehavior;
  95449. }());
  95450. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  95451. })(BABYLON || (BABYLON = {}));
  95452. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  95453. var BABYLON;
  95454. (function (BABYLON) {
  95455. /**
  95456. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  95457. */
  95458. var FadeInOutBehavior = /** @class */ (function () {
  95459. /**
  95460. * Instatiates the FadeInOutBehavior
  95461. */
  95462. function FadeInOutBehavior() {
  95463. var _this = this;
  95464. /**
  95465. * Time in milliseconds to delay before fading in (Default: 0)
  95466. */
  95467. this.delay = 0;
  95468. /**
  95469. * Time in milliseconds for the mesh to fade in (Default: 300)
  95470. */
  95471. this.fadeInTime = 300;
  95472. this._millisecondsPerFrame = 1000 / 60;
  95473. this._hovered = false;
  95474. this._hoverValue = 0;
  95475. this._ownerNode = null;
  95476. this._update = function () {
  95477. if (_this._ownerNode) {
  95478. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  95479. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  95480. if (_this._ownerNode.visibility > 1) {
  95481. _this._setAllVisibility(_this._ownerNode, 1);
  95482. _this._hoverValue = _this.fadeInTime + _this.delay;
  95483. return;
  95484. }
  95485. else if (_this._ownerNode.visibility < 0) {
  95486. _this._setAllVisibility(_this._ownerNode, 0);
  95487. if (_this._hoverValue < 0) {
  95488. _this._hoverValue = 0;
  95489. return;
  95490. }
  95491. }
  95492. setTimeout(_this._update, _this._millisecondsPerFrame);
  95493. }
  95494. };
  95495. }
  95496. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  95497. /**
  95498. * The name of the behavior
  95499. */
  95500. get: function () {
  95501. return "FadeInOut";
  95502. },
  95503. enumerable: true,
  95504. configurable: true
  95505. });
  95506. /**
  95507. * Initializes the behavior
  95508. */
  95509. FadeInOutBehavior.prototype.init = function () {
  95510. };
  95511. /**
  95512. * Attaches the fade behavior on the passed in mesh
  95513. * @param ownerNode The mesh that will be faded in/out once attached
  95514. */
  95515. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  95516. this._ownerNode = ownerNode;
  95517. this._setAllVisibility(this._ownerNode, 0);
  95518. };
  95519. /**
  95520. * Detaches the behavior from the mesh
  95521. */
  95522. FadeInOutBehavior.prototype.detach = function () {
  95523. this._ownerNode = null;
  95524. };
  95525. /**
  95526. * Triggers the mesh to begin fading in or out
  95527. * @param value if the object should fade in or out (true to fade in)
  95528. */
  95529. FadeInOutBehavior.prototype.fadeIn = function (value) {
  95530. this._hovered = value;
  95531. this._update();
  95532. };
  95533. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  95534. var _this = this;
  95535. mesh.visibility = value;
  95536. mesh.getChildMeshes().forEach(function (c) {
  95537. _this._setAllVisibility(c, value);
  95538. });
  95539. };
  95540. return FadeInOutBehavior;
  95541. }());
  95542. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  95543. })(BABYLON || (BABYLON = {}));
  95544. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  95545. var BABYLON;
  95546. (function (BABYLON) {
  95547. /**
  95548. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  95549. */
  95550. var Gizmo = /** @class */ (function () {
  95551. /**
  95552. * Creates a gizmo
  95553. * @param gizmoLayer The utility layer the gizmo will be added to
  95554. */
  95555. function Gizmo(
  95556. /** The utility layer the gizmo will be added to */
  95557. gizmoLayer) {
  95558. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95559. var _this = this;
  95560. this.gizmoLayer = gizmoLayer;
  95561. /**
  95562. * Ratio for the scale of the gizmo (Default: 1)
  95563. */
  95564. this.scaleRatio = 1;
  95565. this._tmpMatrix = new BABYLON.Matrix();
  95566. /**
  95567. * If a custom mesh has been set (Default: false)
  95568. */
  95569. this._customMeshSet = false;
  95570. /**
  95571. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  95572. */
  95573. this.updateGizmoRotationToMatchAttachedMesh = true;
  95574. /**
  95575. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  95576. */
  95577. this.updateGizmoPositionToMatchAttachedMesh = true;
  95578. /**
  95579. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  95580. */
  95581. this._updateScale = true;
  95582. this._interactionsEnabled = true;
  95583. this._tempVector = new BABYLON.Vector3();
  95584. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  95585. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  95586. _this._update();
  95587. });
  95588. this.attachedMesh = null;
  95589. }
  95590. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  95591. /**
  95592. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  95593. * * When set, interactions will be enabled
  95594. */
  95595. get: function () {
  95596. return this._attachedMesh;
  95597. },
  95598. set: function (value) {
  95599. this._attachedMesh = value;
  95600. this._rootMesh.setEnabled(value ? true : false);
  95601. this._attachedMeshChanged(value);
  95602. },
  95603. enumerable: true,
  95604. configurable: true
  95605. });
  95606. /**
  95607. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  95608. * @param mesh The mesh to replace the default mesh of the gizmo
  95609. */
  95610. Gizmo.prototype.setCustomMesh = function (mesh) {
  95611. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  95612. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  95613. }
  95614. this._rootMesh.getChildMeshes().forEach(function (c) {
  95615. c.dispose();
  95616. });
  95617. mesh.parent = this._rootMesh;
  95618. this._customMeshSet = true;
  95619. };
  95620. Gizmo.prototype._attachedMeshChanged = function (value) {
  95621. };
  95622. /**
  95623. * @hidden
  95624. * Updates the gizmo to match the attached mesh's position/rotation
  95625. */
  95626. Gizmo.prototype._update = function () {
  95627. if (this.attachedMesh) {
  95628. if (this.updateGizmoRotationToMatchAttachedMesh) {
  95629. if (!this._rootMesh.rotationQuaternion) {
  95630. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  95631. }
  95632. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  95633. this._tempVector.copyFrom(this.attachedMesh.scaling);
  95634. if (this.attachedMesh.scaling.x < 0) {
  95635. this.attachedMesh.scaling.x *= -1;
  95636. }
  95637. if (this.attachedMesh.scaling.y < 0) {
  95638. this.attachedMesh.scaling.y *= -1;
  95639. }
  95640. if (this.attachedMesh.scaling.z < 0) {
  95641. this.attachedMesh.scaling.z *= -1;
  95642. }
  95643. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  95644. this.attachedMesh.scaling.copyFrom(this._tempVector);
  95645. this.attachedMesh.computeWorldMatrix();
  95646. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  95647. }
  95648. else if (this._rootMesh.rotationQuaternion) {
  95649. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  95650. }
  95651. if (this.updateGizmoPositionToMatchAttachedMesh) {
  95652. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  95653. }
  95654. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  95655. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  95656. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  95657. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  95658. }
  95659. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  95660. var dist = this._tempVector.length() * this.scaleRatio;
  95661. this._rootMesh.scaling.set(dist, dist, dist);
  95662. }
  95663. }
  95664. };
  95665. /**
  95666. * Disposes of the gizmo
  95667. */
  95668. Gizmo.prototype.dispose = function () {
  95669. this._rootMesh.dispose();
  95670. if (this._beforeRenderObserver) {
  95671. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95672. }
  95673. };
  95674. return Gizmo;
  95675. }());
  95676. BABYLON.Gizmo = Gizmo;
  95677. })(BABYLON || (BABYLON = {}));
  95678. //# sourceMappingURL=babylon.gizmo.js.map
  95679. var BABYLON;
  95680. (function (BABYLON) {
  95681. /**
  95682. * Single axis drag gizmo
  95683. */
  95684. var AxisDragGizmo = /** @class */ (function (_super) {
  95685. __extends(AxisDragGizmo, _super);
  95686. /**
  95687. * Creates an AxisDragGizmo
  95688. * @param gizmoLayer The utility layer the gizmo will be added to
  95689. * @param dragAxis The axis which the gizmo will be able to drag on
  95690. * @param color The color of the gizmo
  95691. */
  95692. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  95693. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95694. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95695. var _this = _super.call(this, gizmoLayer) || this;
  95696. _this._pointerObserver = null;
  95697. /**
  95698. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  95699. */
  95700. _this.snapDistance = 0;
  95701. /**
  95702. * Event that fires each time the gizmo snaps to a new location.
  95703. * * snapDistance is the the change in distance
  95704. */
  95705. _this.onSnapObservable = new BABYLON.Observable();
  95706. // Create Material
  95707. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95708. coloredMaterial.disableLighting = true;
  95709. coloredMaterial.emissiveColor = color;
  95710. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95711. hoverMaterial.disableLighting = true;
  95712. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95713. // Build mesh on root node
  95714. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95715. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  95716. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  95717. arrowTail.color = coloredMaterial.emissiveColor;
  95718. arrow.addChild(arrowMesh);
  95719. arrow.addChild(arrowTail);
  95720. // Position arrow pointing in its drag axis
  95721. arrowMesh.scaling.scaleInPlace(0.05);
  95722. arrowMesh.material = coloredMaterial;
  95723. arrowMesh.rotation.x = Math.PI / 2;
  95724. arrowMesh.position.z += 0.3;
  95725. arrowTail.scaling.scaleInPlace(0.26);
  95726. arrowTail.rotation.x = Math.PI / 2;
  95727. arrowTail.material = coloredMaterial;
  95728. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  95729. arrow.scaling.scaleInPlace(1 / 3);
  95730. _this._rootMesh.addChild(arrow);
  95731. var currentSnapDragDistance = 0;
  95732. var tmpVector = new BABYLON.Vector3();
  95733. var tmpSnapEvent = { snapDistance: 0 };
  95734. // Add drag behavior to handle events when the gizmo is dragged
  95735. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95736. _this.dragBehavior.moveAttached = false;
  95737. _this._rootMesh.addBehavior(_this.dragBehavior);
  95738. var localDelta = new BABYLON.Vector3();
  95739. var tmpMatrix = new BABYLON.Matrix();
  95740. _this.dragBehavior.onDragObservable.add(function (event) {
  95741. if (_this.attachedMesh) {
  95742. // Convert delta to local translation if it has a parent
  95743. if (_this.attachedMesh.parent) {
  95744. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  95745. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  95746. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  95747. }
  95748. else {
  95749. localDelta.copyFrom(event.delta);
  95750. }
  95751. // Snapping logic
  95752. if (_this.snapDistance == 0) {
  95753. _this.attachedMesh.position.addInPlace(localDelta);
  95754. }
  95755. else {
  95756. currentSnapDragDistance += event.dragDistance;
  95757. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  95758. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  95759. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  95760. localDelta.normalizeToRef(tmpVector);
  95761. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  95762. _this.attachedMesh.position.addInPlace(tmpVector);
  95763. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  95764. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  95765. }
  95766. }
  95767. }
  95768. });
  95769. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95770. if (_this._customMeshSet) {
  95771. return;
  95772. }
  95773. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  95774. var material = isHovered ? hoverMaterial : coloredMaterial;
  95775. _this._rootMesh.getChildMeshes().forEach(function (m) {
  95776. m.material = material;
  95777. if (m.color) {
  95778. m.color = material.emissiveColor;
  95779. }
  95780. });
  95781. });
  95782. return _this;
  95783. }
  95784. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  95785. if (this.dragBehavior) {
  95786. this.dragBehavior.enabled = value ? true : false;
  95787. }
  95788. };
  95789. /**
  95790. * Disposes of the gizmo
  95791. */
  95792. AxisDragGizmo.prototype.dispose = function () {
  95793. this.onSnapObservable.clear();
  95794. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95795. this.dragBehavior.detach();
  95796. _super.prototype.dispose.call(this);
  95797. };
  95798. return AxisDragGizmo;
  95799. }(BABYLON.Gizmo));
  95800. BABYLON.AxisDragGizmo = AxisDragGizmo;
  95801. })(BABYLON || (BABYLON = {}));
  95802. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  95803. var BABYLON;
  95804. (function (BABYLON) {
  95805. /**
  95806. * Single axis scale gizmo
  95807. */
  95808. var AxisScaleGizmo = /** @class */ (function (_super) {
  95809. __extends(AxisScaleGizmo, _super);
  95810. /**
  95811. * Creates an AxisScaleGizmo
  95812. * @param gizmoLayer The utility layer the gizmo will be added to
  95813. * @param dragAxis The axis which the gizmo will be able to scale on
  95814. * @param color The color of the gizmo
  95815. */
  95816. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  95817. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95818. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95819. var _this = _super.call(this, gizmoLayer) || this;
  95820. _this._pointerObserver = null;
  95821. /**
  95822. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  95823. */
  95824. _this.snapDistance = 0;
  95825. /**
  95826. * Event that fires each time the gizmo snaps to a new location.
  95827. * * snapDistance is the the change in distance
  95828. */
  95829. _this.onSnapObservable = new BABYLON.Observable();
  95830. /**
  95831. * If the scaling operation should be done on all axis (default: false)
  95832. */
  95833. _this.uniformScaling = false;
  95834. // Create Material
  95835. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95836. _this._coloredMaterial.disableLighting = true;
  95837. _this._coloredMaterial.emissiveColor = color;
  95838. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95839. hoverMaterial.disableLighting = true;
  95840. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95841. // Build mesh on root node
  95842. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95843. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  95844. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  95845. arrowTail.color = _this._coloredMaterial.emissiveColor;
  95846. arrow.addChild(arrowMesh);
  95847. arrow.addChild(arrowTail);
  95848. // Position arrow pointing in its drag axis
  95849. arrowMesh.scaling.scaleInPlace(0.1);
  95850. arrowMesh.material = _this._coloredMaterial;
  95851. arrowMesh.rotation.x = Math.PI / 2;
  95852. arrowMesh.position.z += 0.3;
  95853. arrowTail.scaling.scaleInPlace(0.26);
  95854. arrowTail.rotation.x = Math.PI / 2;
  95855. arrowTail.material = _this._coloredMaterial;
  95856. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  95857. _this._rootMesh.addChild(arrow);
  95858. arrow.scaling.scaleInPlace(1 / 3);
  95859. // Add drag behavior to handle events when the gizmo is dragged
  95860. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95861. _this.dragBehavior.moveAttached = false;
  95862. _this._rootMesh.addBehavior(_this.dragBehavior);
  95863. var currentSnapDragDistance = 0;
  95864. var tmpVector = new BABYLON.Vector3();
  95865. var tmpSnapEvent = { snapDistance: 0 };
  95866. _this.dragBehavior.onDragObservable.add(function (event) {
  95867. if (_this.attachedMesh) {
  95868. // Snapping logic
  95869. var snapped = false;
  95870. var dragSteps = 0;
  95871. if (_this.uniformScaling) {
  95872. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  95873. if (tmpVector.y < 0) {
  95874. tmpVector.scaleInPlace(-1);
  95875. }
  95876. }
  95877. else {
  95878. tmpVector.copyFrom(dragAxis);
  95879. }
  95880. if (_this.snapDistance == 0) {
  95881. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  95882. }
  95883. else {
  95884. currentSnapDragDistance += event.dragDistance;
  95885. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  95886. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  95887. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  95888. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  95889. snapped = true;
  95890. }
  95891. else {
  95892. tmpVector.scaleInPlace(0);
  95893. }
  95894. }
  95895. _this.attachedMesh.scaling.addInPlace(tmpVector);
  95896. if (snapped) {
  95897. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  95898. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  95899. }
  95900. }
  95901. });
  95902. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95903. if (_this._customMeshSet) {
  95904. return;
  95905. }
  95906. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  95907. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  95908. _this._rootMesh.getChildMeshes().forEach(function (m) {
  95909. m.material = material;
  95910. if (m.color) {
  95911. m.color = material.emissiveColor;
  95912. }
  95913. });
  95914. });
  95915. return _this;
  95916. }
  95917. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  95918. if (this.dragBehavior) {
  95919. this.dragBehavior.enabled = value ? true : false;
  95920. }
  95921. };
  95922. /**
  95923. * Disposes of the gizmo
  95924. */
  95925. AxisScaleGizmo.prototype.dispose = function () {
  95926. this.onSnapObservable.clear();
  95927. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95928. this.dragBehavior.detach();
  95929. _super.prototype.dispose.call(this);
  95930. };
  95931. /**
  95932. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  95933. * @param mesh The mesh to replace the default mesh of the gizmo
  95934. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  95935. */
  95936. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  95937. var _this = this;
  95938. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  95939. _super.prototype.setCustomMesh.call(this, mesh);
  95940. if (useGizmoMaterial) {
  95941. this._rootMesh.getChildMeshes().forEach(function (m) {
  95942. m.material = _this._coloredMaterial;
  95943. if (m.color) {
  95944. m.color = _this._coloredMaterial.emissiveColor;
  95945. }
  95946. });
  95947. this._customMeshSet = false;
  95948. }
  95949. };
  95950. return AxisScaleGizmo;
  95951. }(BABYLON.Gizmo));
  95952. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  95953. })(BABYLON || (BABYLON = {}));
  95954. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  95955. var BABYLON;
  95956. (function (BABYLON) {
  95957. /**
  95958. * Single plane rotation gizmo
  95959. */
  95960. var PlaneRotationGizmo = /** @class */ (function (_super) {
  95961. __extends(PlaneRotationGizmo, _super);
  95962. /**
  95963. * Creates a PlaneRotationGizmo
  95964. * @param gizmoLayer The utility layer the gizmo will be added to
  95965. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  95966. * @param color The color of the gizmo
  95967. */
  95968. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  95969. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95970. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95971. var _this = _super.call(this, gizmoLayer) || this;
  95972. _this._pointerObserver = null;
  95973. /**
  95974. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  95975. */
  95976. _this.snapDistance = 0;
  95977. /**
  95978. * Event that fires each time the gizmo snaps to a new location.
  95979. * * snapDistance is the the change in distance
  95980. */
  95981. _this.onSnapObservable = new BABYLON.Observable();
  95982. // Create Material
  95983. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95984. coloredMaterial.disableLighting = true;
  95985. coloredMaterial.emissiveColor = color;
  95986. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95987. hoverMaterial.disableLighting = true;
  95988. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95989. // Build mesh on root node
  95990. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95991. // Create circle out of lines
  95992. var tessellation = 20;
  95993. var radius = 0.8;
  95994. var points = new Array();
  95995. for (var i = 0; i < tessellation; i++) {
  95996. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  95997. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  95998. }
  95999. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  96000. rotationMesh.color = coloredMaterial.emissiveColor;
  96001. // Position arrow pointing in its drag axis
  96002. rotationMesh.scaling.scaleInPlace(0.26);
  96003. rotationMesh.material = coloredMaterial;
  96004. rotationMesh.rotation.x = Math.PI / 2;
  96005. parentMesh.addChild(rotationMesh);
  96006. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  96007. _this._rootMesh.addChild(parentMesh);
  96008. parentMesh.scaling.scaleInPlace(1 / 3);
  96009. // Add drag behavior to handle events when the gizmo is dragged
  96010. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  96011. _this.dragBehavior.moveAttached = false;
  96012. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  96013. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  96014. _this._rootMesh.addBehavior(_this.dragBehavior);
  96015. var lastDragPosition = new BABYLON.Vector3();
  96016. _this.dragBehavior.onDragStartObservable.add(function (e) {
  96017. if (_this.attachedMesh) {
  96018. lastDragPosition.copyFrom(e.dragPlanePoint);
  96019. }
  96020. });
  96021. var rotationMatrix = new BABYLON.Matrix();
  96022. var planeNormalTowardsCamera = new BABYLON.Vector3();
  96023. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  96024. var tmpSnapEvent = { snapDistance: 0 };
  96025. var currentSnapDragDistance = 0;
  96026. var tmpMatrix = new BABYLON.Matrix();
  96027. var tmpVector = new BABYLON.Vector3();
  96028. var amountToRotate = new BABYLON.Quaternion();
  96029. _this.dragBehavior.onDragObservable.add(function (event) {
  96030. if (_this.attachedMesh) {
  96031. if (!_this.attachedMesh.rotationQuaternion) {
  96032. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  96033. }
  96034. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  96035. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  96036. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  96037. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  96038. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  96039. var angle = Math.atan2(cross.length(), dot);
  96040. planeNormalTowardsCamera.copyFrom(planeNormal);
  96041. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  96042. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  96043. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  96044. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  96045. }
  96046. // Flip up vector depending on which side the camera is on
  96047. if (gizmoLayer.utilityLayerScene.activeCamera) {
  96048. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  96049. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  96050. planeNormalTowardsCamera.scaleInPlace(-1);
  96051. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  96052. }
  96053. }
  96054. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  96055. if (halfCircleSide)
  96056. angle = -angle;
  96057. // Snapping logic
  96058. var snapped = false;
  96059. if (_this.snapDistance != 0) {
  96060. currentSnapDragDistance += angle;
  96061. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96062. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96063. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96064. angle = _this.snapDistance * dragSteps;
  96065. snapped = true;
  96066. }
  96067. else {
  96068. angle = 0;
  96069. }
  96070. }
  96071. // If the mesh has a parent, convert needed world rotation to local rotation
  96072. tmpMatrix.reset();
  96073. if (_this.attachedMesh.parent) {
  96074. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96075. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  96076. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  96077. }
  96078. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  96079. var quaternionCoefficient = Math.sin(angle / 2);
  96080. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  96081. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  96082. if (tmpMatrix.determinant() > 0) {
  96083. amountToRotate.toEulerAnglesToRef(tmpVector);
  96084. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  96085. }
  96086. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  96087. // Rotate selected mesh quaternion over fixed axis
  96088. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  96089. }
  96090. else {
  96091. // Rotate selected mesh quaternion over rotated axis
  96092. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  96093. }
  96094. lastDragPosition.copyFrom(event.dragPlanePoint);
  96095. if (snapped) {
  96096. tmpSnapEvent.snapDistance = angle;
  96097. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96098. }
  96099. }
  96100. });
  96101. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96102. if (_this._customMeshSet) {
  96103. return;
  96104. }
  96105. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96106. var material = isHovered ? hoverMaterial : coloredMaterial;
  96107. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96108. m.material = material;
  96109. if (m.color) {
  96110. m.color = material.emissiveColor;
  96111. }
  96112. });
  96113. });
  96114. return _this;
  96115. }
  96116. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  96117. if (this.dragBehavior) {
  96118. this.dragBehavior.enabled = value ? true : false;
  96119. }
  96120. };
  96121. /**
  96122. * Disposes of the gizmo
  96123. */
  96124. PlaneRotationGizmo.prototype.dispose = function () {
  96125. this.onSnapObservable.clear();
  96126. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96127. this.dragBehavior.detach();
  96128. _super.prototype.dispose.call(this);
  96129. };
  96130. return PlaneRotationGizmo;
  96131. }(BABYLON.Gizmo));
  96132. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  96133. })(BABYLON || (BABYLON = {}));
  96134. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  96135. var BABYLON;
  96136. (function (BABYLON) {
  96137. /**
  96138. * Gizmo that enables dragging a mesh along 3 axis
  96139. */
  96140. var PositionGizmo = /** @class */ (function (_super) {
  96141. __extends(PositionGizmo, _super);
  96142. /**
  96143. * Creates a PositionGizmo
  96144. * @param gizmoLayer The utility layer the gizmo will be added to
  96145. */
  96146. function PositionGizmo(gizmoLayer) {
  96147. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96148. var _this = _super.call(this, gizmoLayer) || this;
  96149. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96150. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96151. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96152. _this.attachedMesh = null;
  96153. return _this;
  96154. }
  96155. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  96156. set: function (mesh) {
  96157. if (this.xGizmo) {
  96158. this.xGizmo.attachedMesh = mesh;
  96159. this.yGizmo.attachedMesh = mesh;
  96160. this.zGizmo.attachedMesh = mesh;
  96161. }
  96162. },
  96163. enumerable: true,
  96164. configurable: true
  96165. });
  96166. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96167. get: function () {
  96168. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96169. },
  96170. set: function (value) {
  96171. if (this.xGizmo) {
  96172. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96173. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96174. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96175. }
  96176. },
  96177. enumerable: true,
  96178. configurable: true
  96179. });
  96180. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  96181. get: function () {
  96182. return this.xGizmo.snapDistance;
  96183. },
  96184. /**
  96185. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96186. */
  96187. set: function (value) {
  96188. if (this.xGizmo) {
  96189. this.xGizmo.snapDistance = value;
  96190. this.yGizmo.snapDistance = value;
  96191. this.zGizmo.snapDistance = value;
  96192. }
  96193. },
  96194. enumerable: true,
  96195. configurable: true
  96196. });
  96197. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  96198. get: function () {
  96199. return this.xGizmo.scaleRatio;
  96200. },
  96201. /**
  96202. * Ratio for the scale of the gizmo (Default: 1)
  96203. */
  96204. set: function (value) {
  96205. if (this.xGizmo) {
  96206. this.xGizmo.scaleRatio = value;
  96207. this.yGizmo.scaleRatio = value;
  96208. this.zGizmo.scaleRatio = value;
  96209. }
  96210. },
  96211. enumerable: true,
  96212. configurable: true
  96213. });
  96214. /**
  96215. * Disposes of the gizmo
  96216. */
  96217. PositionGizmo.prototype.dispose = function () {
  96218. this.xGizmo.dispose();
  96219. this.yGizmo.dispose();
  96220. this.zGizmo.dispose();
  96221. };
  96222. /**
  96223. * CustomMeshes are not supported by this gizmo
  96224. * @param mesh The mesh to replace the default mesh of the gizmo
  96225. */
  96226. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  96227. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  96228. };
  96229. return PositionGizmo;
  96230. }(BABYLON.Gizmo));
  96231. BABYLON.PositionGizmo = PositionGizmo;
  96232. })(BABYLON || (BABYLON = {}));
  96233. //# sourceMappingURL=babylon.positionGizmo.js.map
  96234. var BABYLON;
  96235. (function (BABYLON) {
  96236. /**
  96237. * Gizmo that enables rotating a mesh along 3 axis
  96238. */
  96239. var RotationGizmo = /** @class */ (function (_super) {
  96240. __extends(RotationGizmo, _super);
  96241. /**
  96242. * Creates a RotationGizmo
  96243. * @param gizmoLayer The utility layer the gizmo will be added to
  96244. */
  96245. function RotationGizmo(gizmoLayer) {
  96246. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96247. var _this = _super.call(this, gizmoLayer) || this;
  96248. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96249. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96250. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96251. _this.attachedMesh = null;
  96252. return _this;
  96253. }
  96254. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  96255. set: function (mesh) {
  96256. if (this.xGizmo) {
  96257. this.xGizmo.attachedMesh = mesh;
  96258. this.yGizmo.attachedMesh = mesh;
  96259. this.zGizmo.attachedMesh = mesh;
  96260. }
  96261. },
  96262. enumerable: true,
  96263. configurable: true
  96264. });
  96265. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96266. get: function () {
  96267. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96268. },
  96269. set: function (value) {
  96270. if (this.xGizmo) {
  96271. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96272. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96273. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96274. }
  96275. },
  96276. enumerable: true,
  96277. configurable: true
  96278. });
  96279. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  96280. get: function () {
  96281. return this.xGizmo.snapDistance;
  96282. },
  96283. /**
  96284. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96285. */
  96286. set: function (value) {
  96287. if (this.xGizmo) {
  96288. this.xGizmo.snapDistance = value;
  96289. this.yGizmo.snapDistance = value;
  96290. this.zGizmo.snapDistance = value;
  96291. }
  96292. },
  96293. enumerable: true,
  96294. configurable: true
  96295. });
  96296. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  96297. get: function () {
  96298. return this.xGizmo.scaleRatio;
  96299. },
  96300. /**
  96301. * Ratio for the scale of the gizmo (Default: 1)
  96302. */
  96303. set: function (value) {
  96304. if (this.xGizmo) {
  96305. this.xGizmo.scaleRatio = value;
  96306. this.yGizmo.scaleRatio = value;
  96307. this.zGizmo.scaleRatio = value;
  96308. }
  96309. },
  96310. enumerable: true,
  96311. configurable: true
  96312. });
  96313. /**
  96314. * Disposes of the gizmo
  96315. */
  96316. RotationGizmo.prototype.dispose = function () {
  96317. this.xGizmo.dispose();
  96318. this.yGizmo.dispose();
  96319. this.zGizmo.dispose();
  96320. };
  96321. /**
  96322. * CustomMeshes are not supported by this gizmo
  96323. * @param mesh The mesh to replace the default mesh of the gizmo
  96324. */
  96325. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  96326. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  96327. };
  96328. return RotationGizmo;
  96329. }(BABYLON.Gizmo));
  96330. BABYLON.RotationGizmo = RotationGizmo;
  96331. })(BABYLON || (BABYLON = {}));
  96332. //# sourceMappingURL=babylon.rotationGizmo.js.map
  96333. var BABYLON;
  96334. (function (BABYLON) {
  96335. /**
  96336. * Gizmo that enables scaling a mesh along 3 axis
  96337. */
  96338. var ScaleGizmo = /** @class */ (function (_super) {
  96339. __extends(ScaleGizmo, _super);
  96340. /**
  96341. * Creates a ScaleGizmo
  96342. * @param gizmoLayer The utility layer the gizmo will be added to
  96343. */
  96344. function ScaleGizmo(gizmoLayer) {
  96345. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96346. var _this = _super.call(this, gizmoLayer) || this;
  96347. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96348. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96349. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96350. // Create uniform scale gizmo
  96351. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  96352. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  96353. _this.uniformScaleGizmo.uniformScaling = true;
  96354. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  96355. octahedron.scaling.scaleInPlace(0.007);
  96356. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  96357. _this.attachedMesh = null;
  96358. return _this;
  96359. }
  96360. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  96361. set: function (mesh) {
  96362. if (this.xGizmo) {
  96363. this.xGizmo.attachedMesh = mesh;
  96364. this.yGizmo.attachedMesh = mesh;
  96365. this.zGizmo.attachedMesh = mesh;
  96366. this.uniformScaleGizmo.attachedMesh = mesh;
  96367. }
  96368. },
  96369. enumerable: true,
  96370. configurable: true
  96371. });
  96372. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96373. get: function () {
  96374. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96375. },
  96376. set: function (value) {
  96377. if (this.xGizmo) {
  96378. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96379. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96380. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96381. }
  96382. },
  96383. enumerable: true,
  96384. configurable: true
  96385. });
  96386. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  96387. get: function () {
  96388. return this.xGizmo.snapDistance;
  96389. },
  96390. /**
  96391. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96392. */
  96393. set: function (value) {
  96394. if (this.xGizmo) {
  96395. this.xGizmo.snapDistance = value;
  96396. this.yGizmo.snapDistance = value;
  96397. this.zGizmo.snapDistance = value;
  96398. this.uniformScaleGizmo.snapDistance = value;
  96399. }
  96400. },
  96401. enumerable: true,
  96402. configurable: true
  96403. });
  96404. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  96405. get: function () {
  96406. return this.xGizmo.scaleRatio;
  96407. },
  96408. /**
  96409. * Ratio for the scale of the gizmo (Default: 1)
  96410. */
  96411. set: function (value) {
  96412. if (this.xGizmo) {
  96413. this.xGizmo.scaleRatio = value;
  96414. this.yGizmo.scaleRatio = value;
  96415. this.zGizmo.scaleRatio = value;
  96416. this.uniformScaleGizmo.scaleRatio = value;
  96417. }
  96418. },
  96419. enumerable: true,
  96420. configurable: true
  96421. });
  96422. /**
  96423. * Disposes of the gizmo
  96424. */
  96425. ScaleGizmo.prototype.dispose = function () {
  96426. this.xGizmo.dispose();
  96427. this.yGizmo.dispose();
  96428. this.zGizmo.dispose();
  96429. this.uniformScaleGizmo.dispose();
  96430. };
  96431. return ScaleGizmo;
  96432. }(BABYLON.Gizmo));
  96433. BABYLON.ScaleGizmo = ScaleGizmo;
  96434. })(BABYLON || (BABYLON = {}));
  96435. //# sourceMappingURL=babylon.scaleGizmo.js.map
  96436. var BABYLON;
  96437. (function (BABYLON) {
  96438. /**
  96439. * Bounding box gizmo
  96440. */
  96441. var BoundingBoxGizmo = /** @class */ (function (_super) {
  96442. __extends(BoundingBoxGizmo, _super);
  96443. /**
  96444. * Creates an BoundingBoxGizmo
  96445. * @param gizmoLayer The utility layer the gizmo will be added to
  96446. * @param color The color of the gizmo
  96447. */
  96448. function BoundingBoxGizmo(color, gizmoLayer) {
  96449. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96450. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  96451. var _this = _super.call(this, gizmoLayer) || this;
  96452. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  96453. _this._renderObserver = null;
  96454. _this._pointerObserver = null;
  96455. _this._scaleDragSpeed = 0.2;
  96456. _this._tmpQuaternion = new BABYLON.Quaternion();
  96457. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  96458. _this._tmpRotationMatrix = new BABYLON.Matrix();
  96459. /**
  96460. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  96461. */
  96462. _this.ignoreChildren = false;
  96463. /**
  96464. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  96465. */
  96466. _this.includeChildPredicate = null;
  96467. /**
  96468. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  96469. */
  96470. _this.rotationSphereSize = 0.1;
  96471. /**
  96472. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  96473. */
  96474. _this.scaleBoxSize = 0.1;
  96475. /**
  96476. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  96477. */
  96478. _this.fixedDragMeshScreenSize = false;
  96479. /**
  96480. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  96481. */
  96482. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  96483. /**
  96484. * Fired when a rotation sphere or scale box is dragged
  96485. */
  96486. _this.onDragStartObservable = new BABYLON.Observable();
  96487. /**
  96488. * Fired when a scale box is dragged
  96489. */
  96490. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  96491. /**
  96492. * Fired when a scale box drag is ended
  96493. */
  96494. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  96495. /**
  96496. * Fired when a rotation sphere is dragged
  96497. */
  96498. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  96499. /**
  96500. * Fired when a rotation sphere drag is ended
  96501. */
  96502. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  96503. /**
  96504. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  96505. */
  96506. _this.scalePivot = null;
  96507. _this._existingMeshScale = new BABYLON.Vector3();
  96508. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  96509. _this._updateScale = false;
  96510. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  96511. // Create Materials
  96512. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96513. coloredMaterial.disableLighting = true;
  96514. coloredMaterial.emissiveColor = color;
  96515. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96516. hoverColoredMaterial.disableLighting = true;
  96517. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96518. // Build bounding box out of lines
  96519. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96520. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  96521. var lines = [];
  96522. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  96523. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96524. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96525. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96526. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96527. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96528. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96529. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96530. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96531. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96532. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96533. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96534. lines.forEach(function (l) {
  96535. l.color = color;
  96536. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  96537. l.isPickable = false;
  96538. _this._lineBoundingBox.addChild(l);
  96539. });
  96540. _this._rootMesh.addChild(_this._lineBoundingBox);
  96541. // Create rotation spheres
  96542. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96543. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  96544. var _loop_1 = function (i_1) {
  96545. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  96546. sphere.rotationQuaternion = new BABYLON.Quaternion();
  96547. sphere.material = coloredMaterial;
  96548. // Drag behavior
  96549. _dragBehavior = new BABYLON.PointerDragBehavior({});
  96550. _dragBehavior.moveAttached = false;
  96551. _dragBehavior.updateDragPlane = false;
  96552. sphere.addBehavior(_dragBehavior);
  96553. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  96554. var totalTurnAmountOfDrag = 0;
  96555. _dragBehavior.onDragStartObservable.add(function (event) {
  96556. startingTurnDirection.copyFrom(sphere.forward);
  96557. totalTurnAmountOfDrag = 0;
  96558. });
  96559. _dragBehavior.onDragObservable.add(function (event) {
  96560. _this.onRotationSphereDragObservable.notifyObservers({});
  96561. if (_this.attachedMesh) {
  96562. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  96563. var worldDragDirection = startingTurnDirection;
  96564. // Project the world right on to the drag plane
  96565. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  96566. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  96567. // project drag delta on to the resulting drag axis and rotate based on that
  96568. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  96569. // Make rotation relative to size of mesh.
  96570. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  96571. // Rotate based on axis
  96572. if (!_this.attachedMesh.rotationQuaternion) {
  96573. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  96574. }
  96575. if (!_this._anchorMesh.rotationQuaternion) {
  96576. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  96577. }
  96578. // Do not allow the object to turn more than a full circle
  96579. totalTurnAmountOfDrag += projectDist;
  96580. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  96581. if (i_1 >= 8) {
  96582. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  96583. }
  96584. else if (i_1 >= 4) {
  96585. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  96586. }
  96587. else {
  96588. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  96589. }
  96590. // Rotate around center of bounding box
  96591. _this._anchorMesh.addChild(_this.attachedMesh);
  96592. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  96593. _this._anchorMesh.removeChild(_this.attachedMesh);
  96594. }
  96595. _this.updateBoundingBox();
  96596. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  96597. }
  96598. });
  96599. // Selection/deselection
  96600. _dragBehavior.onDragStartObservable.add(function () {
  96601. _this.onDragStartObservable.notifyObservers({});
  96602. _this._selectNode(sphere);
  96603. });
  96604. _dragBehavior.onDragEndObservable.add(function () {
  96605. _this.onRotationSphereDragEndObservable.notifyObservers({});
  96606. _this._selectNode(null);
  96607. });
  96608. this_1._rotateSpheresParent.addChild(sphere);
  96609. };
  96610. var this_1 = this, _dragBehavior;
  96611. for (var i_1 = 0; i_1 < 12; i_1++) {
  96612. _loop_1(i_1);
  96613. }
  96614. _this._rootMesh.addChild(_this._rotateSpheresParent);
  96615. // Create scale cubes
  96616. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96617. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  96618. for (var i = 0; i < 2; i++) {
  96619. for (var j = 0; j < 2; j++) {
  96620. var _loop_2 = function () {
  96621. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  96622. box.material = coloredMaterial;
  96623. // Dragging logic
  96624. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  96625. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96626. _dragBehavior.moveAttached = false;
  96627. box.addBehavior(_dragBehavior);
  96628. _dragBehavior.onDragObservable.add(function (event) {
  96629. _this.onScaleBoxDragObservable.notifyObservers({});
  96630. if (_this.attachedMesh) {
  96631. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  96632. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  96633. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  96634. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  96635. _this.updateBoundingBox();
  96636. if (_this.scalePivot) {
  96637. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  96638. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  96639. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  96640. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  96641. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  96642. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  96643. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  96644. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  96645. }
  96646. else {
  96647. // Scale from the position of the opposite corner
  96648. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  96649. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  96650. }
  96651. _this._anchorMesh.addChild(_this.attachedMesh);
  96652. _this._anchorMesh.scaling.addInPlace(deltaScale);
  96653. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  96654. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  96655. }
  96656. _this._anchorMesh.removeChild(_this.attachedMesh);
  96657. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  96658. }
  96659. });
  96660. // Selection/deselection
  96661. _dragBehavior.onDragStartObservable.add(function () {
  96662. _this.onDragStartObservable.notifyObservers({});
  96663. _this._selectNode(box);
  96664. });
  96665. _dragBehavior.onDragEndObservable.add(function () {
  96666. _this.onScaleBoxDragEndObservable.notifyObservers({});
  96667. _this._selectNode(null);
  96668. });
  96669. this_2._scaleBoxesParent.addChild(box);
  96670. };
  96671. var this_2 = this, _dragBehavior;
  96672. for (var k = 0; k < 2; k++) {
  96673. _loop_2();
  96674. }
  96675. }
  96676. }
  96677. _this._rootMesh.addChild(_this._scaleBoxesParent);
  96678. // Hover color change
  96679. var pointerIds = new Array();
  96680. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96681. if (!pointerIds[pointerInfo.event.pointerId]) {
  96682. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  96683. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  96684. pointerIds[pointerInfo.event.pointerId] = mesh;
  96685. mesh.material = hoverColoredMaterial;
  96686. }
  96687. });
  96688. }
  96689. else {
  96690. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  96691. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  96692. delete pointerIds[pointerInfo.event.pointerId];
  96693. }
  96694. }
  96695. });
  96696. // Update bounding box positions
  96697. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  96698. // Only update the bouding box if scaling has changed
  96699. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  96700. _this.updateBoundingBox();
  96701. }
  96702. });
  96703. _this.updateBoundingBox();
  96704. return _this;
  96705. }
  96706. /** @hidden */
  96707. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  96708. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  96709. // Save old pivot and set pivot to 0,0,0
  96710. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  96711. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  96712. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  96713. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  96714. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  96715. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  96716. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  96717. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  96718. }
  96719. }
  96720. BoundingBoxGizmo._PivotCached++;
  96721. };
  96722. /** @hidden */
  96723. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  96724. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  96725. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  96726. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  96727. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  96728. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  96729. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  96730. }
  96731. this._PivotCached--;
  96732. };
  96733. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  96734. if (value) {
  96735. // Reset anchor mesh to match attached mesh's scale
  96736. // This is needed to avoid invalid box/sphere position on first drag
  96737. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  96738. this._anchorMesh.addChild(value);
  96739. this._anchorMesh.removeChild(value);
  96740. BoundingBoxGizmo._RestorePivotPoint(value);
  96741. this.updateBoundingBox();
  96742. }
  96743. };
  96744. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  96745. this._rotateSpheresParent.getChildMeshes()
  96746. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  96747. m.isVisible = (!selectedMesh || m == selectedMesh);
  96748. });
  96749. };
  96750. /**
  96751. * Updates the bounding box information for the Gizmo
  96752. */
  96753. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  96754. if (this.attachedMesh) {
  96755. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  96756. this._update();
  96757. // Rotate based on axis
  96758. if (!this.attachedMesh.rotationQuaternion) {
  96759. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  96760. }
  96761. if (!this._anchorMesh.rotationQuaternion) {
  96762. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  96763. }
  96764. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  96765. // Store original position and reset mesh to origin before computing the bounding box
  96766. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  96767. this._tmpVector.copyFrom(this.attachedMesh.position);
  96768. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  96769. this.attachedMesh.position.set(0, 0, 0);
  96770. // Update bounding dimensions/positions
  96771. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  96772. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  96773. // Update gizmo to match bounding box scaling and rotation
  96774. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  96775. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  96776. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  96777. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  96778. this._lineBoundingBox.computeWorldMatrix();
  96779. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  96780. // restore position/rotation values
  96781. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  96782. this.attachedMesh.position.copyFrom(this._tmpVector);
  96783. }
  96784. // Update rotation sphere locations
  96785. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  96786. for (var i = 0; i < 3; i++) {
  96787. for (var j = 0; j < 2; j++) {
  96788. for (var k = 0; k < 2; k++) {
  96789. var index = ((i * 4) + (j * 2)) + k;
  96790. if (i == 0) {
  96791. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  96792. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96793. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96794. }
  96795. if (i == 1) {
  96796. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  96797. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96798. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96799. }
  96800. if (i == 2) {
  96801. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  96802. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96803. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96804. }
  96805. if (this.fixedDragMeshScreenSize) {
  96806. this._rootMesh.computeWorldMatrix();
  96807. this._rotateSpheresParent.computeWorldMatrix();
  96808. rotateSpheres[index].computeWorldMatrix();
  96809. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  96810. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  96811. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  96812. }
  96813. else {
  96814. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  96815. }
  96816. }
  96817. }
  96818. }
  96819. // Update scale box locations
  96820. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  96821. for (var i = 0; i < 2; i++) {
  96822. for (var j = 0; j < 2; j++) {
  96823. for (var k = 0; k < 2; k++) {
  96824. var index = ((i * 4) + (j * 2)) + k;
  96825. if (scaleBoxes[index]) {
  96826. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  96827. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96828. if (this.fixedDragMeshScreenSize) {
  96829. this._rootMesh.computeWorldMatrix();
  96830. this._scaleBoxesParent.computeWorldMatrix();
  96831. scaleBoxes[index].computeWorldMatrix();
  96832. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  96833. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  96834. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  96835. }
  96836. else {
  96837. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  96838. }
  96839. }
  96840. }
  96841. }
  96842. }
  96843. if (this.attachedMesh) {
  96844. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  96845. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  96846. }
  96847. };
  96848. /**
  96849. * Enables rotation on the specified axis and disables rotation on the others
  96850. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  96851. */
  96852. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  96853. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  96854. if (i < 4) {
  96855. m.setEnabled(axis.indexOf("x") != -1);
  96856. }
  96857. else if (i < 8) {
  96858. m.setEnabled(axis.indexOf("y") != -1);
  96859. }
  96860. else {
  96861. m.setEnabled(axis.indexOf("z") != -1);
  96862. }
  96863. });
  96864. };
  96865. /**
  96866. * Disposes of the gizmo
  96867. */
  96868. BoundingBoxGizmo.prototype.dispose = function () {
  96869. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96870. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  96871. this._lineBoundingBox.dispose();
  96872. this._rotateSpheresParent.dispose();
  96873. this._scaleBoxesParent.dispose();
  96874. _super.prototype.dispose.call(this);
  96875. };
  96876. /**
  96877. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  96878. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  96879. * @returns the bounding box mesh with the passed in mesh as a child
  96880. */
  96881. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  96882. var makeNotPickable = function (root) {
  96883. root.isPickable = false;
  96884. root.getChildMeshes().forEach(function (c) {
  96885. makeNotPickable(c);
  96886. });
  96887. };
  96888. makeNotPickable(mesh);
  96889. // Reset position to get boudning box from origin with no rotation
  96890. if (!mesh.rotationQuaternion) {
  96891. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  96892. }
  96893. var oldPos = mesh.position.clone();
  96894. var oldRot = mesh.rotationQuaternion.clone();
  96895. mesh.rotationQuaternion.set(0, 0, 0, 1);
  96896. mesh.position.set(0, 0, 0);
  96897. // Update bounding dimensions/positions
  96898. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  96899. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  96900. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  96901. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  96902. // Restore original positions
  96903. mesh.addChild(box);
  96904. mesh.rotationQuaternion.copyFrom(oldRot);
  96905. mesh.position.copyFrom(oldPos);
  96906. // Reverse parenting
  96907. mesh.removeChild(box);
  96908. box.addChild(mesh);
  96909. box.visibility = 0;
  96910. return box;
  96911. };
  96912. /**
  96913. * CustomMeshes are not supported by this gizmo
  96914. * @param mesh The mesh to replace the default mesh of the gizmo
  96915. */
  96916. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  96917. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  96918. };
  96919. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  96920. // store/remove pivot point should only be applied during their outermost calls
  96921. BoundingBoxGizmo._PivotCached = 0;
  96922. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  96923. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  96924. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  96925. return BoundingBoxGizmo;
  96926. }(BABYLON.Gizmo));
  96927. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  96928. })(BABYLON || (BABYLON = {}));
  96929. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  96930. var BABYLON;
  96931. (function (BABYLON) {
  96932. /**
  96933. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  96934. */
  96935. var GizmoManager = /** @class */ (function () {
  96936. /**
  96937. * Instatiates a gizmo manager
  96938. * @param scene the scene to overlay the gizmos on top of
  96939. */
  96940. function GizmoManager(scene) {
  96941. var _this = this;
  96942. this.scene = scene;
  96943. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  96944. this._pointerObserver = null;
  96945. this._attachedMesh = null;
  96946. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  96947. /**
  96948. * When bounding box gizmo is enabled, this can be used to track drag/end events
  96949. */
  96950. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  96951. /**
  96952. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  96953. */
  96954. this.attachableMeshes = null;
  96955. /**
  96956. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  96957. */
  96958. this.usePointerToAttachGizmos = true;
  96959. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  96960. // Instatiate/dispose gizmos based on pointer actions
  96961. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  96962. if (!_this.usePointerToAttachGizmos) {
  96963. return;
  96964. }
  96965. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96966. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  96967. var node = pointerInfo.pickInfo.pickedMesh;
  96968. if (_this.attachableMeshes == null) {
  96969. // Attach to the most parent node
  96970. while (node && node.parent != null) {
  96971. node = node.parent;
  96972. }
  96973. }
  96974. else {
  96975. // Attach to the parent node that is an attachableMesh
  96976. var found = false;
  96977. _this.attachableMeshes.forEach(function (mesh) {
  96978. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  96979. node = mesh;
  96980. found = true;
  96981. }
  96982. });
  96983. if (!found) {
  96984. node = null;
  96985. }
  96986. }
  96987. if (node instanceof BABYLON.AbstractMesh) {
  96988. _this.attachToMesh(node);
  96989. }
  96990. else {
  96991. _this.attachToMesh(null);
  96992. }
  96993. }
  96994. else {
  96995. _this.attachToMesh(null);
  96996. }
  96997. }
  96998. });
  96999. }
  97000. /**
  97001. * Attaches a set of gizmos to the specified mesh
  97002. * @param mesh The mesh the gizmo's should be attached to
  97003. */
  97004. GizmoManager.prototype.attachToMesh = function (mesh) {
  97005. if (this._attachedMesh) {
  97006. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  97007. }
  97008. this._attachedMesh = mesh;
  97009. for (var key in this.gizmos) {
  97010. var gizmo = (this.gizmos[key]);
  97011. if (gizmo && this._gizmosEnabled[key]) {
  97012. gizmo.attachedMesh = mesh;
  97013. }
  97014. }
  97015. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  97016. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  97017. }
  97018. };
  97019. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  97020. get: function () {
  97021. return this._gizmosEnabled.positionGizmo;
  97022. },
  97023. /**
  97024. * If the position gizmo is enabled
  97025. */
  97026. set: function (value) {
  97027. if (value) {
  97028. if (!this.gizmos.positionGizmo) {
  97029. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  97030. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97031. }
  97032. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  97033. }
  97034. else if (this.gizmos.positionGizmo) {
  97035. this.gizmos.positionGizmo.attachedMesh = null;
  97036. }
  97037. this._gizmosEnabled.positionGizmo = value;
  97038. },
  97039. enumerable: true,
  97040. configurable: true
  97041. });
  97042. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  97043. get: function () {
  97044. return this._gizmosEnabled.rotationGizmo;
  97045. },
  97046. /**
  97047. * If the rotation gizmo is enabled
  97048. */
  97049. set: function (value) {
  97050. if (value) {
  97051. if (!this.gizmos.rotationGizmo) {
  97052. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  97053. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97054. }
  97055. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  97056. }
  97057. else if (this.gizmos.rotationGizmo) {
  97058. this.gizmos.rotationGizmo.attachedMesh = null;
  97059. }
  97060. this._gizmosEnabled.rotationGizmo = value;
  97061. },
  97062. enumerable: true,
  97063. configurable: true
  97064. });
  97065. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  97066. get: function () {
  97067. return this._gizmosEnabled.scaleGizmo;
  97068. },
  97069. /**
  97070. * If the scale gizmo is enabled
  97071. */
  97072. set: function (value) {
  97073. if (value) {
  97074. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  97075. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  97076. }
  97077. else if (this.gizmos.scaleGizmo) {
  97078. this.gizmos.scaleGizmo.attachedMesh = null;
  97079. }
  97080. this._gizmosEnabled.scaleGizmo = value;
  97081. },
  97082. enumerable: true,
  97083. configurable: true
  97084. });
  97085. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  97086. get: function () {
  97087. return this._gizmosEnabled.boundingBoxGizmo;
  97088. },
  97089. /**
  97090. * If the boundingBox gizmo is enabled
  97091. */
  97092. set: function (value) {
  97093. if (value) {
  97094. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  97095. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  97096. if (this._attachedMesh) {
  97097. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  97098. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  97099. }
  97100. }
  97101. else if (this.gizmos.boundingBoxGizmo) {
  97102. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  97103. }
  97104. this._gizmosEnabled.boundingBoxGizmo = value;
  97105. },
  97106. enumerable: true,
  97107. configurable: true
  97108. });
  97109. /**
  97110. * Disposes of the gizmo manager
  97111. */
  97112. GizmoManager.prototype.dispose = function () {
  97113. this.scene.onPointerObservable.remove(this._pointerObserver);
  97114. for (var key in this.gizmos) {
  97115. var gizmo = (this.gizmos[key]);
  97116. if (gizmo) {
  97117. gizmo.dispose();
  97118. }
  97119. }
  97120. this.boundingBoxDragBehavior.detach();
  97121. };
  97122. return GizmoManager;
  97123. }());
  97124. BABYLON.GizmoManager = GizmoManager;
  97125. })(BABYLON || (BABYLON = {}));
  97126. //# sourceMappingURL=babylon.gizmoManager.js.map
  97127. var BABYLON;
  97128. (function (BABYLON) {
  97129. /**
  97130. * Defines a target to use with MorphTargetManager
  97131. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  97132. */
  97133. var MorphTarget = /** @class */ (function () {
  97134. /**
  97135. * Creates a new MorphTarget
  97136. * @param name defines the name of the target
  97137. * @param influence defines the influence to use
  97138. */
  97139. function MorphTarget(
  97140. /** defines the name of the target */
  97141. name, influence, scene) {
  97142. if (influence === void 0) { influence = 0; }
  97143. if (scene === void 0) { scene = null; }
  97144. this.name = name;
  97145. /**
  97146. * Gets or sets the list of animations
  97147. */
  97148. this.animations = new Array();
  97149. this._positions = null;
  97150. this._normals = null;
  97151. this._tangents = null;
  97152. /**
  97153. * Observable raised when the influence changes
  97154. */
  97155. this.onInfluenceChanged = new BABYLON.Observable();
  97156. this._animationPropertiesOverride = null;
  97157. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97158. this.influence = influence;
  97159. }
  97160. Object.defineProperty(MorphTarget.prototype, "influence", {
  97161. /**
  97162. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  97163. */
  97164. get: function () {
  97165. return this._influence;
  97166. },
  97167. set: function (influence) {
  97168. if (this._influence === influence) {
  97169. return;
  97170. }
  97171. var previous = this._influence;
  97172. this._influence = influence;
  97173. if (this.onInfluenceChanged.hasObservers) {
  97174. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  97175. }
  97176. },
  97177. enumerable: true,
  97178. configurable: true
  97179. });
  97180. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  97181. /**
  97182. * Gets or sets the animation properties override
  97183. */
  97184. get: function () {
  97185. if (!this._animationPropertiesOverride && this._scene) {
  97186. return this._scene.animationPropertiesOverride;
  97187. }
  97188. return this._animationPropertiesOverride;
  97189. },
  97190. set: function (value) {
  97191. this._animationPropertiesOverride = value;
  97192. },
  97193. enumerable: true,
  97194. configurable: true
  97195. });
  97196. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  97197. /**
  97198. * Gets a boolean defining if the target contains position data
  97199. */
  97200. get: function () {
  97201. return !!this._positions;
  97202. },
  97203. enumerable: true,
  97204. configurable: true
  97205. });
  97206. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  97207. /**
  97208. * Gets a boolean defining if the target contains normal data
  97209. */
  97210. get: function () {
  97211. return !!this._normals;
  97212. },
  97213. enumerable: true,
  97214. configurable: true
  97215. });
  97216. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  97217. /**
  97218. * Gets a boolean defining if the target contains tangent data
  97219. */
  97220. get: function () {
  97221. return !!this._tangents;
  97222. },
  97223. enumerable: true,
  97224. configurable: true
  97225. });
  97226. /**
  97227. * Affects position data to this target
  97228. * @param data defines the position data to use
  97229. */
  97230. MorphTarget.prototype.setPositions = function (data) {
  97231. this._positions = data;
  97232. };
  97233. /**
  97234. * Gets the position data stored in this target
  97235. * @returns a FloatArray containing the position data (or null if not present)
  97236. */
  97237. MorphTarget.prototype.getPositions = function () {
  97238. return this._positions;
  97239. };
  97240. /**
  97241. * Affects normal data to this target
  97242. * @param data defines the normal data to use
  97243. */
  97244. MorphTarget.prototype.setNormals = function (data) {
  97245. this._normals = data;
  97246. };
  97247. /**
  97248. * Gets the normal data stored in this target
  97249. * @returns a FloatArray containing the normal data (or null if not present)
  97250. */
  97251. MorphTarget.prototype.getNormals = function () {
  97252. return this._normals;
  97253. };
  97254. /**
  97255. * Affects tangent data to this target
  97256. * @param data defines the tangent data to use
  97257. */
  97258. MorphTarget.prototype.setTangents = function (data) {
  97259. this._tangents = data;
  97260. };
  97261. /**
  97262. * Gets the tangent data stored in this target
  97263. * @returns a FloatArray containing the tangent data (or null if not present)
  97264. */
  97265. MorphTarget.prototype.getTangents = function () {
  97266. return this._tangents;
  97267. };
  97268. /**
  97269. * Serializes the current target into a Serialization object
  97270. * @returns the serialized object
  97271. */
  97272. MorphTarget.prototype.serialize = function () {
  97273. var serializationObject = {};
  97274. serializationObject.name = this.name;
  97275. serializationObject.influence = this.influence;
  97276. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  97277. if (this.hasNormals) {
  97278. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  97279. }
  97280. if (this.hasTangents) {
  97281. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  97282. }
  97283. // Animations
  97284. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  97285. return serializationObject;
  97286. };
  97287. // Statics
  97288. /**
  97289. * Creates a new target from serialized data
  97290. * @param serializationObject defines the serialized data to use
  97291. * @returns a new MorphTarget
  97292. */
  97293. MorphTarget.Parse = function (serializationObject) {
  97294. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  97295. result.setPositions(serializationObject.positions);
  97296. if (serializationObject.normals) {
  97297. result.setNormals(serializationObject.normals);
  97298. }
  97299. if (serializationObject.tangents) {
  97300. result.setTangents(serializationObject.tangents);
  97301. }
  97302. // Animations
  97303. if (serializationObject.animations) {
  97304. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  97305. var parsedAnimation = serializationObject.animations[animationIndex];
  97306. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  97307. }
  97308. }
  97309. return result;
  97310. };
  97311. /**
  97312. * Creates a MorphTarget from mesh data
  97313. * @param mesh defines the source mesh
  97314. * @param name defines the name to use for the new target
  97315. * @param influence defines the influence to attach to the target
  97316. * @returns a new MorphTarget
  97317. */
  97318. MorphTarget.FromMesh = function (mesh, name, influence) {
  97319. if (!name) {
  97320. name = mesh.name;
  97321. }
  97322. var result = new MorphTarget(name, influence, mesh.getScene());
  97323. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  97324. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97325. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  97326. }
  97327. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  97328. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  97329. }
  97330. return result;
  97331. };
  97332. return MorphTarget;
  97333. }());
  97334. BABYLON.MorphTarget = MorphTarget;
  97335. })(BABYLON || (BABYLON = {}));
  97336. //# sourceMappingURL=babylon.morphTarget.js.map
  97337. var BABYLON;
  97338. (function (BABYLON) {
  97339. /**
  97340. * This class is used to deform meshes using morphing between different targets
  97341. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  97342. */
  97343. var MorphTargetManager = /** @class */ (function () {
  97344. /**
  97345. * Creates a new MorphTargetManager
  97346. * @param scene defines the current scene
  97347. */
  97348. function MorphTargetManager(scene) {
  97349. if (scene === void 0) { scene = null; }
  97350. this._targets = new Array();
  97351. this._targetObservable = new Array();
  97352. this._activeTargets = new BABYLON.SmartArray(16);
  97353. this._supportsNormals = false;
  97354. this._supportsTangents = false;
  97355. this._vertexCount = 0;
  97356. this._uniqueId = 0;
  97357. this._tempInfluences = new Array();
  97358. if (!scene) {
  97359. scene = BABYLON.Engine.LastCreatedScene;
  97360. }
  97361. this._scene = scene;
  97362. if (this._scene) {
  97363. this._scene.morphTargetManagers.push(this);
  97364. this._uniqueId = this._scene.getUniqueId();
  97365. }
  97366. }
  97367. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  97368. /**
  97369. * Gets the unique ID of this manager
  97370. */
  97371. get: function () {
  97372. return this._uniqueId;
  97373. },
  97374. enumerable: true,
  97375. configurable: true
  97376. });
  97377. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  97378. /**
  97379. * Gets the number of vertices handled by this manager
  97380. */
  97381. get: function () {
  97382. return this._vertexCount;
  97383. },
  97384. enumerable: true,
  97385. configurable: true
  97386. });
  97387. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  97388. /**
  97389. * Gets a boolean indicating if this manager supports morphing of normals
  97390. */
  97391. get: function () {
  97392. return this._supportsNormals;
  97393. },
  97394. enumerable: true,
  97395. configurable: true
  97396. });
  97397. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  97398. /**
  97399. * Gets a boolean indicating if this manager supports morphing of tangents
  97400. */
  97401. get: function () {
  97402. return this._supportsTangents;
  97403. },
  97404. enumerable: true,
  97405. configurable: true
  97406. });
  97407. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  97408. /**
  97409. * Gets the number of targets stored in this manager
  97410. */
  97411. get: function () {
  97412. return this._targets.length;
  97413. },
  97414. enumerable: true,
  97415. configurable: true
  97416. });
  97417. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  97418. /**
  97419. * Gets the number of influencers (ie. the number of targets with influences > 0)
  97420. */
  97421. get: function () {
  97422. return this._activeTargets.length;
  97423. },
  97424. enumerable: true,
  97425. configurable: true
  97426. });
  97427. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  97428. /**
  97429. * Gets the list of influences (one per target)
  97430. */
  97431. get: function () {
  97432. return this._influences;
  97433. },
  97434. enumerable: true,
  97435. configurable: true
  97436. });
  97437. /**
  97438. * Gets the active target at specified index. An active target is a target with an influence > 0
  97439. * @param index defines the index to check
  97440. * @returns the requested target
  97441. */
  97442. MorphTargetManager.prototype.getActiveTarget = function (index) {
  97443. return this._activeTargets.data[index];
  97444. };
  97445. /**
  97446. * Gets the target at specified index
  97447. * @param index defines the index to check
  97448. * @returns the requested target
  97449. */
  97450. MorphTargetManager.prototype.getTarget = function (index) {
  97451. return this._targets[index];
  97452. };
  97453. /**
  97454. * Add a new target to this manager
  97455. * @param target defines the target to add
  97456. */
  97457. MorphTargetManager.prototype.addTarget = function (target) {
  97458. var _this = this;
  97459. this._targets.push(target);
  97460. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  97461. _this._syncActiveTargets(needUpdate);
  97462. }));
  97463. this._syncActiveTargets(true);
  97464. };
  97465. /**
  97466. * Removes a target from the manager
  97467. * @param target defines the target to remove
  97468. */
  97469. MorphTargetManager.prototype.removeTarget = function (target) {
  97470. var index = this._targets.indexOf(target);
  97471. if (index >= 0) {
  97472. this._targets.splice(index, 1);
  97473. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  97474. this._syncActiveTargets(true);
  97475. }
  97476. };
  97477. /**
  97478. * Serializes the current manager into a Serialization object
  97479. * @returns the serialized object
  97480. */
  97481. MorphTargetManager.prototype.serialize = function () {
  97482. var serializationObject = {};
  97483. serializationObject.id = this.uniqueId;
  97484. serializationObject.targets = [];
  97485. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  97486. var target = _a[_i];
  97487. serializationObject.targets.push(target.serialize());
  97488. }
  97489. return serializationObject;
  97490. };
  97491. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  97492. var influenceCount = 0;
  97493. this._activeTargets.reset();
  97494. this._supportsNormals = true;
  97495. this._supportsTangents = true;
  97496. this._vertexCount = 0;
  97497. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  97498. var target = _a[_i];
  97499. this._activeTargets.push(target);
  97500. this._tempInfluences[influenceCount++] = target.influence;
  97501. var positions = target.getPositions();
  97502. if (positions) {
  97503. this._supportsNormals = this._supportsNormals && target.hasNormals;
  97504. this._supportsTangents = this._supportsTangents && target.hasTangents;
  97505. var vertexCount = positions.length / 3;
  97506. if (this._vertexCount === 0) {
  97507. this._vertexCount = vertexCount;
  97508. }
  97509. else if (this._vertexCount !== vertexCount) {
  97510. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  97511. return;
  97512. }
  97513. }
  97514. }
  97515. if (!this._influences || this._influences.length !== influenceCount) {
  97516. this._influences = new Float32Array(influenceCount);
  97517. }
  97518. for (var index = 0; index < influenceCount; index++) {
  97519. this._influences[index] = this._tempInfluences[index];
  97520. }
  97521. if (needUpdate) {
  97522. this.synchronize();
  97523. }
  97524. };
  97525. /**
  97526. * Syncrhonize the targets with all the meshes using this morph target manager
  97527. */
  97528. MorphTargetManager.prototype.synchronize = function () {
  97529. if (!this._scene) {
  97530. return;
  97531. }
  97532. // Flag meshes as dirty to resync with the active targets
  97533. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  97534. var mesh = _a[_i];
  97535. if (mesh.morphTargetManager === this) {
  97536. mesh._syncGeometryWithMorphTargetManager();
  97537. }
  97538. }
  97539. };
  97540. // Statics
  97541. /**
  97542. * Creates a new MorphTargetManager from serialized data
  97543. * @param serializationObject defines the serialized data
  97544. * @param scene defines the hosting scene
  97545. * @returns the new MorphTargetManager
  97546. */
  97547. MorphTargetManager.Parse = function (serializationObject, scene) {
  97548. var result = new MorphTargetManager(scene);
  97549. result._uniqueId = serializationObject.id;
  97550. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  97551. var targetData = _a[_i];
  97552. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  97553. }
  97554. return result;
  97555. };
  97556. return MorphTargetManager;
  97557. }());
  97558. BABYLON.MorphTargetManager = MorphTargetManager;
  97559. })(BABYLON || (BABYLON = {}));
  97560. //# sourceMappingURL=babylon.morphTargetManager.js.map
  97561. var BABYLON;
  97562. (function (BABYLON) {
  97563. var Octree = /** @class */ (function () {
  97564. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  97565. if (maxDepth === void 0) { maxDepth = 2; }
  97566. this.maxDepth = maxDepth;
  97567. this.dynamicContent = new Array();
  97568. this._maxBlockCapacity = maxBlockCapacity || 64;
  97569. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  97570. this._creationFunc = creationFunc;
  97571. }
  97572. // Methods
  97573. Octree.prototype.update = function (worldMin, worldMax, entries) {
  97574. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  97575. };
  97576. Octree.prototype.addMesh = function (entry) {
  97577. for (var index = 0; index < this.blocks.length; index++) {
  97578. var block = this.blocks[index];
  97579. block.addEntry(entry);
  97580. }
  97581. };
  97582. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  97583. this._selectionContent.reset();
  97584. for (var index = 0; index < this.blocks.length; index++) {
  97585. var block = this.blocks[index];
  97586. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  97587. }
  97588. if (allowDuplicate) {
  97589. this._selectionContent.concat(this.dynamicContent);
  97590. }
  97591. else {
  97592. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97593. }
  97594. return this._selectionContent;
  97595. };
  97596. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  97597. this._selectionContent.reset();
  97598. for (var index = 0; index < this.blocks.length; index++) {
  97599. var block = this.blocks[index];
  97600. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  97601. }
  97602. if (allowDuplicate) {
  97603. this._selectionContent.concat(this.dynamicContent);
  97604. }
  97605. else {
  97606. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97607. }
  97608. return this._selectionContent;
  97609. };
  97610. Octree.prototype.intersectsRay = function (ray) {
  97611. this._selectionContent.reset();
  97612. for (var index = 0; index < this.blocks.length; index++) {
  97613. var block = this.blocks[index];
  97614. block.intersectsRay(ray, this._selectionContent);
  97615. }
  97616. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97617. return this._selectionContent;
  97618. };
  97619. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  97620. target.blocks = new Array();
  97621. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  97622. // Segmenting space
  97623. for (var x = 0; x < 2; x++) {
  97624. for (var y = 0; y < 2; y++) {
  97625. for (var z = 0; z < 2; z++) {
  97626. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  97627. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  97628. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  97629. block.addEntries(entries);
  97630. target.blocks.push(block);
  97631. }
  97632. }
  97633. }
  97634. };
  97635. Octree.CreationFuncForMeshes = function (entry, block) {
  97636. var boundingInfo = entry.getBoundingInfo();
  97637. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  97638. block.entries.push(entry);
  97639. }
  97640. };
  97641. Octree.CreationFuncForSubMeshes = function (entry, block) {
  97642. var boundingInfo = entry.getBoundingInfo();
  97643. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  97644. block.entries.push(entry);
  97645. }
  97646. };
  97647. return Octree;
  97648. }());
  97649. BABYLON.Octree = Octree;
  97650. })(BABYLON || (BABYLON = {}));
  97651. //# sourceMappingURL=babylon.octree.js.map
  97652. var BABYLON;
  97653. (function (BABYLON) {
  97654. var OctreeBlock = /** @class */ (function () {
  97655. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  97656. this.entries = new Array();
  97657. this._boundingVectors = new Array();
  97658. this._capacity = capacity;
  97659. this._depth = depth;
  97660. this._maxDepth = maxDepth;
  97661. this._creationFunc = creationFunc;
  97662. this._minPoint = minPoint;
  97663. this._maxPoint = maxPoint;
  97664. this._boundingVectors.push(minPoint.clone());
  97665. this._boundingVectors.push(maxPoint.clone());
  97666. this._boundingVectors.push(minPoint.clone());
  97667. this._boundingVectors[2].x = maxPoint.x;
  97668. this._boundingVectors.push(minPoint.clone());
  97669. this._boundingVectors[3].y = maxPoint.y;
  97670. this._boundingVectors.push(minPoint.clone());
  97671. this._boundingVectors[4].z = maxPoint.z;
  97672. this._boundingVectors.push(maxPoint.clone());
  97673. this._boundingVectors[5].z = minPoint.z;
  97674. this._boundingVectors.push(maxPoint.clone());
  97675. this._boundingVectors[6].x = minPoint.x;
  97676. this._boundingVectors.push(maxPoint.clone());
  97677. this._boundingVectors[7].y = minPoint.y;
  97678. }
  97679. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  97680. // Property
  97681. get: function () {
  97682. return this._capacity;
  97683. },
  97684. enumerable: true,
  97685. configurable: true
  97686. });
  97687. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  97688. get: function () {
  97689. return this._minPoint;
  97690. },
  97691. enumerable: true,
  97692. configurable: true
  97693. });
  97694. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  97695. get: function () {
  97696. return this._maxPoint;
  97697. },
  97698. enumerable: true,
  97699. configurable: true
  97700. });
  97701. // Methods
  97702. OctreeBlock.prototype.addEntry = function (entry) {
  97703. if (this.blocks) {
  97704. for (var index = 0; index < this.blocks.length; index++) {
  97705. var block = this.blocks[index];
  97706. block.addEntry(entry);
  97707. }
  97708. return;
  97709. }
  97710. this._creationFunc(entry, this);
  97711. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  97712. this.createInnerBlocks();
  97713. }
  97714. };
  97715. OctreeBlock.prototype.addEntries = function (entries) {
  97716. for (var index = 0; index < entries.length; index++) {
  97717. var mesh = entries[index];
  97718. this.addEntry(mesh);
  97719. }
  97720. };
  97721. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  97722. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  97723. if (this.blocks) {
  97724. for (var index = 0; index < this.blocks.length; index++) {
  97725. var block = this.blocks[index];
  97726. block.select(frustumPlanes, selection, allowDuplicate);
  97727. }
  97728. return;
  97729. }
  97730. if (allowDuplicate) {
  97731. selection.concat(this.entries);
  97732. }
  97733. else {
  97734. selection.concatWithNoDuplicate(this.entries);
  97735. }
  97736. }
  97737. };
  97738. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  97739. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  97740. if (this.blocks) {
  97741. for (var index = 0; index < this.blocks.length; index++) {
  97742. var block = this.blocks[index];
  97743. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  97744. }
  97745. return;
  97746. }
  97747. if (allowDuplicate) {
  97748. selection.concat(this.entries);
  97749. }
  97750. else {
  97751. selection.concatWithNoDuplicate(this.entries);
  97752. }
  97753. }
  97754. };
  97755. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  97756. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  97757. if (this.blocks) {
  97758. for (var index = 0; index < this.blocks.length; index++) {
  97759. var block = this.blocks[index];
  97760. block.intersectsRay(ray, selection);
  97761. }
  97762. return;
  97763. }
  97764. selection.concatWithNoDuplicate(this.entries);
  97765. }
  97766. };
  97767. OctreeBlock.prototype.createInnerBlocks = function () {
  97768. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  97769. };
  97770. return OctreeBlock;
  97771. }());
  97772. BABYLON.OctreeBlock = OctreeBlock;
  97773. })(BABYLON || (BABYLON = {}));
  97774. //# sourceMappingURL=babylon.octreeBlock.js.map
  97775. var BABYLON;
  97776. (function (BABYLON) {
  97777. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  97778. if (maxCapacity === void 0) { maxCapacity = 64; }
  97779. if (maxDepth === void 0) { maxDepth = 2; }
  97780. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  97781. if (!component) {
  97782. component = new OctreeSceneComponent(this);
  97783. this._addComponent(component);
  97784. }
  97785. if (!this._selectionOctree) {
  97786. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  97787. }
  97788. var worldExtends = this.getWorldExtends();
  97789. // Update octree
  97790. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  97791. return this._selectionOctree;
  97792. };
  97793. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  97794. get: function () {
  97795. return this._selectionOctree;
  97796. },
  97797. enumerable: true,
  97798. configurable: true
  97799. });
  97800. /**
  97801. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  97802. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  97803. * @param maxCapacity defines the maximum size of each block (64 by default)
  97804. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  97805. * @returns the new octree
  97806. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  97807. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  97808. */
  97809. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  97810. if (maxCapacity === void 0) { maxCapacity = 64; }
  97811. if (maxDepth === void 0) { maxDepth = 2; }
  97812. var scene = this.getScene();
  97813. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  97814. if (!component) {
  97815. component = new OctreeSceneComponent(scene);
  97816. scene._addComponent(component);
  97817. }
  97818. if (!this._submeshesOctree) {
  97819. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  97820. }
  97821. this.computeWorldMatrix(true);
  97822. var boundingInfo = this.getBoundingInfo();
  97823. // Update octree
  97824. var bbox = boundingInfo.boundingBox;
  97825. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  97826. return this._submeshesOctree;
  97827. };
  97828. /**
  97829. * Defines the octree scene component responsible to manage any octrees
  97830. * in a given scene.
  97831. */
  97832. var OctreeSceneComponent = /** @class */ (function () {
  97833. /**
  97834. * Creates a new instance of the component for the given scene
  97835. * @param scene Defines the scene to register the component in
  97836. */
  97837. function OctreeSceneComponent(scene) {
  97838. /**
  97839. * The component name helpfull to identify the component in the list of scene components.
  97840. */
  97841. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  97842. /**
  97843. * Indicates if the meshes have been checked to make sure they are isEnabled()
  97844. */
  97845. this.checksIsEnabled = true;
  97846. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  97847. this.scene = scene;
  97848. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  97849. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  97850. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  97851. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  97852. }
  97853. /**
  97854. * Registers the component in a given scene
  97855. */
  97856. OctreeSceneComponent.prototype.register = function () {
  97857. var _this = this;
  97858. this.scene.onMeshRemovedObservable.add(function (mesh) {
  97859. var sceneOctree = _this.scene.selectionOctree;
  97860. if (sceneOctree !== undefined && sceneOctree !== null) {
  97861. var index = sceneOctree.dynamicContent.indexOf(mesh);
  97862. if (index !== -1) {
  97863. sceneOctree.dynamicContent.splice(index, 1);
  97864. }
  97865. }
  97866. });
  97867. this.scene.onMeshImportedObservable.add(function (mesh) {
  97868. var sceneOctree = _this.scene.selectionOctree;
  97869. if (sceneOctree !== undefined && sceneOctree !== null) {
  97870. sceneOctree.addMesh(mesh);
  97871. }
  97872. });
  97873. };
  97874. /**
  97875. * Return the list of active meshes
  97876. * @returns the list of active meshes
  97877. */
  97878. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  97879. if (this.scene._selectionOctree) {
  97880. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  97881. return selection;
  97882. }
  97883. return this.scene._getDefaultMeshCandidates();
  97884. };
  97885. /**
  97886. * Return the list of active sub meshes
  97887. * @param mesh The mesh to get the candidates sub meshes from
  97888. * @returns the list of active sub meshes
  97889. */
  97890. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  97891. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  97892. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  97893. return intersections;
  97894. }
  97895. return this.scene._getDefaultSubMeshCandidates(mesh);
  97896. };
  97897. /**
  97898. * Return the list of sub meshes intersecting with a given local ray
  97899. * @param mesh defines the mesh to find the submesh for
  97900. * @param localRay defines the ray in local space
  97901. * @returns the list of intersecting sub meshes
  97902. */
  97903. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  97904. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  97905. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  97906. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  97907. return intersections;
  97908. }
  97909. return this.scene._getDefaultSubMeshCandidates(mesh);
  97910. };
  97911. /**
  97912. * Return the list of sub meshes colliding with a collider
  97913. * @param mesh defines the mesh to find the submesh for
  97914. * @param collider defines the collider to evaluate the collision against
  97915. * @returns the list of colliding sub meshes
  97916. */
  97917. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  97918. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  97919. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  97920. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  97921. return intersections;
  97922. }
  97923. return this.scene._getDefaultSubMeshCandidates(mesh);
  97924. };
  97925. /**
  97926. * Rebuilds the elements related to this component in case of
  97927. * context lost for instance.
  97928. */
  97929. OctreeSceneComponent.prototype.rebuild = function () {
  97930. // Nothing to do here.
  97931. };
  97932. /**
  97933. * Disposes the component and the associated ressources.
  97934. */
  97935. OctreeSceneComponent.prototype.dispose = function () {
  97936. // Nothing to do here.
  97937. };
  97938. return OctreeSceneComponent;
  97939. }());
  97940. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  97941. })(BABYLON || (BABYLON = {}));
  97942. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  97943. var BABYLON;
  97944. (function (BABYLON) {
  97945. /**
  97946. * Postprocess used to generate anaglyphic rendering
  97947. */
  97948. var AnaglyphPostProcess = /** @class */ (function (_super) {
  97949. __extends(AnaglyphPostProcess, _super);
  97950. /**
  97951. * Creates a new AnaglyphPostProcess
  97952. * @param name defines postprocess name
  97953. * @param options defines creation options or target ratio scale
  97954. * @param rigCameras defines cameras using this postprocess
  97955. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  97956. * @param engine defines hosting engine
  97957. * @param reusable defines if the postprocess will be reused multiple times per frame
  97958. */
  97959. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  97960. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  97961. _this._passedProcess = rigCameras[0]._rigPostProcess;
  97962. _this.onApplyObservable.add(function (effect) {
  97963. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  97964. });
  97965. return _this;
  97966. }
  97967. return AnaglyphPostProcess;
  97968. }(BABYLON.PostProcess));
  97969. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  97970. })(BABYLON || (BABYLON = {}));
  97971. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  97972. var BABYLON;
  97973. (function (BABYLON) {
  97974. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  97975. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  97976. });
  97977. /**
  97978. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  97979. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  97980. */
  97981. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  97982. __extends(AnaglyphArcRotateCamera, _super);
  97983. /**
  97984. * Creates a new AnaglyphArcRotateCamera
  97985. * @param name defines camera name
  97986. * @param alpha defines alpha angle (in radians)
  97987. * @param beta defines beta angle (in radians)
  97988. * @param radius defines radius
  97989. * @param target defines camera target
  97990. * @param interaxialDistance defines distance between each color axis
  97991. * @param scene defines the hosting scene
  97992. */
  97993. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  97994. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97995. _this.interaxialDistance = interaxialDistance;
  97996. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  97997. return _this;
  97998. }
  97999. /**
  98000. * Gets camera class name
  98001. * @returns AnaglyphArcRotateCamera
  98002. */
  98003. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  98004. return "AnaglyphArcRotateCamera";
  98005. };
  98006. return AnaglyphArcRotateCamera;
  98007. }(BABYLON.ArcRotateCamera));
  98008. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  98009. })(BABYLON || (BABYLON = {}));
  98010. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  98011. var BABYLON;
  98012. (function (BABYLON) {
  98013. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  98014. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98015. });
  98016. /**
  98017. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  98018. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98019. */
  98020. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  98021. __extends(AnaglyphFreeCamera, _super);
  98022. /**
  98023. * Creates a new AnaglyphFreeCamera
  98024. * @param name defines camera name
  98025. * @param position defines initial position
  98026. * @param interaxialDistance defines distance between each color axis
  98027. * @param scene defines the hosting scene
  98028. */
  98029. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  98030. var _this = _super.call(this, name, position, scene) || this;
  98031. _this.interaxialDistance = interaxialDistance;
  98032. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98033. return _this;
  98034. }
  98035. /**
  98036. * Gets camera class name
  98037. * @returns AnaglyphFreeCamera
  98038. */
  98039. AnaglyphFreeCamera.prototype.getClassName = function () {
  98040. return "AnaglyphFreeCamera";
  98041. };
  98042. return AnaglyphFreeCamera;
  98043. }(BABYLON.FreeCamera));
  98044. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  98045. })(BABYLON || (BABYLON = {}));
  98046. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  98047. var BABYLON;
  98048. (function (BABYLON) {
  98049. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  98050. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98051. });
  98052. /**
  98053. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  98054. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98055. */
  98056. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  98057. __extends(AnaglyphGamepadCamera, _super);
  98058. /**
  98059. * Creates a new AnaglyphGamepadCamera
  98060. * @param name defines camera name
  98061. * @param position defines initial position
  98062. * @param interaxialDistance defines distance between each color axis
  98063. * @param scene defines the hosting scene
  98064. */
  98065. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  98066. var _this = _super.call(this, name, position, scene) || this;
  98067. _this.interaxialDistance = interaxialDistance;
  98068. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98069. return _this;
  98070. }
  98071. /**
  98072. * Gets camera class name
  98073. * @returns AnaglyphGamepadCamera
  98074. */
  98075. AnaglyphGamepadCamera.prototype.getClassName = function () {
  98076. return "AnaglyphGamepadCamera";
  98077. };
  98078. return AnaglyphGamepadCamera;
  98079. }(BABYLON.GamepadCamera));
  98080. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  98081. })(BABYLON || (BABYLON = {}));
  98082. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  98083. var BABYLON;
  98084. (function (BABYLON) {
  98085. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  98086. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98087. });
  98088. /**
  98089. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  98090. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98091. */
  98092. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  98093. __extends(AnaglyphUniversalCamera, _super);
  98094. /**
  98095. * Creates a new AnaglyphUniversalCamera
  98096. * @param name defines camera name
  98097. * @param position defines initial position
  98098. * @param interaxialDistance defines distance between each color axis
  98099. * @param scene defines the hosting scene
  98100. */
  98101. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  98102. var _this = _super.call(this, name, position, scene) || this;
  98103. _this.interaxialDistance = interaxialDistance;
  98104. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98105. return _this;
  98106. }
  98107. /**
  98108. * Gets camera class name
  98109. * @returns AnaglyphUniversalCamera
  98110. */
  98111. AnaglyphUniversalCamera.prototype.getClassName = function () {
  98112. return "AnaglyphUniversalCamera";
  98113. };
  98114. return AnaglyphUniversalCamera;
  98115. }(BABYLON.UniversalCamera));
  98116. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  98117. })(BABYLON || (BABYLON = {}));
  98118. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  98119. var BABYLON;
  98120. (function (BABYLON) {
  98121. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  98122. __extends(StereoscopicInterlacePostProcess, _super);
  98123. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  98124. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  98125. _this._passedProcess = rigCameras[0]._rigPostProcess;
  98126. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  98127. _this.onSizeChangedObservable.add(function () {
  98128. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  98129. });
  98130. _this.onApplyObservable.add(function (effect) {
  98131. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  98132. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  98133. });
  98134. return _this;
  98135. }
  98136. return StereoscopicInterlacePostProcess;
  98137. }(BABYLON.PostProcess));
  98138. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  98139. })(BABYLON || (BABYLON = {}));
  98140. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  98141. var BABYLON;
  98142. (function (BABYLON) {
  98143. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  98144. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98145. });
  98146. /**
  98147. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  98148. * @see http://doc.babylonjs.com/features/cameras
  98149. */
  98150. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  98151. __extends(StereoscopicArcRotateCamera, _super);
  98152. /**
  98153. * Creates a new StereoscopicArcRotateCamera
  98154. * @param name defines camera name
  98155. * @param alpha defines alpha angle (in radians)
  98156. * @param beta defines beta angle (in radians)
  98157. * @param radius defines radius
  98158. * @param target defines camera target
  98159. * @param interaxialDistance defines distance between each color axis
  98160. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98161. * @param scene defines the hosting scene
  98162. */
  98163. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  98164. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  98165. _this.interaxialDistance = interaxialDistance;
  98166. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98167. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98168. return _this;
  98169. }
  98170. /**
  98171. * Gets camera class name
  98172. * @returns StereoscopicArcRotateCamera
  98173. */
  98174. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  98175. return "StereoscopicArcRotateCamera";
  98176. };
  98177. return StereoscopicArcRotateCamera;
  98178. }(BABYLON.ArcRotateCamera));
  98179. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  98180. })(BABYLON || (BABYLON = {}));
  98181. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  98182. var BABYLON;
  98183. (function (BABYLON) {
  98184. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  98185. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98186. });
  98187. /**
  98188. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  98189. * @see http://doc.babylonjs.com/features/cameras
  98190. */
  98191. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  98192. __extends(StereoscopicFreeCamera, _super);
  98193. /**
  98194. * Creates a new StereoscopicFreeCamera
  98195. * @param name defines camera name
  98196. * @param position defines initial position
  98197. * @param interaxialDistance defines distance between each color axis
  98198. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98199. * @param scene defines the hosting scene
  98200. */
  98201. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98202. var _this = _super.call(this, name, position, scene) || this;
  98203. _this.interaxialDistance = interaxialDistance;
  98204. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98205. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98206. return _this;
  98207. }
  98208. /**
  98209. * Gets camera class name
  98210. * @returns StereoscopicFreeCamera
  98211. */
  98212. StereoscopicFreeCamera.prototype.getClassName = function () {
  98213. return "StereoscopicFreeCamera";
  98214. };
  98215. return StereoscopicFreeCamera;
  98216. }(BABYLON.FreeCamera));
  98217. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  98218. })(BABYLON || (BABYLON = {}));
  98219. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  98220. var BABYLON;
  98221. (function (BABYLON) {
  98222. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  98223. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98224. });
  98225. /**
  98226. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  98227. * @see http://doc.babylonjs.com/features/cameras
  98228. */
  98229. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  98230. __extends(StereoscopicGamepadCamera, _super);
  98231. /**
  98232. * Creates a new StereoscopicGamepadCamera
  98233. * @param name defines camera name
  98234. * @param position defines initial position
  98235. * @param interaxialDistance defines distance between each color axis
  98236. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98237. * @param scene defines the hosting scene
  98238. */
  98239. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98240. var _this = _super.call(this, name, position, scene) || this;
  98241. _this.interaxialDistance = interaxialDistance;
  98242. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98243. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98244. return _this;
  98245. }
  98246. /**
  98247. * Gets camera class name
  98248. * @returns StereoscopicGamepadCamera
  98249. */
  98250. StereoscopicGamepadCamera.prototype.getClassName = function () {
  98251. return "StereoscopicGamepadCamera";
  98252. };
  98253. return StereoscopicGamepadCamera;
  98254. }(BABYLON.GamepadCamera));
  98255. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  98256. })(BABYLON || (BABYLON = {}));
  98257. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  98258. var BABYLON;
  98259. (function (BABYLON) {
  98260. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  98261. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98262. });
  98263. /**
  98264. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  98265. * @see http://doc.babylonjs.com/features/cameras
  98266. */
  98267. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  98268. __extends(StereoscopicUniversalCamera, _super);
  98269. /**
  98270. * Creates a new StereoscopicUniversalCamera
  98271. * @param name defines camera name
  98272. * @param position defines initial position
  98273. * @param interaxialDistance defines distance between each color axis
  98274. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98275. * @param scene defines the hosting scene
  98276. */
  98277. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98278. var _this = _super.call(this, name, position, scene) || this;
  98279. _this.interaxialDistance = interaxialDistance;
  98280. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98281. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98282. return _this;
  98283. }
  98284. /**
  98285. * Gets camera class name
  98286. * @returns StereoscopicUniversalCamera
  98287. */
  98288. StereoscopicUniversalCamera.prototype.getClassName = function () {
  98289. return "StereoscopicUniversalCamera";
  98290. };
  98291. return StereoscopicUniversalCamera;
  98292. }(BABYLON.UniversalCamera));
  98293. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  98294. })(BABYLON || (BABYLON = {}));
  98295. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  98296. var BABYLON;
  98297. (function (BABYLON) {
  98298. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  98299. __extends(VRDistortionCorrectionPostProcess, _super);
  98300. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  98301. var _this = _super.call(this, name, "vrDistortionCorrection", [
  98302. 'LensCenter',
  98303. 'Scale',
  98304. 'ScaleIn',
  98305. 'HmdWarpParam'
  98306. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  98307. _this._isRightEye = isRightEye;
  98308. _this._distortionFactors = vrMetrics.distortionK;
  98309. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  98310. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  98311. _this.adaptScaleToCurrentViewport = true;
  98312. _this.onSizeChangedObservable.add(function () {
  98313. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  98314. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  98315. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  98316. });
  98317. _this.onApplyObservable.add(function (effect) {
  98318. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  98319. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  98320. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  98321. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  98322. });
  98323. return _this;
  98324. }
  98325. return VRDistortionCorrectionPostProcess;
  98326. }(BABYLON.PostProcess));
  98327. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  98328. })(BABYLON || (BABYLON = {}));
  98329. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  98330. var BABYLON;
  98331. (function (BABYLON) {
  98332. /**
  98333. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  98334. * Screen rotation is taken into account.
  98335. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98336. */
  98337. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  98338. /**
  98339. * Instantiates a new input
  98340. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98341. */
  98342. function FreeCameraDeviceOrientationInput() {
  98343. var _this = this;
  98344. this._screenOrientationAngle = 0;
  98345. this._screenQuaternion = new BABYLON.Quaternion();
  98346. this._alpha = 0;
  98347. this._beta = 0;
  98348. this._gamma = 0;
  98349. this._orientationChanged = function () {
  98350. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  98351. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  98352. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  98353. };
  98354. this._deviceOrientation = function (evt) {
  98355. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  98356. _this._beta = evt.beta !== null ? evt.beta : 0;
  98357. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  98358. };
  98359. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  98360. this._orientationChanged();
  98361. }
  98362. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  98363. /**
  98364. * Define the camera controlled by the input.
  98365. */
  98366. get: function () {
  98367. return this._camera;
  98368. },
  98369. set: function (camera) {
  98370. this._camera = camera;
  98371. if (this._camera != null && !this._camera.rotationQuaternion) {
  98372. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  98373. }
  98374. },
  98375. enumerable: true,
  98376. configurable: true
  98377. });
  98378. /**
  98379. * Attach the input controls to a specific dom element to get the input from.
  98380. * @param element Defines the element the controls should be listened from
  98381. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  98382. */
  98383. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  98384. window.addEventListener("orientationchange", this._orientationChanged);
  98385. window.addEventListener("deviceorientation", this._deviceOrientation);
  98386. //In certain cases, the attach control is called AFTER orientation was changed,
  98387. //So this is needed.
  98388. this._orientationChanged();
  98389. };
  98390. /**
  98391. * Detach the current controls from the specified dom element.
  98392. * @param element Defines the element to stop listening the inputs from
  98393. */
  98394. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  98395. window.removeEventListener("orientationchange", this._orientationChanged);
  98396. window.removeEventListener("deviceorientation", this._deviceOrientation);
  98397. };
  98398. /**
  98399. * Update the current camera state depending on the inputs that have been used this frame.
  98400. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  98401. */
  98402. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  98403. //if no device orientation provided, don't update the rotation.
  98404. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  98405. if (!this._alpha)
  98406. return;
  98407. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  98408. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  98409. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  98410. //Mirror on XY Plane
  98411. this._camera.rotationQuaternion.z *= -1;
  98412. this._camera.rotationQuaternion.w *= -1;
  98413. };
  98414. /**
  98415. * Gets the class name of the current intput.
  98416. * @returns the class name
  98417. */
  98418. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  98419. return "FreeCameraDeviceOrientationInput";
  98420. };
  98421. /**
  98422. * Get the friendly name associated with the input class.
  98423. * @returns the input friendly name
  98424. */
  98425. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  98426. return "deviceOrientation";
  98427. };
  98428. return FreeCameraDeviceOrientationInput;
  98429. }());
  98430. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  98431. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  98432. })(BABYLON || (BABYLON = {}));
  98433. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  98434. var BABYLON;
  98435. (function (BABYLON) {
  98436. /**
  98437. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  98438. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98439. */
  98440. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  98441. /**
  98442. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  98443. */
  98444. function ArcRotateCameraVRDeviceOrientationInput() {
  98445. /**
  98446. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  98447. */
  98448. this.alphaCorrection = 1;
  98449. /**
  98450. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  98451. */
  98452. this.betaCorrection = 1;
  98453. /**
  98454. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  98455. */
  98456. this.gammaCorrection = 1;
  98457. this._alpha = 0;
  98458. this._gamma = 0;
  98459. this._dirty = false;
  98460. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  98461. }
  98462. /**
  98463. * Attach the input controls to a specific dom element to get the input from.
  98464. * @param element Defines the element the controls should be listened from
  98465. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  98466. */
  98467. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  98468. this.camera.attachControl(element, noPreventDefault);
  98469. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  98470. };
  98471. /** @hidden */
  98472. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  98473. if (evt.alpha !== null) {
  98474. this._alpha = +evt.alpha | 0;
  98475. }
  98476. if (evt.gamma !== null) {
  98477. this._gamma = +evt.gamma | 0;
  98478. }
  98479. this._dirty = true;
  98480. };
  98481. /**
  98482. * Update the current camera state depending on the inputs that have been used this frame.
  98483. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  98484. */
  98485. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  98486. if (this._dirty) {
  98487. this._dirty = false;
  98488. if (this._gamma < 0) {
  98489. this._gamma = 180 + this._gamma;
  98490. }
  98491. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  98492. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  98493. }
  98494. };
  98495. /**
  98496. * Detach the current controls from the specified dom element.
  98497. * @param element Defines the element to stop listening the inputs from
  98498. */
  98499. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  98500. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  98501. };
  98502. /**
  98503. * Gets the class name of the current intput.
  98504. * @returns the class name
  98505. */
  98506. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  98507. return "ArcRotateCameraVRDeviceOrientationInput";
  98508. };
  98509. /**
  98510. * Get the friendly name associated with the input class.
  98511. * @returns the input friendly name
  98512. */
  98513. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  98514. return "VRDeviceOrientation";
  98515. };
  98516. return ArcRotateCameraVRDeviceOrientationInput;
  98517. }());
  98518. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  98519. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  98520. })(BABYLON || (BABYLON = {}));
  98521. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  98522. var BABYLON;
  98523. (function (BABYLON) {
  98524. /**
  98525. * This represents all the required metrics to create a VR camera.
  98526. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  98527. */
  98528. var VRCameraMetrics = /** @class */ (function () {
  98529. function VRCameraMetrics() {
  98530. /**
  98531. * Define if the current vr camera should compensate the distortion of the lense or not.
  98532. */
  98533. this.compensateDistortion = true;
  98534. }
  98535. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  98536. /**
  98537. * Gets the rendering aspect ratio based on the provided resolutions.
  98538. */
  98539. get: function () {
  98540. return this.hResolution / (2 * this.vResolution);
  98541. },
  98542. enumerable: true,
  98543. configurable: true
  98544. });
  98545. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  98546. /**
  98547. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  98548. */
  98549. get: function () {
  98550. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  98551. },
  98552. enumerable: true,
  98553. configurable: true
  98554. });
  98555. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  98556. /**
  98557. * @hidden
  98558. */
  98559. get: function () {
  98560. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  98561. var h = (4 * meters) / this.hScreenSize;
  98562. return BABYLON.Matrix.Translation(h, 0, 0);
  98563. },
  98564. enumerable: true,
  98565. configurable: true
  98566. });
  98567. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  98568. /**
  98569. * @hidden
  98570. */
  98571. get: function () {
  98572. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  98573. var h = (4 * meters) / this.hScreenSize;
  98574. return BABYLON.Matrix.Translation(-h, 0, 0);
  98575. },
  98576. enumerable: true,
  98577. configurable: true
  98578. });
  98579. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  98580. /**
  98581. * @hidden
  98582. */
  98583. get: function () {
  98584. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  98585. },
  98586. enumerable: true,
  98587. configurable: true
  98588. });
  98589. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  98590. /**
  98591. * @hidden
  98592. */
  98593. get: function () {
  98594. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  98595. },
  98596. enumerable: true,
  98597. configurable: true
  98598. });
  98599. /**
  98600. * Get the default VRMetrics based on the most generic setup.
  98601. * @returns the default vr metrics
  98602. */
  98603. VRCameraMetrics.GetDefault = function () {
  98604. var result = new VRCameraMetrics();
  98605. result.hResolution = 1280;
  98606. result.vResolution = 800;
  98607. result.hScreenSize = 0.149759993;
  98608. result.vScreenSize = 0.0935999975;
  98609. result.vScreenCenter = 0.0467999987;
  98610. result.eyeToScreenDistance = 0.0410000011;
  98611. result.lensSeparationDistance = 0.0635000020;
  98612. result.interpupillaryDistance = 0.0640000030;
  98613. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  98614. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  98615. result.postProcessScaleFactor = 1.714605507808412;
  98616. result.lensCenterOffset = 0.151976421;
  98617. return result;
  98618. };
  98619. return VRCameraMetrics;
  98620. }());
  98621. BABYLON.VRCameraMetrics = VRCameraMetrics;
  98622. })(BABYLON || (BABYLON = {}));
  98623. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  98624. var BABYLON;
  98625. (function (BABYLON) {
  98626. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  98627. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  98628. });
  98629. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  98630. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  98631. });
  98632. /**
  98633. * This represents a WebVR camera.
  98634. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  98635. * @example http://doc.babylonjs.com/how_to/webvr_camera
  98636. */
  98637. var WebVRFreeCamera = /** @class */ (function (_super) {
  98638. __extends(WebVRFreeCamera, _super);
  98639. /**
  98640. * Instantiates a WebVRFreeCamera.
  98641. * @param name The name of the WebVRFreeCamera
  98642. * @param position The starting anchor position for the camera
  98643. * @param scene The scene the camera belongs to
  98644. * @param webVROptions a set of customizable options for the webVRCamera
  98645. */
  98646. function WebVRFreeCamera(name, position, scene, webVROptions) {
  98647. if (webVROptions === void 0) { webVROptions = {}; }
  98648. var _this = _super.call(this, name, position, scene) || this;
  98649. _this.webVROptions = webVROptions;
  98650. /**
  98651. * @hidden
  98652. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  98653. */
  98654. _this._vrDevice = null;
  98655. /**
  98656. * The rawPose of the vrDevice.
  98657. */
  98658. _this.rawPose = null;
  98659. _this._specsVersion = "1.1";
  98660. _this._attached = false;
  98661. _this._descendants = [];
  98662. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  98663. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  98664. /** @hidden */
  98665. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  98666. _this._standingMatrix = null;
  98667. /**
  98668. * Represents device position in babylon space.
  98669. */
  98670. _this.devicePosition = BABYLON.Vector3.Zero();
  98671. /**
  98672. * Represents device rotation in babylon space.
  98673. */
  98674. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  98675. /**
  98676. * The scale of the device to be used when translating from device space to babylon space.
  98677. */
  98678. _this.deviceScaleFactor = 1;
  98679. _this._deviceToWorld = BABYLON.Matrix.Identity();
  98680. _this._worldToDevice = BABYLON.Matrix.Identity();
  98681. /**
  98682. * References to the webVR controllers for the vrDevice.
  98683. */
  98684. _this.controllers = [];
  98685. /**
  98686. * Emits an event when a controller is attached.
  98687. */
  98688. _this.onControllersAttachedObservable = new BABYLON.Observable();
  98689. /**
  98690. * Emits an event when a controller's mesh has been loaded;
  98691. */
  98692. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  98693. /**
  98694. * Emits an event when the HMD's pose has been updated.
  98695. */
  98696. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  98697. _this._poseSet = false;
  98698. /**
  98699. * If the rig cameras be used as parent instead of this camera.
  98700. */
  98701. _this.rigParenting = true;
  98702. _this._defaultHeight = undefined;
  98703. _this._htmlElementAttached = null;
  98704. _this._detachIfAttached = function () {
  98705. var vrDisplay = _this.getEngine().getVRDevice();
  98706. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  98707. _this.detachControl(_this._htmlElementAttached);
  98708. }
  98709. };
  98710. _this._workingVector = BABYLON.Vector3.Zero();
  98711. _this._oneVector = BABYLON.Vector3.One();
  98712. _this._workingMatrix = BABYLON.Matrix.Identity();
  98713. _this._tmpMatrix = new BABYLON.Matrix();
  98714. _this._cache.position = BABYLON.Vector3.Zero();
  98715. if (webVROptions.defaultHeight) {
  98716. _this._defaultHeight = webVROptions.defaultHeight;
  98717. _this.position.y = _this._defaultHeight;
  98718. }
  98719. _this.minZ = 0.1;
  98720. //legacy support - the compensation boolean was removed.
  98721. if (arguments.length === 5) {
  98722. _this.webVROptions = arguments[4];
  98723. }
  98724. // default webVR options
  98725. if (_this.webVROptions.trackPosition == undefined) {
  98726. _this.webVROptions.trackPosition = true;
  98727. }
  98728. if (_this.webVROptions.controllerMeshes == undefined) {
  98729. _this.webVROptions.controllerMeshes = true;
  98730. }
  98731. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  98732. _this.webVROptions.defaultLightingOnControllers = true;
  98733. }
  98734. _this.rotationQuaternion = new BABYLON.Quaternion();
  98735. if (_this.webVROptions && _this.webVROptions.positionScale) {
  98736. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  98737. }
  98738. //enable VR
  98739. var engine = _this.getEngine();
  98740. _this._onVREnabled = function (success) { if (success) {
  98741. _this.initControllers();
  98742. } };
  98743. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  98744. engine.initWebVR().add(function (event) {
  98745. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  98746. return;
  98747. }
  98748. _this._vrDevice = event.vrDisplay;
  98749. //reset the rig parameters.
  98750. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  98751. if (_this._attached) {
  98752. _this.getEngine().enableVR();
  98753. }
  98754. });
  98755. if (typeof (VRFrameData) !== "undefined")
  98756. _this._frameData = new VRFrameData();
  98757. /**
  98758. * The idea behind the following lines:
  98759. * objects that have the camera as parent should actually have the rig cameras as a parent.
  98760. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  98761. * the second will not show it correctly.
  98762. *
  98763. * To solve this - each object that has the camera as parent will be added to a protected array.
  98764. * When the rig camera renders, it will take this array and set all of those to be its children.
  98765. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  98766. * Amazing!
  98767. */
  98768. scene.onBeforeCameraRenderObservable.add(function (camera) {
  98769. if (camera.parent === _this && _this.rigParenting) {
  98770. _this._descendants = _this.getDescendants(true, function (n) {
  98771. // don't take the cameras or the controllers!
  98772. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  98773. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  98774. return !isController && !isRigCamera;
  98775. });
  98776. _this._descendants.forEach(function (node) {
  98777. node.parent = camera;
  98778. });
  98779. }
  98780. });
  98781. scene.onAfterCameraRenderObservable.add(function (camera) {
  98782. if (camera.parent === _this && _this.rigParenting) {
  98783. _this._descendants.forEach(function (node) {
  98784. node.parent = _this;
  98785. });
  98786. }
  98787. });
  98788. return _this;
  98789. }
  98790. /**
  98791. * Gets the device distance from the ground in meters.
  98792. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  98793. */
  98794. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  98795. if (this._standingMatrix) {
  98796. // Add standing matrix offset to get real offset from ground in room
  98797. this._standingMatrix.getTranslationToRef(this._workingVector);
  98798. return this._deviceRoomPosition.y + this._workingVector.y;
  98799. }
  98800. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  98801. return this._defaultHeight || 0;
  98802. };
  98803. /**
  98804. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  98805. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  98806. */
  98807. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  98808. var _this = this;
  98809. if (callback === void 0) { callback = function (bool) { }; }
  98810. // Use standing matrix if available
  98811. this.getEngine().initWebVRAsync().then(function (result) {
  98812. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  98813. callback(false);
  98814. }
  98815. else {
  98816. _this._standingMatrix = new BABYLON.Matrix();
  98817. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  98818. if (!_this.getScene().useRightHandedSystem) {
  98819. [2, 6, 8, 9, 14].forEach(function (num) {
  98820. if (_this._standingMatrix) {
  98821. _this._standingMatrix.m[num] *= -1;
  98822. }
  98823. });
  98824. }
  98825. callback(true);
  98826. }
  98827. });
  98828. };
  98829. /**
  98830. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  98831. * @returns A promise with a boolean set to if the standing matrix is supported.
  98832. */
  98833. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  98834. var _this = this;
  98835. return new Promise(function (res, rej) {
  98836. _this.useStandingMatrix(function (supported) {
  98837. res(supported);
  98838. });
  98839. });
  98840. };
  98841. /**
  98842. * Disposes the camera
  98843. */
  98844. WebVRFreeCamera.prototype.dispose = function () {
  98845. this._detachIfAttached();
  98846. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  98847. _super.prototype.dispose.call(this);
  98848. };
  98849. /**
  98850. * Gets a vrController by name.
  98851. * @param name The name of the controller to retreive
  98852. * @returns the controller matching the name specified or null if not found
  98853. */
  98854. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  98855. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  98856. var gp = _a[_i];
  98857. if (gp.hand === name) {
  98858. return gp;
  98859. }
  98860. }
  98861. return null;
  98862. };
  98863. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  98864. /**
  98865. * The controller corrisponding to the users left hand.
  98866. */
  98867. get: function () {
  98868. if (!this._leftController) {
  98869. this._leftController = this.getControllerByName("left");
  98870. }
  98871. return this._leftController;
  98872. },
  98873. enumerable: true,
  98874. configurable: true
  98875. });
  98876. ;
  98877. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  98878. /**
  98879. * The controller corrisponding to the users right hand.
  98880. */
  98881. get: function () {
  98882. if (!this._rightController) {
  98883. this._rightController = this.getControllerByName("right");
  98884. }
  98885. return this._rightController;
  98886. },
  98887. enumerable: true,
  98888. configurable: true
  98889. });
  98890. ;
  98891. /**
  98892. * Casts a ray forward from the vrCamera's gaze.
  98893. * @param length Length of the ray (default: 100)
  98894. * @returns the ray corrisponding to the gaze
  98895. */
  98896. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  98897. if (length === void 0) { length = 100; }
  98898. if (this.leftCamera) {
  98899. // Use left eye to avoid computation to compute center on every call
  98900. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  98901. }
  98902. else {
  98903. return _super.prototype.getForwardRay.call(this, length);
  98904. }
  98905. };
  98906. /**
  98907. * @hidden
  98908. * Updates the camera based on device's frame data
  98909. */
  98910. WebVRFreeCamera.prototype._checkInputs = function () {
  98911. if (this._vrDevice && this._vrDevice.isPresenting) {
  98912. this._vrDevice.getFrameData(this._frameData);
  98913. this.updateFromDevice(this._frameData.pose);
  98914. }
  98915. _super.prototype._checkInputs.call(this);
  98916. };
  98917. /**
  98918. * Updates the poseControlled values based on the input device pose.
  98919. * @param poseData Pose coming from the device
  98920. */
  98921. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  98922. if (poseData && poseData.orientation) {
  98923. this.rawPose = poseData;
  98924. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  98925. if (this.getScene().useRightHandedSystem) {
  98926. this._deviceRoomRotationQuaternion.z *= -1;
  98927. this._deviceRoomRotationQuaternion.w *= -1;
  98928. }
  98929. if (this.webVROptions.trackPosition && this.rawPose.position) {
  98930. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  98931. if (this.getScene().useRightHandedSystem) {
  98932. this._deviceRoomPosition.z *= -1;
  98933. }
  98934. }
  98935. this._poseSet = true;
  98936. }
  98937. };
  98938. /**
  98939. * WebVR's attach control will start broadcasting frames to the device.
  98940. * Note that in certain browsers (chrome for example) this function must be called
  98941. * within a user-interaction callback. Example:
  98942. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  98943. *
  98944. * @param element html element to attach the vrDevice to
  98945. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  98946. */
  98947. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  98948. _super.prototype.attachControl.call(this, element, noPreventDefault);
  98949. this._attached = true;
  98950. this._htmlElementAttached = element;
  98951. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  98952. if (this._vrDevice) {
  98953. this.getEngine().enableVR();
  98954. }
  98955. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  98956. };
  98957. /**
  98958. * Detaches the camera from the html element and disables VR
  98959. *
  98960. * @param element html element to detach from
  98961. */
  98962. WebVRFreeCamera.prototype.detachControl = function (element) {
  98963. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  98964. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  98965. _super.prototype.detachControl.call(this, element);
  98966. this._attached = false;
  98967. this.getEngine().disableVR();
  98968. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  98969. };
  98970. /**
  98971. * @returns the name of this class
  98972. */
  98973. WebVRFreeCamera.prototype.getClassName = function () {
  98974. return "WebVRFreeCamera";
  98975. };
  98976. /**
  98977. * Calls resetPose on the vrDisplay
  98978. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  98979. */
  98980. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  98981. //uses the vrDisplay's "resetPose()".
  98982. //pitch and roll won't be affected.
  98983. this._vrDevice.resetPose();
  98984. };
  98985. /**
  98986. * @hidden
  98987. * Updates the rig cameras (left and right eye)
  98988. */
  98989. WebVRFreeCamera.prototype._updateRigCameras = function () {
  98990. var camLeft = this._rigCameras[0];
  98991. var camRight = this._rigCameras[1];
  98992. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  98993. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  98994. camLeft.position.copyFrom(this._deviceRoomPosition);
  98995. camRight.position.copyFrom(this._deviceRoomPosition);
  98996. };
  98997. // Remove translation from 6dof headset if trackposition is set to false
  98998. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  98999. if (isViewMatrix === void 0) { isViewMatrix = false; }
  99000. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  99001. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  99002. if (!isViewMatrix) {
  99003. this._tmpMatrix.invert();
  99004. }
  99005. this._tmpMatrix.multiplyToRef(matrix, matrix);
  99006. }
  99007. };
  99008. /**
  99009. * @hidden
  99010. * Updates the cached values of the camera
  99011. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  99012. */
  99013. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  99014. var _this = this;
  99015. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  99016. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  99017. if (!this.updateCacheCalled) {
  99018. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  99019. this.updateCacheCalled = true;
  99020. this.update();
  99021. }
  99022. // Set working vector to the device position in room space rotated by the new rotation
  99023. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  99024. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  99025. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  99026. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  99027. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  99028. // Add translation from anchor position
  99029. this._deviceToWorld.getTranslationToRef(this._workingVector);
  99030. this._workingVector.addInPlace(this.position);
  99031. this._workingVector.subtractInPlace(this._cache.position);
  99032. this._deviceToWorld.setTranslation(this._workingVector);
  99033. // Set an inverted matrix to be used when updating the camera
  99034. this._deviceToWorld.invertToRef(this._worldToDevice);
  99035. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  99036. this.controllers.forEach(function (controller) {
  99037. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  99038. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  99039. controller.update();
  99040. });
  99041. }
  99042. if (!ignoreParentClass) {
  99043. _super.prototype._updateCache.call(this);
  99044. }
  99045. this.updateCacheCalled = false;
  99046. };
  99047. /**
  99048. * Updates the current device position and rotation in the babylon world
  99049. */
  99050. WebVRFreeCamera.prototype.update = function () {
  99051. // Get current device position in babylon world
  99052. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  99053. // Get current device rotation in babylon world
  99054. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  99055. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  99056. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  99057. if (this._poseSet) {
  99058. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  99059. }
  99060. _super.prototype.update.call(this);
  99061. };
  99062. /**
  99063. * @hidden
  99064. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  99065. * @returns an identity matrix
  99066. */
  99067. WebVRFreeCamera.prototype._getViewMatrix = function () {
  99068. return BABYLON.Matrix.Identity();
  99069. };
  99070. /**
  99071. * This function is called by the two RIG cameras.
  99072. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  99073. */
  99074. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  99075. var _this = this;
  99076. // Update the parent camera prior to using a child camera to avoid desynchronization
  99077. var parentCamera = this._cameraRigParams["parentCamera"];
  99078. parentCamera._updateCache();
  99079. //WebVR 1.1
  99080. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  99081. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  99082. if (!this.getScene().useRightHandedSystem) {
  99083. [2, 6, 8, 9, 14].forEach(function (num) {
  99084. _this._webvrViewMatrix.m[num] *= -1;
  99085. });
  99086. }
  99087. // update the camera rotation matrix
  99088. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  99089. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  99090. // Computing target and final matrix
  99091. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  99092. // should the view matrix be updated with scale and position offset?
  99093. if (parentCamera.deviceScaleFactor !== 1) {
  99094. this._webvrViewMatrix.invert();
  99095. // scale the position, if set
  99096. if (parentCamera.deviceScaleFactor) {
  99097. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  99098. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  99099. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  99100. }
  99101. this._webvrViewMatrix.invert();
  99102. }
  99103. // Remove translation from 6dof headset if trackposition is set to false
  99104. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  99105. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  99106. // Compute global position
  99107. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  99108. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  99109. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  99110. this._workingMatrix.getTranslationToRef(this._globalPosition);
  99111. this._markSyncedWithParent();
  99112. return this._webvrViewMatrix;
  99113. };
  99114. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  99115. var _this = this;
  99116. var parentCamera = this.parent;
  99117. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  99118. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  99119. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  99120. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  99121. //babylon compatible matrix
  99122. if (!this.getScene().useRightHandedSystem) {
  99123. [8, 9, 10, 11].forEach(function (num) {
  99124. _this._projectionMatrix.m[num] *= -1;
  99125. });
  99126. }
  99127. return this._projectionMatrix;
  99128. };
  99129. /**
  99130. * Initializes the controllers and their meshes
  99131. */
  99132. WebVRFreeCamera.prototype.initControllers = function () {
  99133. var _this = this;
  99134. this.controllers = [];
  99135. var manager = this.getScene().gamepadManager;
  99136. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  99137. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  99138. var webVrController = gamepad;
  99139. if (webVrController.defaultModel) {
  99140. webVrController.defaultModel.setEnabled(false);
  99141. }
  99142. if (webVrController.hand === "right") {
  99143. _this._rightController = null;
  99144. }
  99145. if (webVrController.hand === "left") {
  99146. _this._leftController = null;
  99147. }
  99148. var controllerIndex = _this.controllers.indexOf(webVrController);
  99149. if (controllerIndex !== -1) {
  99150. _this.controllers.splice(controllerIndex, 1);
  99151. }
  99152. }
  99153. });
  99154. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  99155. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  99156. var webVrController_1 = gamepad;
  99157. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  99158. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  99159. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  99160. if (_this.webVROptions.controllerMeshes) {
  99161. if (webVrController_1.defaultModel) {
  99162. webVrController_1.defaultModel.setEnabled(true);
  99163. }
  99164. else {
  99165. // Load the meshes
  99166. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  99167. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  99168. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  99169. if (_this.webVROptions.defaultLightingOnControllers) {
  99170. if (!_this._lightOnControllers) {
  99171. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  99172. }
  99173. var activateLightOnSubMeshes_1 = function (mesh, light) {
  99174. var children = mesh.getChildren();
  99175. if (children && children.length !== 0) {
  99176. children.forEach(function (mesh) {
  99177. light.includedOnlyMeshes.push(mesh);
  99178. activateLightOnSubMeshes_1(mesh, light);
  99179. });
  99180. }
  99181. };
  99182. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  99183. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  99184. }
  99185. });
  99186. }
  99187. }
  99188. webVrController_1.attachToPoseControlledCamera(_this);
  99189. // since this is async - sanity check. Is the controller already stored?
  99190. if (_this.controllers.indexOf(webVrController_1) === -1) {
  99191. //add to the controllers array
  99192. _this.controllers.push(webVrController_1);
  99193. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  99194. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  99195. // So we're overriding setting left & right manually to be sure
  99196. var firstViveWandDetected = false;
  99197. for (var i = 0; i < _this.controllers.length; i++) {
  99198. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  99199. if (!firstViveWandDetected) {
  99200. firstViveWandDetected = true;
  99201. _this.controllers[i].hand = "left";
  99202. }
  99203. else {
  99204. _this.controllers[i].hand = "right";
  99205. }
  99206. }
  99207. }
  99208. //did we find enough controllers? Great! let the developer know.
  99209. if (_this.controllers.length >= 2) {
  99210. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  99211. }
  99212. }
  99213. }
  99214. });
  99215. };
  99216. return WebVRFreeCamera;
  99217. }(BABYLON.FreeCamera));
  99218. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  99219. })(BABYLON || (BABYLON = {}));
  99220. //# sourceMappingURL=babylon.webVRCamera.js.map
  99221. var BABYLON;
  99222. (function (BABYLON) {
  99223. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  99224. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  99225. });
  99226. // We're mainly based on the logic defined into the FreeCamera code
  99227. /**
  99228. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  99229. * being tilted forward or back and left or right.
  99230. */
  99231. var DeviceOrientationCamera = /** @class */ (function (_super) {
  99232. __extends(DeviceOrientationCamera, _super);
  99233. /**
  99234. * Creates a new device orientation camera
  99235. * @param name The name of the camera
  99236. * @param position The start position camera
  99237. * @param scene The scene the camera belongs to
  99238. */
  99239. function DeviceOrientationCamera(name, position, scene) {
  99240. var _this = _super.call(this, name, position, scene) || this;
  99241. _this._quaternionCache = new BABYLON.Quaternion();
  99242. _this.inputs.addDeviceOrientation();
  99243. return _this;
  99244. }
  99245. /**
  99246. * Gets the current instance class name ("DeviceOrientationCamera").
  99247. * This helps avoiding instanceof at run time.
  99248. * @returns the class name
  99249. */
  99250. DeviceOrientationCamera.prototype.getClassName = function () {
  99251. return "DeviceOrientationCamera";
  99252. };
  99253. /**
  99254. * @hidden
  99255. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  99256. */
  99257. DeviceOrientationCamera.prototype._checkInputs = function () {
  99258. _super.prototype._checkInputs.call(this);
  99259. this._quaternionCache.copyFrom(this.rotationQuaternion);
  99260. if (this._initialQuaternion) {
  99261. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  99262. }
  99263. };
  99264. /**
  99265. * Reset the camera to its default orientation on the specified axis only.
  99266. * @param axis The axis to reset
  99267. */
  99268. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  99269. var _this = this;
  99270. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  99271. //can only work if this camera has a rotation quaternion already.
  99272. if (!this.rotationQuaternion)
  99273. return;
  99274. if (!this._initialQuaternion) {
  99275. this._initialQuaternion = new BABYLON.Quaternion();
  99276. }
  99277. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  99278. ['x', 'y', 'z'].forEach(function (axisName) {
  99279. if (!axis[axisName]) {
  99280. _this._initialQuaternion[axisName] = 0;
  99281. }
  99282. else {
  99283. _this._initialQuaternion[axisName] *= -1;
  99284. }
  99285. });
  99286. this._initialQuaternion.normalize();
  99287. //force rotation update
  99288. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  99289. };
  99290. return DeviceOrientationCamera;
  99291. }(BABYLON.FreeCamera));
  99292. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  99293. })(BABYLON || (BABYLON = {}));
  99294. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  99295. var BABYLON;
  99296. (function (BABYLON) {
  99297. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  99298. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99299. });
  99300. /**
  99301. * Camera used to simulate VR rendering (based on FreeCamera)
  99302. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99303. */
  99304. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  99305. __extends(VRDeviceOrientationFreeCamera, _super);
  99306. /**
  99307. * Creates a new VRDeviceOrientationFreeCamera
  99308. * @param name defines camera name
  99309. * @param position defines the start position of the camera
  99310. * @param scene defines the scene the camera belongs to
  99311. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99312. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99313. */
  99314. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  99315. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99316. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99317. var _this = _super.call(this, name, position, scene) || this;
  99318. vrCameraMetrics.compensateDistortion = compensateDistortion;
  99319. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  99320. return _this;
  99321. }
  99322. /**
  99323. * Gets camera class name
  99324. * @returns VRDeviceOrientationFreeCamera
  99325. */
  99326. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  99327. return "VRDeviceOrientationFreeCamera";
  99328. };
  99329. return VRDeviceOrientationFreeCamera;
  99330. }(BABYLON.DeviceOrientationCamera));
  99331. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  99332. })(BABYLON || (BABYLON = {}));
  99333. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  99334. var BABYLON;
  99335. (function (BABYLON) {
  99336. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  99337. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  99338. });
  99339. /**
  99340. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  99341. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99342. */
  99343. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  99344. __extends(VRDeviceOrientationArcRotateCamera, _super);
  99345. /**
  99346. * Creates a new VRDeviceOrientationArcRotateCamera
  99347. * @param name defines camera name
  99348. * @param alpha defines the camera rotation along the logitudinal axis
  99349. * @param beta defines the camera rotation along the latitudinal axis
  99350. * @param radius defines the camera distance from its target
  99351. * @param target defines the camera target
  99352. * @param scene defines the scene the camera belongs to
  99353. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99354. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99355. */
  99356. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  99357. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99358. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99359. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99360. vrCameraMetrics.compensateDistortion = compensateDistortion;
  99361. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  99362. _this.inputs.addVRDeviceOrientation();
  99363. return _this;
  99364. }
  99365. /**
  99366. * Gets camera class name
  99367. * @returns VRDeviceOrientationArcRotateCamera
  99368. */
  99369. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  99370. return "VRDeviceOrientationArcRotateCamera";
  99371. };
  99372. return VRDeviceOrientationArcRotateCamera;
  99373. }(BABYLON.ArcRotateCamera));
  99374. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  99375. })(BABYLON || (BABYLON = {}));
  99376. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  99377. var BABYLON;
  99378. (function (BABYLON) {
  99379. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  99380. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  99381. });
  99382. /**
  99383. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  99384. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99385. */
  99386. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  99387. __extends(VRDeviceOrientationGamepadCamera, _super);
  99388. /**
  99389. * Creates a new VRDeviceOrientationGamepadCamera
  99390. * @param name defines camera name
  99391. * @param position defines the start position of the camera
  99392. * @param scene defines the scene the camera belongs to
  99393. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99394. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99395. */
  99396. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  99397. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99398. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99399. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  99400. _this.inputs.addGamepad();
  99401. return _this;
  99402. }
  99403. /**
  99404. * Gets camera class name
  99405. * @returns VRDeviceOrientationGamepadCamera
  99406. */
  99407. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  99408. return "VRDeviceOrientationGamepadCamera";
  99409. };
  99410. return VRDeviceOrientationGamepadCamera;
  99411. }(BABYLON.VRDeviceOrientationFreeCamera));
  99412. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  99413. })(BABYLON || (BABYLON = {}));
  99414. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  99415. var BABYLON;
  99416. (function (BABYLON) {
  99417. var VRExperienceHelperGazer = /** @class */ (function () {
  99418. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  99419. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  99420. this.scene = scene;
  99421. /** @hidden */
  99422. this._pointerDownOnMeshAsked = false;
  99423. /** @hidden */
  99424. this._isActionableMesh = false;
  99425. /** @hidden */
  99426. this._teleportationRequestInitiated = false;
  99427. /** @hidden */
  99428. this._teleportationBackRequestInitiated = false;
  99429. /** @hidden */
  99430. this._rotationRightAsked = false;
  99431. /** @hidden */
  99432. this._rotationLeftAsked = false;
  99433. /** @hidden */
  99434. this._dpadPressed = true;
  99435. /** @hidden */
  99436. this._activePointer = false;
  99437. this._id = VRExperienceHelperGazer._idCounter++;
  99438. // Gaze tracker
  99439. if (!gazeTrackerToClone) {
  99440. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  99441. this._gazeTracker.bakeCurrentTransformIntoVertices();
  99442. this._gazeTracker.isPickable = false;
  99443. this._gazeTracker.isVisible = false;
  99444. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  99445. targetMat.specularColor = BABYLON.Color3.Black();
  99446. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  99447. targetMat.backFaceCulling = false;
  99448. this._gazeTracker.material = targetMat;
  99449. }
  99450. else {
  99451. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  99452. }
  99453. }
  99454. /** @hidden */
  99455. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  99456. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  99457. };
  99458. /** @hidden */
  99459. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  99460. this._pointerDownOnMeshAsked = true;
  99461. if (this._currentHit) {
  99462. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  99463. }
  99464. };
  99465. /** @hidden */
  99466. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  99467. if (this._currentHit) {
  99468. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  99469. }
  99470. this._pointerDownOnMeshAsked = false;
  99471. };
  99472. /** @hidden */
  99473. VRExperienceHelperGazer.prototype._activatePointer = function () {
  99474. this._activePointer = true;
  99475. };
  99476. /** @hidden */
  99477. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  99478. this._activePointer = false;
  99479. };
  99480. /** @hidden */
  99481. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  99482. if (distance === void 0) { distance = 100; }
  99483. };
  99484. VRExperienceHelperGazer.prototype.dispose = function () {
  99485. this._interactionsEnabled = false;
  99486. this._teleportationEnabled = false;
  99487. if (this._gazeTracker) {
  99488. this._gazeTracker.dispose();
  99489. }
  99490. };
  99491. VRExperienceHelperGazer._idCounter = 0;
  99492. return VRExperienceHelperGazer;
  99493. }());
  99494. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  99495. __extends(VRExperienceHelperControllerGazer, _super);
  99496. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  99497. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  99498. _this.webVRController = webVRController;
  99499. // Laser pointer
  99500. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  99501. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  99502. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  99503. laserPointerMaterial.alpha = 0.6;
  99504. _this._laserPointer.material = laserPointerMaterial;
  99505. _this._laserPointer.rotation.x = Math.PI / 2;
  99506. _this._laserPointer.position.z = -0.5;
  99507. _this._laserPointer.isVisible = false;
  99508. _this._laserPointer.isPickable = false;
  99509. if (!webVRController.mesh) {
  99510. // Create an empty mesh that is used prior to loading the high quality model
  99511. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  99512. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  99513. preloadPointerPose.rotation.x = -0.7;
  99514. preloadMesh.addChild(preloadPointerPose);
  99515. webVRController.attachToMesh(preloadMesh);
  99516. }
  99517. _this._setLaserPointerParent(webVRController.mesh);
  99518. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  99519. _this._setLaserPointerParent(mesh);
  99520. });
  99521. return _this;
  99522. }
  99523. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  99524. return this.webVRController.getForwardRay(length);
  99525. };
  99526. /** @hidden */
  99527. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  99528. _super.prototype._activatePointer.call(this);
  99529. this._laserPointer.isVisible = true;
  99530. };
  99531. /** @hidden */
  99532. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  99533. _super.prototype._deactivatePointer.call(this);
  99534. this._laserPointer.isVisible = false;
  99535. };
  99536. /** @hidden */
  99537. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  99538. this._laserPointer.material.emissiveColor = color;
  99539. };
  99540. /** @hidden */
  99541. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  99542. var makeNotPick = function (root) {
  99543. root.isPickable = false;
  99544. root.getChildMeshes().forEach(function (c) {
  99545. makeNotPick(c);
  99546. });
  99547. };
  99548. makeNotPick(mesh);
  99549. var childMeshes = mesh.getChildMeshes();
  99550. this.webVRController._pointingPoseNode = null;
  99551. for (var i = 0; i < childMeshes.length; i++) {
  99552. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  99553. mesh = childMeshes[i];
  99554. this.webVRController._pointingPoseNode = mesh;
  99555. break;
  99556. }
  99557. }
  99558. this._laserPointer.parent = mesh;
  99559. };
  99560. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  99561. if (distance === void 0) { distance = 100; }
  99562. this._laserPointer.scaling.y = distance;
  99563. this._laserPointer.position.z = -distance / 2;
  99564. };
  99565. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  99566. _super.prototype.dispose.call(this);
  99567. this._laserPointer.dispose();
  99568. if (this._meshAttachedObserver) {
  99569. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  99570. }
  99571. };
  99572. return VRExperienceHelperControllerGazer;
  99573. }(VRExperienceHelperGazer));
  99574. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  99575. __extends(VRExperienceHelperCameraGazer, _super);
  99576. function VRExperienceHelperCameraGazer(getCamera, scene) {
  99577. var _this = _super.call(this, scene) || this;
  99578. _this.getCamera = getCamera;
  99579. return _this;
  99580. }
  99581. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  99582. var camera = this.getCamera();
  99583. if (camera) {
  99584. return camera.getForwardRay(length);
  99585. }
  99586. else {
  99587. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  99588. }
  99589. };
  99590. return VRExperienceHelperCameraGazer;
  99591. }(VRExperienceHelperGazer));
  99592. /**
  99593. * Helps to quickly add VR support to an existing scene.
  99594. * See http://doc.babylonjs.com/how_to/webvr_helper
  99595. */
  99596. var VRExperienceHelper = /** @class */ (function () {
  99597. /**
  99598. * Instantiates a VRExperienceHelper.
  99599. * Helps to quickly add VR support to an existing scene.
  99600. * @param scene The scene the VRExperienceHelper belongs to.
  99601. * @param webVROptions Options to modify the vr experience helper's behavior.
  99602. */
  99603. function VRExperienceHelper(scene,
  99604. /** Options to modify the vr experience helper's behavior. */
  99605. webVROptions) {
  99606. if (webVROptions === void 0) { webVROptions = {}; }
  99607. var _this = this;
  99608. this.webVROptions = webVROptions;
  99609. // Can the system support WebVR, even if a headset isn't plugged in?
  99610. this._webVRsupported = false;
  99611. // If WebVR is supported, is a headset plugged in and are we ready to present?
  99612. this._webVRready = false;
  99613. // Are we waiting for the requestPresent callback to complete?
  99614. this._webVRrequesting = false;
  99615. // Are we presenting to the headset right now? (this is the vrDevice state)
  99616. this._webVRpresenting = false;
  99617. // Are we presenting in the fullscreen fallback?
  99618. this._fullscreenVRpresenting = false;
  99619. /**
  99620. * Observable raised when entering VR.
  99621. */
  99622. this.onEnteringVRObservable = new BABYLON.Observable();
  99623. /**
  99624. * Observable raised when exiting VR.
  99625. */
  99626. this.onExitingVRObservable = new BABYLON.Observable();
  99627. /**
  99628. * Observable raised when controller mesh is loaded.
  99629. */
  99630. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  99631. this._useCustomVRButton = false;
  99632. this._teleportationRequested = false;
  99633. this._teleportActive = false;
  99634. this._floorMeshesCollection = [];
  99635. this._rotationAllowed = true;
  99636. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  99637. this._isDefaultTeleportationTarget = true;
  99638. this._teleportationFillColor = "#444444";
  99639. this._teleportationBorderColor = "#FFFFFF";
  99640. this._rotationAngle = 0;
  99641. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  99642. this._padSensibilityUp = 0.65;
  99643. this._padSensibilityDown = 0.35;
  99644. this._leftController = null;
  99645. this._rightController = null;
  99646. /**
  99647. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  99648. */
  99649. this.onNewMeshSelected = new BABYLON.Observable();
  99650. /**
  99651. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  99652. */
  99653. this.onNewMeshPicked = new BABYLON.Observable();
  99654. /**
  99655. * Observable raised before camera teleportation
  99656. */
  99657. this.onBeforeCameraTeleport = new BABYLON.Observable();
  99658. /**
  99659. * Observable raised after camera teleportation
  99660. */
  99661. this.onAfterCameraTeleport = new BABYLON.Observable();
  99662. /**
  99663. * Observable raised when current selected mesh gets unselected
  99664. */
  99665. this.onSelectedMeshUnselected = new BABYLON.Observable();
  99666. /**
  99667. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  99668. */
  99669. this.teleportationEnabled = true;
  99670. this._teleportationInitialized = false;
  99671. this._interactionsEnabled = false;
  99672. this._interactionsRequested = false;
  99673. this._displayGaze = true;
  99674. this._displayLaserPointer = true;
  99675. /**
  99676. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  99677. */
  99678. this.updateGazeTrackerScale = true;
  99679. this._onResize = function () {
  99680. _this.moveButtonToBottomRight();
  99681. if (_this._fullscreenVRpresenting && _this._webVRready) {
  99682. _this.exitVR();
  99683. }
  99684. };
  99685. this._onFullscreenChange = function () {
  99686. if (document.fullscreen !== undefined) {
  99687. _this._fullscreenVRpresenting = document.fullscreen;
  99688. }
  99689. else if (document.mozFullScreen !== undefined) {
  99690. _this._fullscreenVRpresenting = document.mozFullScreen;
  99691. }
  99692. else if (document.webkitIsFullScreen !== undefined) {
  99693. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  99694. }
  99695. else if (document.msIsFullScreen !== undefined) {
  99696. _this._fullscreenVRpresenting = document.msIsFullScreen;
  99697. }
  99698. else if (document.msFullscreenElement !== undefined) {
  99699. _this._fullscreenVRpresenting = document.msFullscreenElement;
  99700. }
  99701. if (!_this._fullscreenVRpresenting && _this._canvas) {
  99702. _this.exitVR();
  99703. if (!_this._useCustomVRButton) {
  99704. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  99705. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  99706. }
  99707. }
  99708. };
  99709. this.beforeRender = function () {
  99710. if (_this._leftController && _this._leftController._activePointer) {
  99711. _this._castRayAndSelectObject(_this._leftController);
  99712. }
  99713. if (_this._rightController && _this._rightController._activePointer) {
  99714. _this._castRayAndSelectObject(_this._rightController);
  99715. }
  99716. if (_this._noControllerIsActive) {
  99717. _this._castRayAndSelectObject(_this._cameraGazer);
  99718. }
  99719. else {
  99720. _this._cameraGazer._gazeTracker.isVisible = false;
  99721. }
  99722. };
  99723. this._onNewGamepadConnected = function (gamepad) {
  99724. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  99725. if (gamepad.leftStick) {
  99726. gamepad.onleftstickchanged(function (stickValues) {
  99727. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  99728. // Listening to classic/xbox gamepad only if no VR controller is active
  99729. if ((!_this._leftController && !_this._rightController) ||
  99730. ((_this._leftController && !_this._leftController._activePointer) &&
  99731. (_this._rightController && !_this._rightController._activePointer))) {
  99732. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  99733. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  99734. }
  99735. }
  99736. });
  99737. }
  99738. if (gamepad.rightStick) {
  99739. gamepad.onrightstickchanged(function (stickValues) {
  99740. if (_this._teleportationInitialized) {
  99741. _this._checkRotate(stickValues, _this._cameraGazer);
  99742. }
  99743. });
  99744. }
  99745. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  99746. gamepad.onbuttondown(function (buttonPressed) {
  99747. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  99748. _this._cameraGazer._selectionPointerDown();
  99749. }
  99750. });
  99751. gamepad.onbuttonup(function (buttonPressed) {
  99752. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  99753. _this._cameraGazer._selectionPointerUp();
  99754. }
  99755. });
  99756. }
  99757. }
  99758. else {
  99759. var webVRController = gamepad;
  99760. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  99761. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  99762. _this._rightController = controller;
  99763. }
  99764. else {
  99765. _this._leftController = controller;
  99766. }
  99767. _this._tryEnableInteractionOnController(controller);
  99768. }
  99769. };
  99770. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  99771. this._tryEnableInteractionOnController = function (controller) {
  99772. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  99773. _this._enableInteractionOnController(controller);
  99774. }
  99775. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  99776. _this._enableTeleportationOnController(controller);
  99777. }
  99778. };
  99779. this._onNewGamepadDisconnected = function (gamepad) {
  99780. if (gamepad instanceof BABYLON.WebVRController) {
  99781. if (gamepad.hand === "left" && _this._leftController != null) {
  99782. _this._leftController.dispose();
  99783. _this._leftController = null;
  99784. }
  99785. if (gamepad.hand === "right" && _this._rightController != null) {
  99786. _this._rightController.dispose();
  99787. _this._rightController = null;
  99788. }
  99789. }
  99790. };
  99791. this._workingVector = BABYLON.Vector3.Zero();
  99792. this._workingQuaternion = BABYLON.Quaternion.Identity();
  99793. this._workingMatrix = BABYLON.Matrix.Identity();
  99794. this._scene = scene;
  99795. this._canvas = scene.getEngine().getRenderingCanvas();
  99796. // Parse options
  99797. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  99798. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  99799. }
  99800. if (webVROptions.createDeviceOrientationCamera === undefined) {
  99801. webVROptions.createDeviceOrientationCamera = true;
  99802. }
  99803. if (webVROptions.laserToggle === undefined) {
  99804. webVROptions.laserToggle = true;
  99805. }
  99806. if (webVROptions.defaultHeight === undefined) {
  99807. webVROptions.defaultHeight = 1.7;
  99808. }
  99809. if (webVROptions.useCustomVRButton) {
  99810. this._useCustomVRButton = true;
  99811. if (webVROptions.customVRButton) {
  99812. this._btnVR = webVROptions.customVRButton;
  99813. }
  99814. }
  99815. if (webVROptions.rayLength) {
  99816. this._rayLength = webVROptions.rayLength;
  99817. }
  99818. this._defaultHeight = webVROptions.defaultHeight;
  99819. if (webVROptions.positionScale) {
  99820. this._rayLength *= webVROptions.positionScale;
  99821. this._defaultHeight *= webVROptions.positionScale;
  99822. }
  99823. this._hasEnteredVR = false;
  99824. // Set position
  99825. if (this._scene.activeCamera) {
  99826. this._position = this._scene.activeCamera.position.clone();
  99827. }
  99828. else {
  99829. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  99830. }
  99831. // Set non-vr camera
  99832. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  99833. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  99834. // Copy data from existing camera
  99835. if (this._scene.activeCamera) {
  99836. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  99837. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  99838. // Set rotation from previous camera
  99839. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  99840. var targetCamera = this._scene.activeCamera;
  99841. if (targetCamera.rotationQuaternion) {
  99842. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  99843. }
  99844. else {
  99845. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  99846. }
  99847. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  99848. }
  99849. }
  99850. this._scene.activeCamera = this._deviceOrientationCamera;
  99851. if (this._canvas) {
  99852. this._scene.activeCamera.attachControl(this._canvas);
  99853. }
  99854. }
  99855. else {
  99856. this._existingCamera = this._scene.activeCamera;
  99857. }
  99858. // Create VR cameras
  99859. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  99860. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  99861. }
  99862. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  99863. this._webVRCamera.useStandingMatrix();
  99864. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  99865. // Create default button
  99866. if (!this._useCustomVRButton) {
  99867. this._btnVR = document.createElement("BUTTON");
  99868. this._btnVR.className = "babylonVRicon";
  99869. this._btnVR.id = "babylonVRiconbtn";
  99870. this._btnVR.title = "Click to switch to VR";
  99871. 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) }";
  99872. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  99873. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  99874. // css += ".babylonVRicon.vrdisplaysupported { }";
  99875. // css += ".babylonVRicon.vrdisplayready { }";
  99876. // css += ".babylonVRicon.vrdisplayrequesting { }";
  99877. var style = document.createElement('style');
  99878. style.appendChild(document.createTextNode(css));
  99879. document.getElementsByTagName('head')[0].appendChild(style);
  99880. this.moveButtonToBottomRight();
  99881. }
  99882. // VR button click event
  99883. if (this._btnVR) {
  99884. this._btnVR.addEventListener("click", function () {
  99885. if (!_this.isInVRMode) {
  99886. _this.enterVR();
  99887. }
  99888. else {
  99889. _this.exitVR();
  99890. }
  99891. });
  99892. }
  99893. // Window events
  99894. window.addEventListener("resize", this._onResize);
  99895. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  99896. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  99897. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  99898. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  99899. document.onmsfullscreenchange = this._onFullscreenChange;
  99900. // Display vr button when headset is connected
  99901. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  99902. this.displayVRButton();
  99903. }
  99904. else {
  99905. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  99906. if (e.vrDisplay) {
  99907. _this.displayVRButton();
  99908. }
  99909. });
  99910. }
  99911. // Exiting VR mode using 'ESC' key on desktop
  99912. this._onKeyDown = function (event) {
  99913. if (event.keyCode === 27 && _this.isInVRMode) {
  99914. _this.exitVR();
  99915. }
  99916. };
  99917. document.addEventListener("keydown", this._onKeyDown);
  99918. // Exiting VR mode double tapping the touch screen
  99919. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  99920. if (_this.isInVRMode) {
  99921. _this.exitVR();
  99922. if (_this._fullscreenVRpresenting) {
  99923. _this._scene.getEngine().switchFullscreen(true);
  99924. }
  99925. }
  99926. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  99927. // Listen for WebVR display changes
  99928. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  99929. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  99930. this._onVRRequestPresentStart = function () {
  99931. _this._webVRrequesting = true;
  99932. _this.updateButtonVisibility();
  99933. };
  99934. this._onVRRequestPresentComplete = function (success) {
  99935. _this._webVRrequesting = false;
  99936. _this.updateButtonVisibility();
  99937. };
  99938. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  99939. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  99940. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  99941. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99942. scene.onDisposeObservable.add(function () {
  99943. _this.dispose();
  99944. });
  99945. // Gamepad connection events
  99946. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  99947. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  99948. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  99949. this.updateButtonVisibility();
  99950. //create easing functions
  99951. this._circleEase = new BABYLON.CircleEase();
  99952. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  99953. if (this.webVROptions.floorMeshes) {
  99954. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  99955. }
  99956. }
  99957. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  99958. /** Return this.onEnteringVRObservable
  99959. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  99960. */
  99961. get: function () {
  99962. return this.onEnteringVRObservable;
  99963. },
  99964. enumerable: true,
  99965. configurable: true
  99966. });
  99967. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  99968. /** Return this.onExitingVRObservable
  99969. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  99970. */
  99971. get: function () {
  99972. return this.onExitingVRObservable;
  99973. },
  99974. enumerable: true,
  99975. configurable: true
  99976. });
  99977. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  99978. /** Return this.onControllerMeshLoadedObservable
  99979. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  99980. */
  99981. get: function () {
  99982. return this.onControllerMeshLoadedObservable;
  99983. },
  99984. enumerable: true,
  99985. configurable: true
  99986. });
  99987. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  99988. /**
  99989. * The mesh used to display where the user is going to teleport.
  99990. */
  99991. get: function () {
  99992. return this._teleportationTarget;
  99993. },
  99994. /**
  99995. * Sets the mesh to be used to display where the user is going to teleport.
  99996. */
  99997. set: function (value) {
  99998. if (value) {
  99999. value.name = "teleportationTarget";
  100000. this._isDefaultTeleportationTarget = false;
  100001. this._teleportationTarget = value;
  100002. }
  100003. },
  100004. enumerable: true,
  100005. configurable: true
  100006. });
  100007. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  100008. /**
  100009. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  100010. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  100011. * See http://doc.babylonjs.com/resources/baking_transformations
  100012. */
  100013. get: function () {
  100014. return this._cameraGazer._gazeTracker;
  100015. },
  100016. set: function (value) {
  100017. if (value) {
  100018. // Dispose of existing meshes
  100019. if (this._cameraGazer._gazeTracker) {
  100020. this._cameraGazer._gazeTracker.dispose();
  100021. }
  100022. if (this._leftController && this._leftController._gazeTracker) {
  100023. this._leftController._gazeTracker.dispose();
  100024. }
  100025. if (this._rightController && this._rightController._gazeTracker) {
  100026. this._rightController._gazeTracker.dispose();
  100027. }
  100028. // Set and create gaze trackers on head and controllers
  100029. this._cameraGazer._gazeTracker = value;
  100030. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  100031. this._cameraGazer._gazeTracker.isPickable = false;
  100032. this._cameraGazer._gazeTracker.isVisible = false;
  100033. this._cameraGazer._gazeTracker.name = "gazeTracker";
  100034. if (this._leftController) {
  100035. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  100036. }
  100037. if (this._rightController) {
  100038. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  100039. }
  100040. }
  100041. },
  100042. enumerable: true,
  100043. configurable: true
  100044. });
  100045. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  100046. /**
  100047. * The gaze tracking mesh corresponding to the left controller
  100048. */
  100049. get: function () {
  100050. if (this._leftController) {
  100051. return this._leftController._gazeTracker;
  100052. }
  100053. return null;
  100054. },
  100055. enumerable: true,
  100056. configurable: true
  100057. });
  100058. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  100059. /**
  100060. * The gaze tracking mesh corresponding to the right controller
  100061. */
  100062. get: function () {
  100063. if (this._rightController) {
  100064. return this._rightController._gazeTracker;
  100065. }
  100066. return null;
  100067. },
  100068. enumerable: true,
  100069. configurable: true
  100070. });
  100071. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  100072. /**
  100073. * If the ray of the gaze should be displayed.
  100074. */
  100075. get: function () {
  100076. return this._displayGaze;
  100077. },
  100078. /**
  100079. * Sets if the ray of the gaze should be displayed.
  100080. */
  100081. set: function (value) {
  100082. this._displayGaze = value;
  100083. if (!value) {
  100084. this._cameraGazer._gazeTracker.isVisible = false;
  100085. if (this._leftController) {
  100086. this._leftController._gazeTracker.isVisible = false;
  100087. }
  100088. if (this._rightController) {
  100089. this._rightController._gazeTracker.isVisible = false;
  100090. }
  100091. }
  100092. },
  100093. enumerable: true,
  100094. configurable: true
  100095. });
  100096. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  100097. /**
  100098. * If the ray of the LaserPointer should be displayed.
  100099. */
  100100. get: function () {
  100101. return this._displayLaserPointer;
  100102. },
  100103. /**
  100104. * Sets if the ray of the LaserPointer should be displayed.
  100105. */
  100106. set: function (value) {
  100107. this._displayLaserPointer = value;
  100108. if (!value) {
  100109. if (this._rightController) {
  100110. this._rightController._deactivatePointer();
  100111. this._rightController._gazeTracker.isVisible = false;
  100112. }
  100113. if (this._leftController) {
  100114. this._leftController._deactivatePointer();
  100115. this._leftController._gazeTracker.isVisible = false;
  100116. }
  100117. }
  100118. else {
  100119. if (this._rightController) {
  100120. this._rightController._activatePointer();
  100121. }
  100122. if (this._leftController) {
  100123. this._leftController._activatePointer();
  100124. }
  100125. }
  100126. },
  100127. enumerable: true,
  100128. configurable: true
  100129. });
  100130. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  100131. /**
  100132. * The deviceOrientationCamera used as the camera when not in VR.
  100133. */
  100134. get: function () {
  100135. return this._deviceOrientationCamera;
  100136. },
  100137. enumerable: true,
  100138. configurable: true
  100139. });
  100140. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  100141. /**
  100142. * Based on the current WebVR support, returns the current VR camera used.
  100143. */
  100144. get: function () {
  100145. if (this._webVRready) {
  100146. return this._webVRCamera;
  100147. }
  100148. else {
  100149. return this._scene.activeCamera;
  100150. }
  100151. },
  100152. enumerable: true,
  100153. configurable: true
  100154. });
  100155. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  100156. /**
  100157. * The webVRCamera which is used when in VR.
  100158. */
  100159. get: function () {
  100160. return this._webVRCamera;
  100161. },
  100162. enumerable: true,
  100163. configurable: true
  100164. });
  100165. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  100166. /**
  100167. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  100168. */
  100169. get: function () {
  100170. return this._vrDeviceOrientationCamera;
  100171. },
  100172. enumerable: true,
  100173. configurable: true
  100174. });
  100175. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  100176. get: function () {
  100177. var result = this._cameraGazer._teleportationRequestInitiated
  100178. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  100179. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  100180. return result;
  100181. },
  100182. enumerable: true,
  100183. configurable: true
  100184. });
  100185. // Raised when one of the controller has loaded successfully its associated default mesh
  100186. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  100187. if (this._leftController && this._leftController.webVRController == webVRController) {
  100188. if (webVRController.mesh) {
  100189. this._leftController._setLaserPointerParent(webVRController.mesh);
  100190. }
  100191. }
  100192. if (this._rightController && this._rightController.webVRController == webVRController) {
  100193. if (webVRController.mesh) {
  100194. this._rightController._setLaserPointerParent(webVRController.mesh);
  100195. }
  100196. }
  100197. try {
  100198. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  100199. }
  100200. catch (err) {
  100201. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  100202. }
  100203. };
  100204. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  100205. /**
  100206. * Gets a value indicating if we are currently in VR mode.
  100207. */
  100208. get: function () {
  100209. return this._webVRpresenting || this._fullscreenVRpresenting;
  100210. },
  100211. enumerable: true,
  100212. configurable: true
  100213. });
  100214. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  100215. var vrDisplay = this._scene.getEngine().getVRDevice();
  100216. if (vrDisplay) {
  100217. var wasPresenting = this._webVRpresenting;
  100218. this._webVRpresenting = vrDisplay.isPresenting;
  100219. if (wasPresenting && !this._webVRpresenting)
  100220. this.exitVR();
  100221. }
  100222. else {
  100223. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  100224. }
  100225. this.updateButtonVisibility();
  100226. };
  100227. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  100228. this._webVRsupported = eventArgs.vrSupported;
  100229. this._webVRready = !!eventArgs.vrDisplay;
  100230. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  100231. this.updateButtonVisibility();
  100232. };
  100233. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  100234. if (this._canvas && !this._useCustomVRButton) {
  100235. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  100236. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  100237. }
  100238. };
  100239. VRExperienceHelper.prototype.displayVRButton = function () {
  100240. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  100241. document.body.appendChild(this._btnVR);
  100242. this._btnVRDisplayed = true;
  100243. }
  100244. };
  100245. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  100246. if (!this._btnVR || this._useCustomVRButton) {
  100247. return;
  100248. }
  100249. this._btnVR.className = "babylonVRicon";
  100250. if (this.isInVRMode) {
  100251. this._btnVR.className += " vrdisplaypresenting";
  100252. }
  100253. else {
  100254. if (this._webVRready)
  100255. this._btnVR.className += " vrdisplayready";
  100256. if (this._webVRsupported)
  100257. this._btnVR.className += " vrdisplaysupported";
  100258. if (this._webVRrequesting)
  100259. this._btnVR.className += " vrdisplayrequesting";
  100260. }
  100261. };
  100262. /**
  100263. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  100264. * Otherwise, will use the fullscreen API.
  100265. */
  100266. VRExperienceHelper.prototype.enterVR = function () {
  100267. if (this.onEnteringVRObservable) {
  100268. try {
  100269. this.onEnteringVRObservable.notifyObservers(this);
  100270. }
  100271. catch (err) {
  100272. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  100273. }
  100274. }
  100275. if (this._scene.activeCamera) {
  100276. this._position = this._scene.activeCamera.position.clone();
  100277. // make sure that we return to the last active camera
  100278. this._existingCamera = this._scene.activeCamera;
  100279. }
  100280. if (this._webVRrequesting)
  100281. return;
  100282. // If WebVR is supported and a headset is connected
  100283. if (this._webVRready) {
  100284. if (!this._webVRpresenting) {
  100285. this._webVRCamera.position = this._position;
  100286. this._scene.activeCamera = this._webVRCamera;
  100287. }
  100288. }
  100289. else if (this._vrDeviceOrientationCamera) {
  100290. this._vrDeviceOrientationCamera.position = this._position;
  100291. if (this._scene.activeCamera) {
  100292. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100293. }
  100294. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  100295. this._scene.getEngine().switchFullscreen(true);
  100296. this.updateButtonVisibility();
  100297. }
  100298. if (this._scene.activeCamera && this._canvas) {
  100299. this._scene.activeCamera.attachControl(this._canvas);
  100300. }
  100301. if (this._interactionsEnabled) {
  100302. this._scene.registerBeforeRender(this.beforeRender);
  100303. }
  100304. this._hasEnteredVR = true;
  100305. };
  100306. /**
  100307. * Attempt to exit VR, or fullscreen.
  100308. */
  100309. VRExperienceHelper.prototype.exitVR = function () {
  100310. if (this._hasEnteredVR) {
  100311. if (this.onExitingVRObservable) {
  100312. try {
  100313. this.onExitingVRObservable.notifyObservers(this);
  100314. }
  100315. catch (err) {
  100316. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  100317. }
  100318. }
  100319. if (this._webVRpresenting) {
  100320. this._scene.getEngine().disableVR();
  100321. }
  100322. if (this._scene.activeCamera) {
  100323. this._position = this._scene.activeCamera.position.clone();
  100324. }
  100325. if (this._deviceOrientationCamera) {
  100326. this._deviceOrientationCamera.position = this._position;
  100327. this._scene.activeCamera = this._deviceOrientationCamera;
  100328. if (this._canvas) {
  100329. this._scene.activeCamera.attachControl(this._canvas);
  100330. }
  100331. }
  100332. else if (this._existingCamera) {
  100333. this._existingCamera.position = this._position;
  100334. this._scene.activeCamera = this._existingCamera;
  100335. }
  100336. this.updateButtonVisibility();
  100337. if (this._interactionsEnabled) {
  100338. this._scene.unregisterBeforeRender(this.beforeRender);
  100339. this._cameraGazer._gazeTracker.isVisible = false;
  100340. if (this._leftController) {
  100341. this._leftController._gazeTracker.isVisible = false;
  100342. }
  100343. if (this._rightController) {
  100344. this._rightController._gazeTracker.isVisible = false;
  100345. }
  100346. }
  100347. // resize to update width and height when exiting vr exits fullscreen
  100348. this._scene.getEngine().resize();
  100349. this._hasEnteredVR = false;
  100350. }
  100351. };
  100352. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  100353. /**
  100354. * The position of the vr experience helper.
  100355. */
  100356. get: function () {
  100357. return this._position;
  100358. },
  100359. /**
  100360. * Sets the position of the vr experience helper.
  100361. */
  100362. set: function (value) {
  100363. this._position = value;
  100364. if (this._scene.activeCamera) {
  100365. this._scene.activeCamera.position = value;
  100366. }
  100367. },
  100368. enumerable: true,
  100369. configurable: true
  100370. });
  100371. /**
  100372. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  100373. */
  100374. VRExperienceHelper.prototype.enableInteractions = function () {
  100375. var _this = this;
  100376. if (!this._interactionsEnabled) {
  100377. this._interactionsRequested = true;
  100378. if (this._leftController) {
  100379. this._enableInteractionOnController(this._leftController);
  100380. }
  100381. if (this._rightController) {
  100382. this._enableInteractionOnController(this._rightController);
  100383. }
  100384. this.raySelectionPredicate = function (mesh) {
  100385. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  100386. };
  100387. this.meshSelectionPredicate = function (mesh) {
  100388. return true;
  100389. };
  100390. this._raySelectionPredicate = function (mesh) {
  100391. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  100392. && mesh.name.indexOf("teleportationTarget") === -1
  100393. && mesh.name.indexOf("torusTeleportation") === -1)) {
  100394. return _this.raySelectionPredicate(mesh);
  100395. }
  100396. return false;
  100397. };
  100398. this._interactionsEnabled = true;
  100399. }
  100400. };
  100401. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  100402. get: function () {
  100403. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  100404. },
  100405. enumerable: true,
  100406. configurable: true
  100407. });
  100408. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  100409. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  100410. if (this._floorMeshesCollection[i].id === mesh.id) {
  100411. return true;
  100412. }
  100413. }
  100414. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  100415. return true;
  100416. }
  100417. return false;
  100418. };
  100419. /**
  100420. * Adds a floor mesh to be used for teleportation.
  100421. * @param floorMesh the mesh to be used for teleportation.
  100422. */
  100423. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  100424. if (!this._floorMeshesCollection) {
  100425. return;
  100426. }
  100427. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  100428. return;
  100429. }
  100430. this._floorMeshesCollection.push(floorMesh);
  100431. };
  100432. /**
  100433. * Removes a floor mesh from being used for teleportation.
  100434. * @param floorMesh the mesh to be removed.
  100435. */
  100436. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  100437. if (!this._floorMeshesCollection) {
  100438. return;
  100439. }
  100440. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  100441. if (meshIndex !== -1) {
  100442. this._floorMeshesCollection.splice(meshIndex, 1);
  100443. }
  100444. };
  100445. /**
  100446. * Enables interactions and teleportation using the VR controllers and gaze.
  100447. * @param vrTeleportationOptions options to modify teleportation behavior.
  100448. */
  100449. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  100450. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  100451. if (!this._teleportationInitialized) {
  100452. this._teleportationRequested = true;
  100453. this.enableInteractions();
  100454. if (vrTeleportationOptions.floorMeshName) {
  100455. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  100456. }
  100457. if (vrTeleportationOptions.floorMeshes) {
  100458. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  100459. }
  100460. if (this._leftController != null) {
  100461. this._enableTeleportationOnController(this._leftController);
  100462. }
  100463. if (this._rightController != null) {
  100464. this._enableTeleportationOnController(this._rightController);
  100465. }
  100466. // Creates an image processing post process for the vignette not relying
  100467. // on the main scene configuration for image processing to reduce setup and spaces
  100468. // (gamma/linear) conflicts.
  100469. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  100470. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  100471. imageProcessingConfiguration.vignetteEnabled = true;
  100472. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  100473. this._webVRCamera.detachPostProcess(this._postProcessMove);
  100474. this._teleportationInitialized = true;
  100475. if (this._isDefaultTeleportationTarget) {
  100476. this._createTeleportationCircles();
  100477. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  100478. }
  100479. }
  100480. };
  100481. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  100482. var _this = this;
  100483. var controllerMesh = controller.webVRController.mesh;
  100484. if (controllerMesh) {
  100485. controller._interactionsEnabled = true;
  100486. controller._activatePointer();
  100487. if (this.webVROptions.laserToggle) {
  100488. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  100489. // Enabling / disabling laserPointer
  100490. if (_this._displayLaserPointer && stateObject.value === 1) {
  100491. if (controller._activePointer) {
  100492. controller._deactivatePointer();
  100493. }
  100494. else {
  100495. controller._activatePointer();
  100496. }
  100497. if (_this.displayGaze) {
  100498. controller._gazeTracker.isVisible = controller._activePointer;
  100499. }
  100500. }
  100501. });
  100502. }
  100503. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  100504. var gazer = controller;
  100505. if (_this._noControllerIsActive) {
  100506. gazer = _this._cameraGazer;
  100507. }
  100508. if (!gazer._pointerDownOnMeshAsked) {
  100509. if (stateObject.value > _this._padSensibilityUp) {
  100510. gazer._selectionPointerDown();
  100511. }
  100512. }
  100513. else if (stateObject.value < _this._padSensibilityDown) {
  100514. gazer._selectionPointerUp();
  100515. }
  100516. });
  100517. }
  100518. };
  100519. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  100520. // Dont teleport if another gaze already requested teleportation
  100521. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  100522. return;
  100523. }
  100524. if (!gazer._teleportationRequestInitiated) {
  100525. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  100526. gazer._activatePointer();
  100527. gazer._teleportationRequestInitiated = true;
  100528. }
  100529. }
  100530. else {
  100531. // Listening to the proper controller values changes to confirm teleportation
  100532. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  100533. if (this._teleportActive) {
  100534. this.teleportCamera(this._haloCenter);
  100535. }
  100536. gazer._teleportationRequestInitiated = false;
  100537. }
  100538. }
  100539. };
  100540. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  100541. // Only rotate when user is not currently selecting a teleportation location
  100542. if (gazer._teleportationRequestInitiated) {
  100543. return;
  100544. }
  100545. if (!gazer._rotationLeftAsked) {
  100546. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  100547. gazer._rotationLeftAsked = true;
  100548. if (this._rotationAllowed) {
  100549. this._rotateCamera(false);
  100550. }
  100551. }
  100552. }
  100553. else {
  100554. if (stateObject.x > -this._padSensibilityDown) {
  100555. gazer._rotationLeftAsked = false;
  100556. }
  100557. }
  100558. if (!gazer._rotationRightAsked) {
  100559. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  100560. gazer._rotationRightAsked = true;
  100561. if (this._rotationAllowed) {
  100562. this._rotateCamera(true);
  100563. }
  100564. }
  100565. }
  100566. else {
  100567. if (stateObject.x < this._padSensibilityDown) {
  100568. gazer._rotationRightAsked = false;
  100569. }
  100570. }
  100571. };
  100572. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  100573. // Only teleport backwards when user is not currently selecting a teleportation location
  100574. if (gazer._teleportationRequestInitiated) {
  100575. return;
  100576. }
  100577. // Teleport backwards
  100578. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  100579. if (!gazer._teleportationBackRequestInitiated) {
  100580. if (!this.currentVRCamera) {
  100581. return;
  100582. }
  100583. // Get rotation and position of the current camera
  100584. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  100585. var position = this.currentVRCamera.position;
  100586. // If the camera has device position, use that instead
  100587. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  100588. rotation = this.currentVRCamera.deviceRotationQuaternion;
  100589. position = this.currentVRCamera.devicePosition;
  100590. }
  100591. // Get matrix with only the y rotation of the device rotation
  100592. rotation.toEulerAnglesToRef(this._workingVector);
  100593. this._workingVector.z = 0;
  100594. this._workingVector.x = 0;
  100595. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  100596. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  100597. // Rotate backwards ray by device rotation to cast at the ground behind the user
  100598. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  100599. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  100600. var ray = new BABYLON.Ray(position, this._workingVector);
  100601. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  100602. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  100603. this.teleportCamera(hit.pickedPoint);
  100604. }
  100605. gazer._teleportationBackRequestInitiated = true;
  100606. }
  100607. }
  100608. else {
  100609. gazer._teleportationBackRequestInitiated = false;
  100610. }
  100611. };
  100612. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  100613. var _this = this;
  100614. var controllerMesh = controller.webVRController.mesh;
  100615. if (controllerMesh) {
  100616. if (!controller._interactionsEnabled) {
  100617. this._enableInteractionOnController(controller);
  100618. }
  100619. controller._interactionsEnabled = true;
  100620. controller._teleportationEnabled = true;
  100621. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100622. controller._dpadPressed = false;
  100623. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  100624. controller._dpadPressed = stateObject.pressed;
  100625. if (!controller._dpadPressed) {
  100626. controller._rotationLeftAsked = false;
  100627. controller._rotationRightAsked = false;
  100628. controller._teleportationBackRequestInitiated = false;
  100629. }
  100630. });
  100631. }
  100632. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  100633. if (_this.teleportationEnabled) {
  100634. _this._checkTeleportBackwards(stateObject, controller);
  100635. _this._checkTeleportWithRay(stateObject, controller);
  100636. }
  100637. _this._checkRotate(stateObject, controller);
  100638. });
  100639. }
  100640. };
  100641. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  100642. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  100643. this._teleportationTarget.isPickable = false;
  100644. var length = 512;
  100645. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  100646. dynamicTexture.hasAlpha = true;
  100647. var context = dynamicTexture.getContext();
  100648. var centerX = length / 2;
  100649. var centerY = length / 2;
  100650. var radius = 200;
  100651. context.beginPath();
  100652. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  100653. context.fillStyle = this._teleportationFillColor;
  100654. context.fill();
  100655. context.lineWidth = 10;
  100656. context.strokeStyle = this._teleportationBorderColor;
  100657. context.stroke();
  100658. context.closePath();
  100659. dynamicTexture.update();
  100660. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  100661. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  100662. this._teleportationTarget.material = teleportationCircleMaterial;
  100663. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  100664. torus.isPickable = false;
  100665. torus.parent = this._teleportationTarget;
  100666. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  100667. var keys = [];
  100668. keys.push({
  100669. frame: 0,
  100670. value: 0
  100671. });
  100672. keys.push({
  100673. frame: 30,
  100674. value: 0.4
  100675. });
  100676. keys.push({
  100677. frame: 60,
  100678. value: 0
  100679. });
  100680. animationInnerCircle.setKeys(keys);
  100681. var easingFunction = new BABYLON.SineEase();
  100682. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  100683. animationInnerCircle.setEasingFunction(easingFunction);
  100684. torus.animations = [];
  100685. torus.animations.push(animationInnerCircle);
  100686. this._scene.beginAnimation(torus, 0, 60, true);
  100687. this._hideTeleportationTarget();
  100688. };
  100689. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  100690. this._teleportActive = true;
  100691. if (this._teleportationInitialized) {
  100692. this._teleportationTarget.isVisible = true;
  100693. if (this._isDefaultTeleportationTarget) {
  100694. this._teleportationTarget.getChildren()[0].isVisible = true;
  100695. }
  100696. }
  100697. };
  100698. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  100699. this._teleportActive = false;
  100700. if (this._teleportationInitialized) {
  100701. this._teleportationTarget.isVisible = false;
  100702. if (this._isDefaultTeleportationTarget) {
  100703. this._teleportationTarget.getChildren()[0].isVisible = false;
  100704. }
  100705. }
  100706. };
  100707. VRExperienceHelper.prototype._rotateCamera = function (right) {
  100708. var _this = this;
  100709. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  100710. return;
  100711. }
  100712. if (right) {
  100713. this._rotationAngle++;
  100714. }
  100715. else {
  100716. this._rotationAngle--;
  100717. }
  100718. this.currentVRCamera.animations = [];
  100719. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  100720. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100721. var animationRotationKeys = [];
  100722. animationRotationKeys.push({
  100723. frame: 0,
  100724. value: this.currentVRCamera.rotationQuaternion
  100725. });
  100726. animationRotationKeys.push({
  100727. frame: 6,
  100728. value: target
  100729. });
  100730. animationRotation.setKeys(animationRotationKeys);
  100731. animationRotation.setEasingFunction(this._circleEase);
  100732. this.currentVRCamera.animations.push(animationRotation);
  100733. this._postProcessMove.animations = [];
  100734. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100735. var vignetteWeightKeys = [];
  100736. vignetteWeightKeys.push({
  100737. frame: 0,
  100738. value: 0
  100739. });
  100740. vignetteWeightKeys.push({
  100741. frame: 3,
  100742. value: 4
  100743. });
  100744. vignetteWeightKeys.push({
  100745. frame: 6,
  100746. value: 0
  100747. });
  100748. animationPP.setKeys(vignetteWeightKeys);
  100749. animationPP.setEasingFunction(this._circleEase);
  100750. this._postProcessMove.animations.push(animationPP);
  100751. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100752. var vignetteStretchKeys = [];
  100753. vignetteStretchKeys.push({
  100754. frame: 0,
  100755. value: 0
  100756. });
  100757. vignetteStretchKeys.push({
  100758. frame: 3,
  100759. value: 10
  100760. });
  100761. vignetteStretchKeys.push({
  100762. frame: 6,
  100763. value: 0
  100764. });
  100765. animationPP2.setKeys(vignetteStretchKeys);
  100766. animationPP2.setEasingFunction(this._circleEase);
  100767. this._postProcessMove.animations.push(animationPP2);
  100768. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  100769. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  100770. this._postProcessMove.samples = 4;
  100771. this._webVRCamera.attachPostProcess(this._postProcessMove);
  100772. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  100773. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  100774. });
  100775. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  100776. };
  100777. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  100778. if (hit.pickedPoint) {
  100779. if (gazer._teleportationRequestInitiated) {
  100780. this._displayTeleportationTarget();
  100781. this._haloCenter.copyFrom(hit.pickedPoint);
  100782. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  100783. }
  100784. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  100785. if (pickNormal) {
  100786. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  100787. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  100788. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  100789. }
  100790. this._teleportationTarget.position.y += 0.1;
  100791. }
  100792. };
  100793. /**
  100794. * Teleports the users feet to the desired location
  100795. * @param location The location where the user's feet should be placed
  100796. */
  100797. VRExperienceHelper.prototype.teleportCamera = function (location) {
  100798. var _this = this;
  100799. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  100800. return;
  100801. }
  100802. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  100803. // offset of the headset from the anchor.
  100804. if (this.webVRCamera.leftCamera) {
  100805. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  100806. this._workingVector.subtractInPlace(this.webVRCamera.position);
  100807. location.subtractToRef(this._workingVector, this._workingVector);
  100808. }
  100809. else {
  100810. this._workingVector.copyFrom(location);
  100811. }
  100812. // Add height to account for user's height offset
  100813. if (this.isInVRMode) {
  100814. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  100815. }
  100816. else {
  100817. this._workingVector.y += this._defaultHeight;
  100818. }
  100819. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  100820. // Create animation from the camera's position to the new location
  100821. this.currentVRCamera.animations = [];
  100822. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100823. var animationCameraTeleportationKeys = [{
  100824. frame: 0,
  100825. value: this.currentVRCamera.position
  100826. },
  100827. {
  100828. frame: 11,
  100829. value: this._workingVector
  100830. }
  100831. ];
  100832. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  100833. animationCameraTeleportation.setEasingFunction(this._circleEase);
  100834. this.currentVRCamera.animations.push(animationCameraTeleportation);
  100835. this._postProcessMove.animations = [];
  100836. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100837. var vignetteWeightKeys = [];
  100838. vignetteWeightKeys.push({
  100839. frame: 0,
  100840. value: 0
  100841. });
  100842. vignetteWeightKeys.push({
  100843. frame: 5,
  100844. value: 8
  100845. });
  100846. vignetteWeightKeys.push({
  100847. frame: 11,
  100848. value: 0
  100849. });
  100850. animationPP.setKeys(vignetteWeightKeys);
  100851. this._postProcessMove.animations.push(animationPP);
  100852. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100853. var vignetteStretchKeys = [];
  100854. vignetteStretchKeys.push({
  100855. frame: 0,
  100856. value: 0
  100857. });
  100858. vignetteStretchKeys.push({
  100859. frame: 5,
  100860. value: 10
  100861. });
  100862. vignetteStretchKeys.push({
  100863. frame: 11,
  100864. value: 0
  100865. });
  100866. animationPP2.setKeys(vignetteStretchKeys);
  100867. this._postProcessMove.animations.push(animationPP2);
  100868. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  100869. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  100870. this._webVRCamera.attachPostProcess(this._postProcessMove);
  100871. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  100872. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  100873. });
  100874. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  100875. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  100876. });
  100877. this._hideTeleportationTarget();
  100878. };
  100879. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  100880. if (normal) {
  100881. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  100882. if (angle < Math.PI / 2) {
  100883. normal.scaleInPlace(-1);
  100884. }
  100885. }
  100886. return normal;
  100887. };
  100888. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  100889. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  100890. return;
  100891. }
  100892. var ray = gazer._getForwardRay(this._rayLength);
  100893. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  100894. if (hit) {
  100895. // Populate the contrllers mesh that can be used for drag/drop
  100896. if (gazer._laserPointer) {
  100897. hit.originMesh = gazer._laserPointer.parent;
  100898. }
  100899. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  100900. }
  100901. gazer._currentHit = hit;
  100902. // Moving the gazeTracker on the mesh face targetted
  100903. if (hit && hit.pickedPoint) {
  100904. if (this._displayGaze) {
  100905. var multiplier = 1;
  100906. gazer._gazeTracker.isVisible = true;
  100907. if (gazer._isActionableMesh) {
  100908. multiplier = 3;
  100909. }
  100910. if (this.updateGazeTrackerScale) {
  100911. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  100912. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  100913. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  100914. }
  100915. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  100916. // To avoid z-fighting
  100917. var deltaFighting = 0.002;
  100918. if (pickNormal) {
  100919. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  100920. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  100921. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  100922. }
  100923. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  100924. if (gazer._gazeTracker.position.x < 0) {
  100925. gazer._gazeTracker.position.x += deltaFighting;
  100926. }
  100927. else {
  100928. gazer._gazeTracker.position.x -= deltaFighting;
  100929. }
  100930. if (gazer._gazeTracker.position.y < 0) {
  100931. gazer._gazeTracker.position.y += deltaFighting;
  100932. }
  100933. else {
  100934. gazer._gazeTracker.position.y -= deltaFighting;
  100935. }
  100936. if (gazer._gazeTracker.position.z < 0) {
  100937. gazer._gazeTracker.position.z += deltaFighting;
  100938. }
  100939. else {
  100940. gazer._gazeTracker.position.z -= deltaFighting;
  100941. }
  100942. }
  100943. // Changing the size of the laser pointer based on the distance from the targetted point
  100944. gazer._updatePointerDistance(hit.distance);
  100945. }
  100946. else {
  100947. gazer._updatePointerDistance();
  100948. gazer._gazeTracker.isVisible = false;
  100949. }
  100950. if (hit && hit.pickedMesh) {
  100951. // The object selected is the floor, we're in a teleportation scenario
  100952. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  100953. // Moving the teleportation area to this targetted point
  100954. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  100955. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  100956. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  100957. }
  100958. gazer._currentMeshSelected = null;
  100959. if (gazer._teleportationRequestInitiated) {
  100960. this._moveTeleportationSelectorTo(hit, gazer, ray);
  100961. }
  100962. return;
  100963. }
  100964. // If not, we're in a selection scenario
  100965. //this._teleportationAllowed = false;
  100966. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  100967. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  100968. this.onNewMeshPicked.notifyObservers(hit);
  100969. gazer._currentMeshSelected = hit.pickedMesh;
  100970. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  100971. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  100972. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  100973. gazer._isActionableMesh = true;
  100974. }
  100975. else {
  100976. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100977. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100978. gazer._isActionableMesh = false;
  100979. }
  100980. try {
  100981. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  100982. }
  100983. catch (err) {
  100984. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  100985. }
  100986. }
  100987. else {
  100988. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  100989. gazer._currentMeshSelected = null;
  100990. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100991. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100992. }
  100993. }
  100994. }
  100995. else {
  100996. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  100997. gazer._currentMeshSelected = null;
  100998. //this._teleportationAllowed = false;
  100999. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101000. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101001. }
  101002. };
  101003. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  101004. if (mesh) {
  101005. this.onSelectedMeshUnselected.notifyObservers(mesh);
  101006. }
  101007. };
  101008. /**
  101009. * Sets the color of the laser ray from the vr controllers.
  101010. * @param color new color for the ray.
  101011. */
  101012. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  101013. if (this._leftController) {
  101014. this._leftController._setLaserPointerColor(color);
  101015. }
  101016. if (this._rightController) {
  101017. this._rightController._setLaserPointerColor(color);
  101018. }
  101019. };
  101020. /**
  101021. * Sets the color of the ray from the vr headsets gaze.
  101022. * @param color new color for the ray.
  101023. */
  101024. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  101025. if (!this._cameraGazer._gazeTracker.material) {
  101026. return;
  101027. }
  101028. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  101029. if (this._leftController) {
  101030. this._leftController._gazeTracker.material.emissiveColor = color;
  101031. }
  101032. if (this._rightController) {
  101033. this._rightController._gazeTracker.material.emissiveColor = color;
  101034. }
  101035. };
  101036. /**
  101037. * Exits VR and disposes of the vr experience helper
  101038. */
  101039. VRExperienceHelper.prototype.dispose = function () {
  101040. if (this.isInVRMode) {
  101041. this.exitVR();
  101042. }
  101043. if (this._postProcessMove) {
  101044. this._postProcessMove.dispose();
  101045. }
  101046. if (this._webVRCamera) {
  101047. this._webVRCamera.dispose();
  101048. }
  101049. if (this._vrDeviceOrientationCamera) {
  101050. this._vrDeviceOrientationCamera.dispose();
  101051. }
  101052. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  101053. document.body.removeChild(this._btnVR);
  101054. }
  101055. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  101056. this._deviceOrientationCamera.dispose();
  101057. }
  101058. if (this._cameraGazer) {
  101059. this._cameraGazer.dispose();
  101060. }
  101061. if (this._leftController) {
  101062. this._leftController.dispose();
  101063. }
  101064. if (this._rightController) {
  101065. this._rightController.dispose();
  101066. }
  101067. if (this._teleportationTarget) {
  101068. this._teleportationTarget.dispose();
  101069. }
  101070. this._floorMeshesCollection = [];
  101071. document.removeEventListener("keydown", this._onKeyDown);
  101072. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101073. window.removeEventListener("resize", this._onResize);
  101074. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  101075. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  101076. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  101077. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  101078. document.onmsfullscreenchange = null;
  101079. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  101080. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  101081. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  101082. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101083. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  101084. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  101085. this._scene.unregisterBeforeRender(this.beforeRender);
  101086. };
  101087. /**
  101088. * Gets the name of the VRExperienceHelper class
  101089. * @returns "VRExperienceHelper"
  101090. */
  101091. VRExperienceHelper.prototype.getClassName = function () {
  101092. return "VRExperienceHelper";
  101093. };
  101094. return VRExperienceHelper;
  101095. }());
  101096. BABYLON.VRExperienceHelper = VRExperienceHelper;
  101097. })(BABYLON || (BABYLON = {}));
  101098. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  101099. // Mainly based on these 2 articles :
  101100. // 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
  101101. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  101102. var BABYLON;
  101103. (function (BABYLON) {
  101104. /**
  101105. * Defines the potential axis of a Joystick
  101106. */
  101107. var JoystickAxis;
  101108. (function (JoystickAxis) {
  101109. /** X axis */
  101110. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  101111. /** Y axis */
  101112. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  101113. /** Z axis */
  101114. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  101115. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  101116. /**
  101117. * Class used to define virtual joystick (used in touch mode)
  101118. */
  101119. var VirtualJoystick = /** @class */ (function () {
  101120. /**
  101121. * Creates a new virtual joystick
  101122. * @param leftJoystick defines that the joystick is for left hand (false by default)
  101123. */
  101124. function VirtualJoystick(leftJoystick) {
  101125. var _this = this;
  101126. if (leftJoystick) {
  101127. this._leftJoystick = true;
  101128. }
  101129. else {
  101130. this._leftJoystick = false;
  101131. }
  101132. VirtualJoystick._globalJoystickIndex++;
  101133. // By default left & right arrow keys are moving the X
  101134. // and up & down keys are moving the Y
  101135. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  101136. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  101137. this.reverseLeftRight = false;
  101138. this.reverseUpDown = false;
  101139. // collections of pointers
  101140. this._touches = new BABYLON.StringDictionary();
  101141. this.deltaPosition = BABYLON.Vector3.Zero();
  101142. this._joystickSensibility = 25;
  101143. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  101144. this._onResize = function (evt) {
  101145. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  101146. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  101147. if (VirtualJoystick.vjCanvas) {
  101148. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  101149. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  101150. }
  101151. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  101152. };
  101153. // injecting a canvas element on top of the canvas 3D game
  101154. if (!VirtualJoystick.vjCanvas) {
  101155. window.addEventListener("resize", this._onResize, false);
  101156. VirtualJoystick.vjCanvas = document.createElement("canvas");
  101157. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  101158. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  101159. VirtualJoystick.vjCanvas.width = window.innerWidth;
  101160. VirtualJoystick.vjCanvas.height = window.innerHeight;
  101161. VirtualJoystick.vjCanvas.style.width = "100%";
  101162. VirtualJoystick.vjCanvas.style.height = "100%";
  101163. VirtualJoystick.vjCanvas.style.position = "absolute";
  101164. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  101165. VirtualJoystick.vjCanvas.style.top = "0px";
  101166. VirtualJoystick.vjCanvas.style.left = "0px";
  101167. VirtualJoystick.vjCanvas.style.zIndex = "5";
  101168. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  101169. // Support for jQuery PEP polyfill
  101170. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  101171. var context = VirtualJoystick.vjCanvas.getContext('2d');
  101172. if (!context) {
  101173. throw new Error("Unable to create canvas for virtual joystick");
  101174. }
  101175. VirtualJoystick.vjCanvasContext = context;
  101176. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  101177. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  101178. document.body.appendChild(VirtualJoystick.vjCanvas);
  101179. }
  101180. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  101181. this.pressed = false;
  101182. // default joystick color
  101183. this._joystickColor = "cyan";
  101184. this._joystickPointerID = -1;
  101185. // current joystick position
  101186. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  101187. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  101188. // origin joystick position
  101189. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  101190. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  101191. this._onPointerDownHandlerRef = function (evt) {
  101192. _this._onPointerDown(evt);
  101193. };
  101194. this._onPointerMoveHandlerRef = function (evt) {
  101195. _this._onPointerMove(evt);
  101196. };
  101197. this._onPointerUpHandlerRef = function (evt) {
  101198. _this._onPointerUp(evt);
  101199. };
  101200. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  101201. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  101202. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  101203. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  101204. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  101205. evt.preventDefault(); // Disables system menu
  101206. }, false);
  101207. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  101208. }
  101209. /**
  101210. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  101211. * @param newJoystickSensibility defines the new sensibility
  101212. */
  101213. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  101214. this._joystickSensibility = newJoystickSensibility;
  101215. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  101216. };
  101217. VirtualJoystick.prototype._onPointerDown = function (e) {
  101218. var positionOnScreenCondition;
  101219. e.preventDefault();
  101220. if (this._leftJoystick === true) {
  101221. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  101222. }
  101223. else {
  101224. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  101225. }
  101226. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  101227. // First contact will be dedicated to the virtual joystick
  101228. this._joystickPointerID = e.pointerId;
  101229. this._joystickPointerStartPos.x = e.clientX;
  101230. this._joystickPointerStartPos.y = e.clientY;
  101231. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  101232. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  101233. this._deltaJoystickVector.x = 0;
  101234. this._deltaJoystickVector.y = 0;
  101235. this.pressed = true;
  101236. this._touches.add(e.pointerId.toString(), e);
  101237. }
  101238. else {
  101239. // You can only trigger the action buttons with a joystick declared
  101240. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  101241. this._action();
  101242. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  101243. }
  101244. }
  101245. };
  101246. VirtualJoystick.prototype._onPointerMove = function (e) {
  101247. // If the current pointer is the one associated to the joystick (first touch contact)
  101248. if (this._joystickPointerID == e.pointerId) {
  101249. this._joystickPointerPos.x = e.clientX;
  101250. this._joystickPointerPos.y = e.clientY;
  101251. this._deltaJoystickVector = this._joystickPointerPos.clone();
  101252. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  101253. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  101254. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  101255. switch (this._axisTargetedByLeftAndRight) {
  101256. case JoystickAxis.X:
  101257. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  101258. break;
  101259. case JoystickAxis.Y:
  101260. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  101261. break;
  101262. case JoystickAxis.Z:
  101263. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  101264. break;
  101265. }
  101266. var directionUpDown = this.reverseUpDown ? 1 : -1;
  101267. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  101268. switch (this._axisTargetedByUpAndDown) {
  101269. case JoystickAxis.X:
  101270. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  101271. break;
  101272. case JoystickAxis.Y:
  101273. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  101274. break;
  101275. case JoystickAxis.Z:
  101276. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  101277. break;
  101278. }
  101279. }
  101280. else {
  101281. var data = this._touches.get(e.pointerId.toString());
  101282. if (data) {
  101283. data.x = e.clientX;
  101284. data.y = e.clientY;
  101285. }
  101286. }
  101287. };
  101288. VirtualJoystick.prototype._onPointerUp = function (e) {
  101289. if (this._joystickPointerID == e.pointerId) {
  101290. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  101291. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  101292. this._joystickPointerID = -1;
  101293. this.pressed = false;
  101294. }
  101295. else {
  101296. var touch = this._touches.get(e.pointerId.toString());
  101297. if (touch) {
  101298. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  101299. }
  101300. }
  101301. this._deltaJoystickVector.x = 0;
  101302. this._deltaJoystickVector.y = 0;
  101303. this._touches.remove(e.pointerId.toString());
  101304. };
  101305. /**
  101306. * Change the color of the virtual joystick
  101307. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  101308. */
  101309. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  101310. this._joystickColor = newColor;
  101311. };
  101312. /**
  101313. * Defines a callback to call when the joystick is touched
  101314. * @param action defines the callback
  101315. */
  101316. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  101317. this._action = action;
  101318. };
  101319. /**
  101320. * Defines which axis you'd like to control for left & right
  101321. * @param axis defines the axis to use
  101322. */
  101323. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  101324. switch (axis) {
  101325. case JoystickAxis.X:
  101326. case JoystickAxis.Y:
  101327. case JoystickAxis.Z:
  101328. this._axisTargetedByLeftAndRight = axis;
  101329. break;
  101330. default:
  101331. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  101332. break;
  101333. }
  101334. };
  101335. /**
  101336. * Defines which axis you'd like to control for up & down
  101337. * @param axis defines the axis to use
  101338. */
  101339. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  101340. switch (axis) {
  101341. case JoystickAxis.X:
  101342. case JoystickAxis.Y:
  101343. case JoystickAxis.Z:
  101344. this._axisTargetedByUpAndDown = axis;
  101345. break;
  101346. default:
  101347. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  101348. break;
  101349. }
  101350. };
  101351. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  101352. var _this = this;
  101353. if (this.pressed) {
  101354. this._touches.forEach(function (key, touch) {
  101355. if (touch.pointerId === _this._joystickPointerID) {
  101356. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  101357. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  101358. VirtualJoystick.vjCanvasContext.beginPath();
  101359. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  101360. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101361. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  101362. VirtualJoystick.vjCanvasContext.stroke();
  101363. VirtualJoystick.vjCanvasContext.closePath();
  101364. VirtualJoystick.vjCanvasContext.beginPath();
  101365. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101366. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  101367. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  101368. VirtualJoystick.vjCanvasContext.stroke();
  101369. VirtualJoystick.vjCanvasContext.closePath();
  101370. VirtualJoystick.vjCanvasContext.beginPath();
  101371. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101372. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  101373. VirtualJoystick.vjCanvasContext.stroke();
  101374. VirtualJoystick.vjCanvasContext.closePath();
  101375. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  101376. }
  101377. else {
  101378. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  101379. VirtualJoystick.vjCanvasContext.beginPath();
  101380. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  101381. VirtualJoystick.vjCanvasContext.beginPath();
  101382. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  101383. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  101384. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  101385. VirtualJoystick.vjCanvasContext.stroke();
  101386. VirtualJoystick.vjCanvasContext.closePath();
  101387. touch.prevX = touch.x;
  101388. touch.prevY = touch.y;
  101389. }
  101390. ;
  101391. });
  101392. }
  101393. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  101394. };
  101395. /**
  101396. * Release internal HTML canvas
  101397. */
  101398. VirtualJoystick.prototype.releaseCanvas = function () {
  101399. if (VirtualJoystick.vjCanvas) {
  101400. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  101401. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  101402. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  101403. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  101404. window.removeEventListener("resize", this._onResize);
  101405. document.body.removeChild(VirtualJoystick.vjCanvas);
  101406. VirtualJoystick.vjCanvas = null;
  101407. }
  101408. };
  101409. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  101410. VirtualJoystick._globalJoystickIndex = 0;
  101411. return VirtualJoystick;
  101412. }());
  101413. BABYLON.VirtualJoystick = VirtualJoystick;
  101414. })(BABYLON || (BABYLON = {}));
  101415. //# sourceMappingURL=babylon.virtualJoystick.js.map
  101416. var BABYLON;
  101417. (function (BABYLON) {
  101418. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  101419. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  101420. });
  101421. /**
  101422. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  101423. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  101424. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  101425. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  101426. */
  101427. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  101428. __extends(VirtualJoysticksCamera, _super);
  101429. /**
  101430. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  101431. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  101432. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  101433. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  101434. * @param name Define the name of the camera in the scene
  101435. * @param position Define the start position of the camera in the scene
  101436. * @param scene Define the scene the camera belongs to
  101437. */
  101438. function VirtualJoysticksCamera(name, position, scene) {
  101439. var _this = _super.call(this, name, position, scene) || this;
  101440. _this.inputs.addVirtualJoystick();
  101441. return _this;
  101442. }
  101443. /**
  101444. * Gets the current object class name.
  101445. * @return the class name
  101446. */
  101447. VirtualJoysticksCamera.prototype.getClassName = function () {
  101448. return "VirtualJoysticksCamera";
  101449. };
  101450. return VirtualJoysticksCamera;
  101451. }(BABYLON.FreeCamera));
  101452. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  101453. })(BABYLON || (BABYLON = {}));
  101454. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  101455. var BABYLON;
  101456. (function (BABYLON) {
  101457. /**
  101458. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  101459. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101460. */
  101461. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  101462. function FreeCameraVirtualJoystickInput() {
  101463. }
  101464. /**
  101465. * Gets the left stick of the virtual joystick.
  101466. * @returns The virtual Joystick
  101467. */
  101468. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  101469. return this._leftjoystick;
  101470. };
  101471. /**
  101472. * Gets the right stick of the virtual joystick.
  101473. * @returns The virtual Joystick
  101474. */
  101475. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  101476. return this._rightjoystick;
  101477. };
  101478. /**
  101479. * Update the current camera state depending on the inputs that have been used this frame.
  101480. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101481. */
  101482. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  101483. if (this._leftjoystick) {
  101484. var camera = this.camera;
  101485. var speed = camera._computeLocalCameraSpeed() * 50;
  101486. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  101487. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  101488. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  101489. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  101490. if (!this._leftjoystick.pressed) {
  101491. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  101492. }
  101493. if (!this._rightjoystick.pressed) {
  101494. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  101495. }
  101496. }
  101497. };
  101498. /**
  101499. * Attach the input controls to a specific dom element to get the input from.
  101500. * @param element Defines the element the controls should be listened from
  101501. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101502. */
  101503. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  101504. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  101505. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  101506. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  101507. this._leftjoystick.setJoystickSensibility(0.15);
  101508. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  101509. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  101510. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  101511. this._rightjoystick.reverseUpDown = true;
  101512. this._rightjoystick.setJoystickSensibility(0.05);
  101513. this._rightjoystick.setJoystickColor("yellow");
  101514. };
  101515. /**
  101516. * Detach the current controls from the specified dom element.
  101517. * @param element Defines the element to stop listening the inputs from
  101518. */
  101519. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  101520. this._leftjoystick.releaseCanvas();
  101521. this._rightjoystick.releaseCanvas();
  101522. };
  101523. /**
  101524. * Gets the class name of the current intput.
  101525. * @returns the class name
  101526. */
  101527. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  101528. return "FreeCameraVirtualJoystickInput";
  101529. };
  101530. /**
  101531. * Get the friendly name associated with the input class.
  101532. * @returns the input friendly name
  101533. */
  101534. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  101535. return "virtualJoystick";
  101536. };
  101537. return FreeCameraVirtualJoystickInput;
  101538. }());
  101539. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  101540. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  101541. })(BABYLON || (BABYLON = {}));
  101542. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  101543. var BABYLON;
  101544. (function (BABYLON) {
  101545. var SimplificationSettings = /** @class */ (function () {
  101546. function SimplificationSettings(quality, distance, optimizeMesh) {
  101547. this.quality = quality;
  101548. this.distance = distance;
  101549. this.optimizeMesh = optimizeMesh;
  101550. }
  101551. return SimplificationSettings;
  101552. }());
  101553. BABYLON.SimplificationSettings = SimplificationSettings;
  101554. var SimplificationQueue = /** @class */ (function () {
  101555. function SimplificationQueue() {
  101556. this.running = false;
  101557. this._simplificationArray = [];
  101558. }
  101559. SimplificationQueue.prototype.addTask = function (task) {
  101560. this._simplificationArray.push(task);
  101561. };
  101562. SimplificationQueue.prototype.executeNext = function () {
  101563. var task = this._simplificationArray.pop();
  101564. if (task) {
  101565. this.running = true;
  101566. this.runSimplification(task);
  101567. }
  101568. else {
  101569. this.running = false;
  101570. }
  101571. };
  101572. SimplificationQueue.prototype.runSimplification = function (task) {
  101573. var _this = this;
  101574. if (task.parallelProcessing) {
  101575. //parallel simplifier
  101576. task.settings.forEach(function (setting) {
  101577. var simplifier = _this.getSimplifier(task);
  101578. simplifier.simplify(setting, function (newMesh) {
  101579. task.mesh.addLODLevel(setting.distance, newMesh);
  101580. newMesh.isVisible = true;
  101581. //check if it is the last
  101582. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  101583. //all done, run the success callback.
  101584. task.successCallback();
  101585. }
  101586. _this.executeNext();
  101587. });
  101588. });
  101589. }
  101590. else {
  101591. //single simplifier.
  101592. var simplifier = this.getSimplifier(task);
  101593. var runDecimation = function (setting, callback) {
  101594. simplifier.simplify(setting, function (newMesh) {
  101595. task.mesh.addLODLevel(setting.distance, newMesh);
  101596. newMesh.isVisible = true;
  101597. //run the next quality level
  101598. callback();
  101599. });
  101600. };
  101601. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  101602. runDecimation(task.settings[loop.index], function () {
  101603. loop.executeNext();
  101604. });
  101605. }, function () {
  101606. //execution ended, run the success callback.
  101607. if (task.successCallback) {
  101608. task.successCallback();
  101609. }
  101610. _this.executeNext();
  101611. });
  101612. }
  101613. };
  101614. SimplificationQueue.prototype.getSimplifier = function (task) {
  101615. switch (task.simplificationType) {
  101616. case SimplificationType.QUADRATIC:
  101617. default:
  101618. return new QuadraticErrorSimplification(task.mesh);
  101619. }
  101620. };
  101621. return SimplificationQueue;
  101622. }());
  101623. BABYLON.SimplificationQueue = SimplificationQueue;
  101624. /**
  101625. * The implemented types of simplification
  101626. * At the moment only Quadratic Error Decimation is implemented
  101627. */
  101628. var SimplificationType;
  101629. (function (SimplificationType) {
  101630. /** Quadratic error decimation */
  101631. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  101632. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  101633. var DecimationTriangle = /** @class */ (function () {
  101634. function DecimationTriangle(vertices) {
  101635. this.vertices = vertices;
  101636. this.error = new Array(4);
  101637. this.deleted = false;
  101638. this.isDirty = false;
  101639. this.deletePending = false;
  101640. this.borderFactor = 0;
  101641. }
  101642. return DecimationTriangle;
  101643. }());
  101644. BABYLON.DecimationTriangle = DecimationTriangle;
  101645. var DecimationVertex = /** @class */ (function () {
  101646. function DecimationVertex(position, id) {
  101647. this.position = position;
  101648. this.id = id;
  101649. this.isBorder = true;
  101650. this.q = new QuadraticMatrix();
  101651. this.triangleCount = 0;
  101652. this.triangleStart = 0;
  101653. this.originalOffsets = [];
  101654. }
  101655. DecimationVertex.prototype.updatePosition = function (newPosition) {
  101656. this.position.copyFrom(newPosition);
  101657. };
  101658. return DecimationVertex;
  101659. }());
  101660. BABYLON.DecimationVertex = DecimationVertex;
  101661. var QuadraticMatrix = /** @class */ (function () {
  101662. function QuadraticMatrix(data) {
  101663. this.data = new Array(10);
  101664. for (var i = 0; i < 10; ++i) {
  101665. if (data && data[i]) {
  101666. this.data[i] = data[i];
  101667. }
  101668. else {
  101669. this.data[i] = 0;
  101670. }
  101671. }
  101672. }
  101673. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  101674. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  101675. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  101676. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  101677. return det;
  101678. };
  101679. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  101680. for (var i = 0; i < 10; ++i) {
  101681. this.data[i] += matrix.data[i];
  101682. }
  101683. };
  101684. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  101685. for (var i = 0; i < 10; ++i) {
  101686. this.data[i] += data[i];
  101687. }
  101688. };
  101689. QuadraticMatrix.prototype.add = function (matrix) {
  101690. var m = new QuadraticMatrix();
  101691. for (var i = 0; i < 10; ++i) {
  101692. m.data[i] = this.data[i] + matrix.data[i];
  101693. }
  101694. return m;
  101695. };
  101696. QuadraticMatrix.FromData = function (a, b, c, d) {
  101697. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  101698. };
  101699. //returning an array to avoid garbage collection
  101700. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  101701. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  101702. };
  101703. return QuadraticMatrix;
  101704. }());
  101705. BABYLON.QuadraticMatrix = QuadraticMatrix;
  101706. var Reference = /** @class */ (function () {
  101707. function Reference(vertexId, triangleId) {
  101708. this.vertexId = vertexId;
  101709. this.triangleId = triangleId;
  101710. }
  101711. return Reference;
  101712. }());
  101713. BABYLON.Reference = Reference;
  101714. /**
  101715. * An implementation of the Quadratic Error simplification algorithm.
  101716. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  101717. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  101718. * @author RaananW
  101719. */
  101720. var QuadraticErrorSimplification = /** @class */ (function () {
  101721. function QuadraticErrorSimplification(_mesh) {
  101722. this._mesh = _mesh;
  101723. this.syncIterations = 5000;
  101724. this.aggressiveness = 7;
  101725. this.decimationIterations = 100;
  101726. this.boundingBoxEpsilon = BABYLON.Epsilon;
  101727. }
  101728. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  101729. var _this = this;
  101730. this.initDecimatedMesh();
  101731. //iterating through the submeshes array, one after the other.
  101732. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  101733. _this.initWithMesh(loop.index, function () {
  101734. _this.runDecimation(settings, loop.index, function () {
  101735. loop.executeNext();
  101736. });
  101737. }, settings.optimizeMesh);
  101738. }, function () {
  101739. setTimeout(function () {
  101740. successCallback(_this._reconstructedMesh);
  101741. }, 0);
  101742. });
  101743. };
  101744. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  101745. var _this = this;
  101746. var targetCount = ~~(this.triangles.length * settings.quality);
  101747. var deletedTriangles = 0;
  101748. var triangleCount = this.triangles.length;
  101749. var iterationFunction = function (iteration, callback) {
  101750. setTimeout(function () {
  101751. if (iteration % 5 === 0) {
  101752. _this.updateMesh(iteration === 0);
  101753. }
  101754. for (var i = 0; i < _this.triangles.length; ++i) {
  101755. _this.triangles[i].isDirty = false;
  101756. }
  101757. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  101758. var trianglesIterator = function (i) {
  101759. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  101760. var t = _this.triangles[tIdx];
  101761. if (!t)
  101762. return;
  101763. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  101764. return;
  101765. }
  101766. for (var j = 0; j < 3; ++j) {
  101767. if (t.error[j] < threshold) {
  101768. var deleted0 = [];
  101769. var deleted1 = [];
  101770. var v0 = t.vertices[j];
  101771. var v1 = t.vertices[(j + 1) % 3];
  101772. if (v0.isBorder || v1.isBorder)
  101773. continue;
  101774. var p = BABYLON.Vector3.Zero();
  101775. var n = BABYLON.Vector3.Zero();
  101776. var uv = BABYLON.Vector2.Zero();
  101777. var color = new BABYLON.Color4(0, 0, 0, 1);
  101778. _this.calculateError(v0, v1, p, n, uv, color);
  101779. var delTr = new Array();
  101780. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  101781. continue;
  101782. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  101783. continue;
  101784. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  101785. continue;
  101786. var uniqueArray = new Array();
  101787. delTr.forEach(function (deletedT) {
  101788. if (uniqueArray.indexOf(deletedT) === -1) {
  101789. deletedT.deletePending = true;
  101790. uniqueArray.push(deletedT);
  101791. }
  101792. });
  101793. if (uniqueArray.length % 2 !== 0) {
  101794. continue;
  101795. }
  101796. v0.q = v1.q.add(v0.q);
  101797. v0.updatePosition(p);
  101798. var tStart = _this.references.length;
  101799. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  101800. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  101801. var tCount = _this.references.length - tStart;
  101802. if (tCount <= v0.triangleCount) {
  101803. if (tCount) {
  101804. for (var c = 0; c < tCount; c++) {
  101805. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  101806. }
  101807. }
  101808. }
  101809. else {
  101810. v0.triangleStart = tStart;
  101811. }
  101812. v0.triangleCount = tCount;
  101813. break;
  101814. }
  101815. }
  101816. };
  101817. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  101818. }, 0);
  101819. };
  101820. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  101821. if (triangleCount - deletedTriangles <= targetCount)
  101822. loop.breakLoop();
  101823. else {
  101824. iterationFunction(loop.index, function () {
  101825. loop.executeNext();
  101826. });
  101827. }
  101828. }, function () {
  101829. setTimeout(function () {
  101830. //reconstruct this part of the mesh
  101831. _this.reconstructMesh(submeshIndex);
  101832. successCallback();
  101833. }, 0);
  101834. });
  101835. };
  101836. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  101837. var _this = this;
  101838. this.vertices = [];
  101839. this.triangles = [];
  101840. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101841. var indices = this._mesh.getIndices();
  101842. var submesh = this._mesh.subMeshes[submeshIndex];
  101843. var findInVertices = function (positionToSearch) {
  101844. if (optimizeMesh) {
  101845. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  101846. if (_this.vertices[ii].position.equals(positionToSearch)) {
  101847. return _this.vertices[ii];
  101848. }
  101849. }
  101850. }
  101851. return null;
  101852. };
  101853. var vertexReferences = [];
  101854. var vertexInit = function (i) {
  101855. if (!positionData) {
  101856. return;
  101857. }
  101858. var offset = i + submesh.verticesStart;
  101859. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  101860. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  101861. vertex.originalOffsets.push(offset);
  101862. if (vertex.id === _this.vertices.length) {
  101863. _this.vertices.push(vertex);
  101864. }
  101865. vertexReferences.push(vertex.id);
  101866. };
  101867. //var totalVertices = mesh.getTotalVertices();
  101868. var totalVertices = submesh.verticesCount;
  101869. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  101870. var indicesInit = function (i) {
  101871. if (!indices) {
  101872. return;
  101873. }
  101874. var offset = (submesh.indexStart / 3) + i;
  101875. var pos = (offset * 3);
  101876. var i0 = indices[pos + 0];
  101877. var i1 = indices[pos + 1];
  101878. var i2 = indices[pos + 2];
  101879. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  101880. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  101881. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  101882. var triangle = new DecimationTriangle([v0, v1, v2]);
  101883. triangle.originalOffset = pos;
  101884. _this.triangles.push(triangle);
  101885. };
  101886. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  101887. _this.init(callback);
  101888. });
  101889. });
  101890. };
  101891. QuadraticErrorSimplification.prototype.init = function (callback) {
  101892. var _this = this;
  101893. var triangleInit1 = function (i) {
  101894. var t = _this.triangles[i];
  101895. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  101896. for (var j = 0; j < 3; j++) {
  101897. 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))));
  101898. }
  101899. };
  101900. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  101901. var triangleInit2 = function (i) {
  101902. var t = _this.triangles[i];
  101903. for (var j = 0; j < 3; ++j) {
  101904. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  101905. }
  101906. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  101907. };
  101908. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  101909. callback();
  101910. });
  101911. });
  101912. };
  101913. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  101914. var newTriangles = [];
  101915. var i;
  101916. for (i = 0; i < this.vertices.length; ++i) {
  101917. this.vertices[i].triangleCount = 0;
  101918. }
  101919. var t;
  101920. var j;
  101921. for (i = 0; i < this.triangles.length; ++i) {
  101922. if (!this.triangles[i].deleted) {
  101923. t = this.triangles[i];
  101924. for (j = 0; j < 3; ++j) {
  101925. t.vertices[j].triangleCount = 1;
  101926. }
  101927. newTriangles.push(t);
  101928. }
  101929. }
  101930. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  101931. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  101932. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  101933. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  101934. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  101935. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  101936. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  101937. var vertexCount = 0;
  101938. for (i = 0; i < this.vertices.length; ++i) {
  101939. var vertex = this.vertices[i];
  101940. vertex.id = vertexCount;
  101941. if (vertex.triangleCount) {
  101942. vertex.originalOffsets.forEach(function (originalOffset) {
  101943. if (!normalData) {
  101944. return;
  101945. }
  101946. newPositionData.push(vertex.position.x);
  101947. newPositionData.push(vertex.position.y);
  101948. newPositionData.push(vertex.position.z);
  101949. newNormalData.push(normalData[originalOffset * 3]);
  101950. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  101951. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  101952. if (uvs && uvs.length) {
  101953. newUVsData.push(uvs[(originalOffset * 2)]);
  101954. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  101955. }
  101956. else if (colorsData && colorsData.length) {
  101957. newColorsData.push(colorsData[(originalOffset * 4)]);
  101958. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  101959. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  101960. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  101961. }
  101962. ++vertexCount;
  101963. });
  101964. }
  101965. }
  101966. var startingIndex = this._reconstructedMesh.getTotalIndices();
  101967. var startingVertex = this._reconstructedMesh.getTotalVertices();
  101968. var submeshesArray = this._reconstructedMesh.subMeshes;
  101969. this._reconstructedMesh.subMeshes = [];
  101970. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  101971. var originalIndices = this._mesh.getIndices();
  101972. for (i = 0; i < newTriangles.length; ++i) {
  101973. t = newTriangles[i]; //now get the new referencing point for each vertex
  101974. [0, 1, 2].forEach(function (idx) {
  101975. var id = originalIndices[t.originalOffset + idx];
  101976. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  101977. if (offset < 0)
  101978. offset = 0;
  101979. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  101980. });
  101981. }
  101982. //overwriting the old vertex buffers and indices.
  101983. this._reconstructedMesh.setIndices(newIndicesArray);
  101984. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  101985. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  101986. if (newUVsData.length > 0)
  101987. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  101988. if (newColorsData.length > 0)
  101989. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  101990. //create submesh
  101991. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  101992. if (submeshIndex > 0) {
  101993. this._reconstructedMesh.subMeshes = [];
  101994. submeshesArray.forEach(function (submesh) {
  101995. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  101996. });
  101997. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  101998. }
  101999. };
  102000. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  102001. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  102002. this._reconstructedMesh.material = this._mesh.material;
  102003. this._reconstructedMesh.parent = this._mesh.parent;
  102004. this._reconstructedMesh.isVisible = false;
  102005. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  102006. };
  102007. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  102008. for (var i = 0; i < vertex1.triangleCount; ++i) {
  102009. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  102010. if (t.deleted)
  102011. continue;
  102012. var s = this.references[vertex1.triangleStart + i].vertexId;
  102013. var v1 = t.vertices[(s + 1) % 3];
  102014. var v2 = t.vertices[(s + 2) % 3];
  102015. if ((v1 === vertex2 || v2 === vertex2)) {
  102016. deletedArray[i] = true;
  102017. delTr.push(t);
  102018. continue;
  102019. }
  102020. var d1 = v1.position.subtract(point);
  102021. d1 = d1.normalize();
  102022. var d2 = v2.position.subtract(point);
  102023. d2 = d2.normalize();
  102024. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  102025. return true;
  102026. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  102027. deletedArray[i] = false;
  102028. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  102029. return true;
  102030. }
  102031. return false;
  102032. };
  102033. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  102034. var newDeleted = deletedTriangles;
  102035. for (var i = 0; i < vertex.triangleCount; ++i) {
  102036. var ref = this.references[vertex.triangleStart + i];
  102037. var t = this.triangles[ref.triangleId];
  102038. if (t.deleted)
  102039. continue;
  102040. if (deletedArray[i] && t.deletePending) {
  102041. t.deleted = true;
  102042. newDeleted++;
  102043. continue;
  102044. }
  102045. t.vertices[ref.vertexId] = origVertex;
  102046. t.isDirty = true;
  102047. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  102048. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  102049. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  102050. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  102051. this.references.push(ref);
  102052. }
  102053. return newDeleted;
  102054. };
  102055. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  102056. for (var i = 0; i < this.vertices.length; ++i) {
  102057. var vCount = [];
  102058. var vId = [];
  102059. var v = this.vertices[i];
  102060. var j;
  102061. for (j = 0; j < v.triangleCount; ++j) {
  102062. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  102063. for (var ii = 0; ii < 3; ii++) {
  102064. var ofs = 0;
  102065. var vv = triangle.vertices[ii];
  102066. while (ofs < vCount.length) {
  102067. if (vId[ofs] === vv.id)
  102068. break;
  102069. ++ofs;
  102070. }
  102071. if (ofs === vCount.length) {
  102072. vCount.push(1);
  102073. vId.push(vv.id);
  102074. }
  102075. else {
  102076. vCount[ofs]++;
  102077. }
  102078. }
  102079. }
  102080. for (j = 0; j < vCount.length; ++j) {
  102081. if (vCount[j] === 1) {
  102082. this.vertices[vId[j]].isBorder = true;
  102083. }
  102084. else {
  102085. this.vertices[vId[j]].isBorder = false;
  102086. }
  102087. }
  102088. }
  102089. };
  102090. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  102091. if (identifyBorders === void 0) { identifyBorders = false; }
  102092. var i;
  102093. if (!identifyBorders) {
  102094. var newTrianglesVector = [];
  102095. for (i = 0; i < this.triangles.length; ++i) {
  102096. if (!this.triangles[i].deleted) {
  102097. newTrianglesVector.push(this.triangles[i]);
  102098. }
  102099. }
  102100. this.triangles = newTrianglesVector;
  102101. }
  102102. for (i = 0; i < this.vertices.length; ++i) {
  102103. this.vertices[i].triangleCount = 0;
  102104. this.vertices[i].triangleStart = 0;
  102105. }
  102106. var t;
  102107. var j;
  102108. var v;
  102109. for (i = 0; i < this.triangles.length; ++i) {
  102110. t = this.triangles[i];
  102111. for (j = 0; j < 3; ++j) {
  102112. v = t.vertices[j];
  102113. v.triangleCount++;
  102114. }
  102115. }
  102116. var tStart = 0;
  102117. for (i = 0; i < this.vertices.length; ++i) {
  102118. this.vertices[i].triangleStart = tStart;
  102119. tStart += this.vertices[i].triangleCount;
  102120. this.vertices[i].triangleCount = 0;
  102121. }
  102122. var newReferences = new Array(this.triangles.length * 3);
  102123. for (i = 0; i < this.triangles.length; ++i) {
  102124. t = this.triangles[i];
  102125. for (j = 0; j < 3; ++j) {
  102126. v = t.vertices[j];
  102127. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  102128. v.triangleCount++;
  102129. }
  102130. }
  102131. this.references = newReferences;
  102132. if (identifyBorders) {
  102133. this.identifyBorder();
  102134. }
  102135. };
  102136. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  102137. var x = point.x;
  102138. var y = point.y;
  102139. var z = point.z;
  102140. 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
  102141. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  102142. };
  102143. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  102144. var q = vertex1.q.add(vertex2.q);
  102145. var border = vertex1.isBorder && vertex2.isBorder;
  102146. var error = 0;
  102147. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  102148. if (qDet !== 0 && !border) {
  102149. if (!pointResult) {
  102150. pointResult = BABYLON.Vector3.Zero();
  102151. }
  102152. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  102153. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  102154. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  102155. error = this.vertexError(q, pointResult);
  102156. }
  102157. else {
  102158. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  102159. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  102160. var error1 = this.vertexError(q, vertex1.position);
  102161. var error2 = this.vertexError(q, vertex2.position);
  102162. var error3 = this.vertexError(q, p3);
  102163. error = Math.min(error1, error2, error3);
  102164. if (error === error1) {
  102165. if (pointResult) {
  102166. pointResult.copyFrom(vertex1.position);
  102167. }
  102168. }
  102169. else if (error === error2) {
  102170. if (pointResult) {
  102171. pointResult.copyFrom(vertex2.position);
  102172. }
  102173. }
  102174. else {
  102175. if (pointResult) {
  102176. pointResult.copyFrom(p3);
  102177. }
  102178. }
  102179. }
  102180. return error;
  102181. };
  102182. return QuadraticErrorSimplification;
  102183. }());
  102184. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  102185. })(BABYLON || (BABYLON = {}));
  102186. //# sourceMappingURL=babylon.meshSimplification.js.map
  102187. var BABYLON;
  102188. (function (BABYLON) {
  102189. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  102190. get: function () {
  102191. if (!this._simplificationQueue) {
  102192. this._simplificationQueue = new BABYLON.SimplificationQueue();
  102193. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  102194. if (!component) {
  102195. component = new SimplicationQueueSceneComponent(this);
  102196. this._addComponent(component);
  102197. }
  102198. }
  102199. return this._simplificationQueue;
  102200. },
  102201. set: function (value) {
  102202. this._simplificationQueue = value;
  102203. },
  102204. enumerable: true,
  102205. configurable: true
  102206. });
  102207. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  102208. if (parallelProcessing === void 0) { parallelProcessing = true; }
  102209. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  102210. this.getScene().simplificationQueue.addTask({
  102211. settings: settings,
  102212. parallelProcessing: parallelProcessing,
  102213. mesh: this,
  102214. simplificationType: simplificationType,
  102215. successCallback: successCallback
  102216. });
  102217. return this;
  102218. };
  102219. /**
  102220. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  102221. * created in a scene
  102222. */
  102223. var SimplicationQueueSceneComponent = /** @class */ (function () {
  102224. /**
  102225. * Creates a new instance of the component for the given scene
  102226. * @param scene Defines the scene to register the component in
  102227. */
  102228. function SimplicationQueueSceneComponent(scene) {
  102229. /**
  102230. * The component name helpfull to identify the component in the list of scene components.
  102231. */
  102232. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  102233. this.scene = scene;
  102234. }
  102235. /**
  102236. * Registers the component in a given scene
  102237. */
  102238. SimplicationQueueSceneComponent.prototype.register = function () {
  102239. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  102240. };
  102241. /**
  102242. * Rebuilds the elements related to this component in case of
  102243. * context lost for instance.
  102244. */
  102245. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  102246. // Nothing to do for this component
  102247. };
  102248. /**
  102249. * Disposes the component and the associated ressources
  102250. */
  102251. SimplicationQueueSceneComponent.prototype.dispose = function () {
  102252. // Nothing to do for this component
  102253. };
  102254. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  102255. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  102256. this.scene._simplificationQueue.executeNext();
  102257. }
  102258. };
  102259. return SimplicationQueueSceneComponent;
  102260. }());
  102261. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  102262. })(BABYLON || (BABYLON = {}));
  102263. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  102264. var BABYLON;
  102265. (function (BABYLON) {
  102266. /**
  102267. * Class used to represent a specific level of detail of a mesh
  102268. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  102269. */
  102270. var MeshLODLevel = /** @class */ (function () {
  102271. /**
  102272. * Creates a new LOD level
  102273. * @param distance defines the distance where this level should star being displayed
  102274. * @param mesh defines the mesh to use to render this level
  102275. */
  102276. function MeshLODLevel(
  102277. /** Defines the distance where this level should star being displayed */
  102278. distance,
  102279. /** Defines the mesh to use to render this level */
  102280. mesh) {
  102281. this.distance = distance;
  102282. this.mesh = mesh;
  102283. }
  102284. return MeshLODLevel;
  102285. }());
  102286. BABYLON.MeshLODLevel = MeshLODLevel;
  102287. })(BABYLON || (BABYLON = {}));
  102288. //# sourceMappingURL=babylon.meshLODLevel.js.map
  102289. var BABYLON;
  102290. (function (BABYLON) {
  102291. /**
  102292. * Defines the root class used to create scene optimization to use with SceneOptimizer
  102293. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102294. */
  102295. var SceneOptimization = /** @class */ (function () {
  102296. /**
  102297. * Creates the SceneOptimization object
  102298. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102299. * @param desc defines the description associated with the optimization
  102300. */
  102301. function SceneOptimization(
  102302. /**
  102303. * Defines the priority of this optimization (0 by default which means first in the list)
  102304. */
  102305. priority) {
  102306. if (priority === void 0) { priority = 0; }
  102307. this.priority = priority;
  102308. }
  102309. /**
  102310. * Gets a string describing the action executed by the current optimization
  102311. * @returns description string
  102312. */
  102313. SceneOptimization.prototype.getDescription = function () {
  102314. return "";
  102315. };
  102316. /**
  102317. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102318. * @param scene defines the current scene where to apply this optimization
  102319. * @param optimizer defines the current optimizer
  102320. * @returns true if everything that can be done was applied
  102321. */
  102322. SceneOptimization.prototype.apply = function (scene, optimizer) {
  102323. return true;
  102324. };
  102325. ;
  102326. return SceneOptimization;
  102327. }());
  102328. BABYLON.SceneOptimization = SceneOptimization;
  102329. /**
  102330. * Defines an optimization used to reduce the size of render target textures
  102331. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102332. */
  102333. var TextureOptimization = /** @class */ (function (_super) {
  102334. __extends(TextureOptimization, _super);
  102335. /**
  102336. * Creates the TextureOptimization object
  102337. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102338. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  102339. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  102340. */
  102341. function TextureOptimization(
  102342. /**
  102343. * Defines the priority of this optimization (0 by default which means first in the list)
  102344. */
  102345. priority,
  102346. /**
  102347. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  102348. */
  102349. maximumSize,
  102350. /**
  102351. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  102352. */
  102353. step) {
  102354. if (priority === void 0) { priority = 0; }
  102355. if (maximumSize === void 0) { maximumSize = 1024; }
  102356. if (step === void 0) { step = 0.5; }
  102357. var _this = _super.call(this, priority) || this;
  102358. _this.priority = priority;
  102359. _this.maximumSize = maximumSize;
  102360. _this.step = step;
  102361. return _this;
  102362. }
  102363. /**
  102364. * Gets a string describing the action executed by the current optimization
  102365. * @returns description string
  102366. */
  102367. TextureOptimization.prototype.getDescription = function () {
  102368. return "Reducing render target texture size to " + this.maximumSize;
  102369. };
  102370. /**
  102371. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102372. * @param scene defines the current scene where to apply this optimization
  102373. * @param optimizer defines the current optimizer
  102374. * @returns true if everything that can be done was applied
  102375. */
  102376. TextureOptimization.prototype.apply = function (scene, optimizer) {
  102377. var allDone = true;
  102378. for (var index = 0; index < scene.textures.length; index++) {
  102379. var texture = scene.textures[index];
  102380. if (!texture.canRescale || texture.getContext) {
  102381. continue;
  102382. }
  102383. var currentSize = texture.getSize();
  102384. var maxDimension = Math.max(currentSize.width, currentSize.height);
  102385. if (maxDimension > this.maximumSize) {
  102386. texture.scale(this.step);
  102387. allDone = false;
  102388. }
  102389. }
  102390. return allDone;
  102391. };
  102392. return TextureOptimization;
  102393. }(SceneOptimization));
  102394. BABYLON.TextureOptimization = TextureOptimization;
  102395. /**
  102396. * Defines an optimization used to increase or decrease the rendering resolution
  102397. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102398. */
  102399. var HardwareScalingOptimization = /** @class */ (function (_super) {
  102400. __extends(HardwareScalingOptimization, _super);
  102401. /**
  102402. * Creates the HardwareScalingOptimization object
  102403. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102404. * @param maximumScale defines the maximum scale to use (2 by default)
  102405. * @param step defines the step to use between two passes (0.5 by default)
  102406. */
  102407. function HardwareScalingOptimization(
  102408. /**
  102409. * Defines the priority of this optimization (0 by default which means first in the list)
  102410. */
  102411. priority,
  102412. /**
  102413. * Defines the maximum scale to use (2 by default)
  102414. */
  102415. maximumScale,
  102416. /**
  102417. * Defines the step to use between two passes (0.5 by default)
  102418. */
  102419. step) {
  102420. if (priority === void 0) { priority = 0; }
  102421. if (maximumScale === void 0) { maximumScale = 2; }
  102422. if (step === void 0) { step = 0.25; }
  102423. var _this = _super.call(this, priority) || this;
  102424. _this.priority = priority;
  102425. _this.maximumScale = maximumScale;
  102426. _this.step = step;
  102427. _this._currentScale = -1;
  102428. _this._directionOffset = 1;
  102429. return _this;
  102430. }
  102431. /**
  102432. * Gets a string describing the action executed by the current optimization
  102433. * @return description string
  102434. */
  102435. HardwareScalingOptimization.prototype.getDescription = function () {
  102436. return "Setting hardware scaling level to " + this._currentScale;
  102437. };
  102438. /**
  102439. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102440. * @param scene defines the current scene where to apply this optimization
  102441. * @param optimizer defines the current optimizer
  102442. * @returns true if everything that can be done was applied
  102443. */
  102444. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  102445. if (this._currentScale === -1) {
  102446. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  102447. if (this._currentScale > this.maximumScale) {
  102448. this._directionOffset = -1;
  102449. }
  102450. }
  102451. this._currentScale += this._directionOffset * this.step;
  102452. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  102453. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  102454. };
  102455. ;
  102456. return HardwareScalingOptimization;
  102457. }(SceneOptimization));
  102458. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  102459. /**
  102460. * Defines an optimization used to remove shadows
  102461. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102462. */
  102463. var ShadowsOptimization = /** @class */ (function (_super) {
  102464. __extends(ShadowsOptimization, _super);
  102465. function ShadowsOptimization() {
  102466. return _super !== null && _super.apply(this, arguments) || this;
  102467. }
  102468. /**
  102469. * Gets a string describing the action executed by the current optimization
  102470. * @return description string
  102471. */
  102472. ShadowsOptimization.prototype.getDescription = function () {
  102473. return "Turning shadows on/off";
  102474. };
  102475. /**
  102476. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102477. * @param scene defines the current scene where to apply this optimization
  102478. * @param optimizer defines the current optimizer
  102479. * @returns true if everything that can be done was applied
  102480. */
  102481. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  102482. scene.shadowsEnabled = optimizer.isInImprovementMode;
  102483. return true;
  102484. };
  102485. ;
  102486. return ShadowsOptimization;
  102487. }(SceneOptimization));
  102488. BABYLON.ShadowsOptimization = ShadowsOptimization;
  102489. /**
  102490. * Defines an optimization used to turn post-processes off
  102491. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102492. */
  102493. var PostProcessesOptimization = /** @class */ (function (_super) {
  102494. __extends(PostProcessesOptimization, _super);
  102495. function PostProcessesOptimization() {
  102496. return _super !== null && _super.apply(this, arguments) || this;
  102497. }
  102498. /**
  102499. * Gets a string describing the action executed by the current optimization
  102500. * @return description string
  102501. */
  102502. PostProcessesOptimization.prototype.getDescription = function () {
  102503. return "Turning post-processes on/off";
  102504. };
  102505. /**
  102506. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102507. * @param scene defines the current scene where to apply this optimization
  102508. * @param optimizer defines the current optimizer
  102509. * @returns true if everything that can be done was applied
  102510. */
  102511. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  102512. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  102513. return true;
  102514. };
  102515. ;
  102516. return PostProcessesOptimization;
  102517. }(SceneOptimization));
  102518. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  102519. /**
  102520. * Defines an optimization used to turn lens flares off
  102521. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102522. */
  102523. var LensFlaresOptimization = /** @class */ (function (_super) {
  102524. __extends(LensFlaresOptimization, _super);
  102525. function LensFlaresOptimization() {
  102526. return _super !== null && _super.apply(this, arguments) || this;
  102527. }
  102528. /**
  102529. * Gets a string describing the action executed by the current optimization
  102530. * @return description string
  102531. */
  102532. LensFlaresOptimization.prototype.getDescription = function () {
  102533. return "Turning lens flares on/off";
  102534. };
  102535. /**
  102536. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102537. * @param scene defines the current scene where to apply this optimization
  102538. * @param optimizer defines the current optimizer
  102539. * @returns true if everything that can be done was applied
  102540. */
  102541. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  102542. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  102543. return true;
  102544. };
  102545. ;
  102546. return LensFlaresOptimization;
  102547. }(SceneOptimization));
  102548. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  102549. /**
  102550. * Defines an optimization based on user defined callback.
  102551. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102552. */
  102553. var CustomOptimization = /** @class */ (function (_super) {
  102554. __extends(CustomOptimization, _super);
  102555. function CustomOptimization() {
  102556. return _super !== null && _super.apply(this, arguments) || this;
  102557. }
  102558. /**
  102559. * Gets a string describing the action executed by the current optimization
  102560. * @returns description string
  102561. */
  102562. CustomOptimization.prototype.getDescription = function () {
  102563. if (this.onGetDescription) {
  102564. return this.onGetDescription();
  102565. }
  102566. return "Running user defined callback";
  102567. };
  102568. /**
  102569. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102570. * @param scene defines the current scene where to apply this optimization
  102571. * @param optimizer defines the current optimizer
  102572. * @returns true if everything that can be done was applied
  102573. */
  102574. CustomOptimization.prototype.apply = function (scene, optimizer) {
  102575. if (this.onApply) {
  102576. return this.onApply(scene, optimizer);
  102577. }
  102578. return true;
  102579. };
  102580. ;
  102581. return CustomOptimization;
  102582. }(SceneOptimization));
  102583. BABYLON.CustomOptimization = CustomOptimization;
  102584. /**
  102585. * Defines an optimization used to turn particles off
  102586. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102587. */
  102588. var ParticlesOptimization = /** @class */ (function (_super) {
  102589. __extends(ParticlesOptimization, _super);
  102590. function ParticlesOptimization() {
  102591. return _super !== null && _super.apply(this, arguments) || this;
  102592. }
  102593. /**
  102594. * Gets a string describing the action executed by the current optimization
  102595. * @return description string
  102596. */
  102597. ParticlesOptimization.prototype.getDescription = function () {
  102598. return "Turning particles on/off";
  102599. };
  102600. /**
  102601. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102602. * @param scene defines the current scene where to apply this optimization
  102603. * @param optimizer defines the current optimizer
  102604. * @returns true if everything that can be done was applied
  102605. */
  102606. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  102607. scene.particlesEnabled = optimizer.isInImprovementMode;
  102608. return true;
  102609. };
  102610. ;
  102611. return ParticlesOptimization;
  102612. }(SceneOptimization));
  102613. BABYLON.ParticlesOptimization = ParticlesOptimization;
  102614. /**
  102615. * Defines an optimization used to turn render targets off
  102616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102617. */
  102618. var RenderTargetsOptimization = /** @class */ (function (_super) {
  102619. __extends(RenderTargetsOptimization, _super);
  102620. function RenderTargetsOptimization() {
  102621. return _super !== null && _super.apply(this, arguments) || this;
  102622. }
  102623. /**
  102624. * Gets a string describing the action executed by the current optimization
  102625. * @return description string
  102626. */
  102627. RenderTargetsOptimization.prototype.getDescription = function () {
  102628. return "Turning render targets off";
  102629. };
  102630. /**
  102631. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102632. * @param scene defines the current scene where to apply this optimization
  102633. * @param optimizer defines the current optimizer
  102634. * @returns true if everything that can be done was applied
  102635. */
  102636. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  102637. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  102638. return true;
  102639. };
  102640. ;
  102641. return RenderTargetsOptimization;
  102642. }(SceneOptimization));
  102643. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  102644. /**
  102645. * Defines an optimization used to merge meshes with compatible materials
  102646. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102647. */
  102648. var MergeMeshesOptimization = /** @class */ (function (_super) {
  102649. __extends(MergeMeshesOptimization, _super);
  102650. function MergeMeshesOptimization() {
  102651. var _this = _super !== null && _super.apply(this, arguments) || this;
  102652. _this._canBeMerged = function (abstractMesh) {
  102653. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  102654. return false;
  102655. }
  102656. var mesh = abstractMesh;
  102657. if (mesh.isDisposed()) {
  102658. return false;
  102659. }
  102660. if (!mesh.isVisible || !mesh.isEnabled()) {
  102661. return false;
  102662. }
  102663. if (mesh.instances.length > 0) {
  102664. return false;
  102665. }
  102666. if (mesh.skeleton || mesh.hasLODLevels) {
  102667. return false;
  102668. }
  102669. return true;
  102670. };
  102671. return _this;
  102672. }
  102673. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  102674. /**
  102675. * Gets or sets a boolean which defines if optimization octree has to be updated
  102676. */
  102677. get: function () {
  102678. return MergeMeshesOptimization._UpdateSelectionTree;
  102679. },
  102680. /**
  102681. * Gets or sets a boolean which defines if optimization octree has to be updated
  102682. */
  102683. set: function (value) {
  102684. MergeMeshesOptimization._UpdateSelectionTree = value;
  102685. },
  102686. enumerable: true,
  102687. configurable: true
  102688. });
  102689. /**
  102690. * Gets a string describing the action executed by the current optimization
  102691. * @return description string
  102692. */
  102693. MergeMeshesOptimization.prototype.getDescription = function () {
  102694. return "Merging similar meshes together";
  102695. };
  102696. /**
  102697. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102698. * @param scene defines the current scene where to apply this optimization
  102699. * @param optimizer defines the current optimizer
  102700. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  102701. * @returns true if everything that can be done was applied
  102702. */
  102703. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  102704. var globalPool = scene.meshes.slice(0);
  102705. var globalLength = globalPool.length;
  102706. for (var index = 0; index < globalLength; index++) {
  102707. var currentPool = new Array();
  102708. var current = globalPool[index];
  102709. // Checks
  102710. if (!this._canBeMerged(current)) {
  102711. continue;
  102712. }
  102713. currentPool.push(current);
  102714. // Find compatible meshes
  102715. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  102716. var otherMesh = globalPool[subIndex];
  102717. if (!this._canBeMerged(otherMesh)) {
  102718. continue;
  102719. }
  102720. if (otherMesh.material !== current.material) {
  102721. continue;
  102722. }
  102723. if (otherMesh.checkCollisions !== current.checkCollisions) {
  102724. continue;
  102725. }
  102726. currentPool.push(otherMesh);
  102727. globalLength--;
  102728. globalPool.splice(subIndex, 1);
  102729. subIndex--;
  102730. }
  102731. if (currentPool.length < 2) {
  102732. continue;
  102733. }
  102734. // Merge meshes
  102735. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  102736. }
  102737. // Call the octree system optimization if it is defined.
  102738. var sceneAsAny = scene;
  102739. if (sceneAsAny.createOrUpdateSelectionOctree) {
  102740. if (updateSelectionTree != undefined) {
  102741. if (updateSelectionTree) {
  102742. sceneAsAny.createOrUpdateSelectionOctree();
  102743. }
  102744. }
  102745. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  102746. sceneAsAny.createOrUpdateSelectionOctree();
  102747. }
  102748. }
  102749. return true;
  102750. };
  102751. ;
  102752. MergeMeshesOptimization._UpdateSelectionTree = false;
  102753. return MergeMeshesOptimization;
  102754. }(SceneOptimization));
  102755. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  102756. /**
  102757. * Defines a list of options used by SceneOptimizer
  102758. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102759. */
  102760. var SceneOptimizerOptions = /** @class */ (function () {
  102761. /**
  102762. * Creates a new list of options used by SceneOptimizer
  102763. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  102764. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  102765. */
  102766. function SceneOptimizerOptions(
  102767. /**
  102768. * Defines the target frame rate to reach (60 by default)
  102769. */
  102770. targetFrameRate,
  102771. /**
  102772. * Defines the interval between two checkes (2000ms by default)
  102773. */
  102774. trackerDuration) {
  102775. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  102776. if (trackerDuration === void 0) { trackerDuration = 2000; }
  102777. this.targetFrameRate = targetFrameRate;
  102778. this.trackerDuration = trackerDuration;
  102779. /**
  102780. * Gets the list of optimizations to apply
  102781. */
  102782. this.optimizations = new Array();
  102783. }
  102784. /**
  102785. * Add a new optimization
  102786. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  102787. * @returns the current SceneOptimizerOptions
  102788. */
  102789. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  102790. this.optimizations.push(optimization);
  102791. return this;
  102792. };
  102793. /**
  102794. * Add a new custom optimization
  102795. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  102796. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  102797. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102798. * @returns the current SceneOptimizerOptions
  102799. */
  102800. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  102801. if (priority === void 0) { priority = 0; }
  102802. var optimization = new CustomOptimization(priority);
  102803. optimization.onApply = onApply;
  102804. optimization.onGetDescription = onGetDescription;
  102805. this.optimizations.push(optimization);
  102806. return this;
  102807. };
  102808. /**
  102809. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  102810. * @param targetFrameRate defines the target frame rate (60 by default)
  102811. * @returns a SceneOptimizerOptions object
  102812. */
  102813. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  102814. var result = new SceneOptimizerOptions(targetFrameRate);
  102815. var priority = 0;
  102816. result.addOptimization(new MergeMeshesOptimization(priority));
  102817. result.addOptimization(new ShadowsOptimization(priority));
  102818. result.addOptimization(new LensFlaresOptimization(priority));
  102819. // Next priority
  102820. priority++;
  102821. result.addOptimization(new PostProcessesOptimization(priority));
  102822. result.addOptimization(new ParticlesOptimization(priority));
  102823. // Next priority
  102824. priority++;
  102825. result.addOptimization(new TextureOptimization(priority, 1024));
  102826. return result;
  102827. };
  102828. /**
  102829. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  102830. * @param targetFrameRate defines the target frame rate (60 by default)
  102831. * @returns a SceneOptimizerOptions object
  102832. */
  102833. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  102834. var result = new SceneOptimizerOptions(targetFrameRate);
  102835. var priority = 0;
  102836. result.addOptimization(new MergeMeshesOptimization(priority));
  102837. result.addOptimization(new ShadowsOptimization(priority));
  102838. result.addOptimization(new LensFlaresOptimization(priority));
  102839. // Next priority
  102840. priority++;
  102841. result.addOptimization(new PostProcessesOptimization(priority));
  102842. result.addOptimization(new ParticlesOptimization(priority));
  102843. // Next priority
  102844. priority++;
  102845. result.addOptimization(new TextureOptimization(priority, 512));
  102846. // Next priority
  102847. priority++;
  102848. result.addOptimization(new RenderTargetsOptimization(priority));
  102849. // Next priority
  102850. priority++;
  102851. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  102852. return result;
  102853. };
  102854. /**
  102855. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  102856. * @param targetFrameRate defines the target frame rate (60 by default)
  102857. * @returns a SceneOptimizerOptions object
  102858. */
  102859. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  102860. var result = new SceneOptimizerOptions(targetFrameRate);
  102861. var priority = 0;
  102862. result.addOptimization(new MergeMeshesOptimization(priority));
  102863. result.addOptimization(new ShadowsOptimization(priority));
  102864. result.addOptimization(new LensFlaresOptimization(priority));
  102865. // Next priority
  102866. priority++;
  102867. result.addOptimization(new PostProcessesOptimization(priority));
  102868. result.addOptimization(new ParticlesOptimization(priority));
  102869. // Next priority
  102870. priority++;
  102871. result.addOptimization(new TextureOptimization(priority, 256));
  102872. // Next priority
  102873. priority++;
  102874. result.addOptimization(new RenderTargetsOptimization(priority));
  102875. // Next priority
  102876. priority++;
  102877. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  102878. return result;
  102879. };
  102880. return SceneOptimizerOptions;
  102881. }());
  102882. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  102883. /**
  102884. * Class used to run optimizations in order to reach a target frame rate
  102885. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102886. */
  102887. var SceneOptimizer = /** @class */ (function () {
  102888. /**
  102889. * Creates a new SceneOptimizer
  102890. * @param scene defines the scene to work on
  102891. * @param options defines the options to use with the SceneOptimizer
  102892. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  102893. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  102894. */
  102895. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  102896. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  102897. if (improvementMode === void 0) { improvementMode = false; }
  102898. var _this = this;
  102899. this._isRunning = false;
  102900. this._currentPriorityLevel = 0;
  102901. this._targetFrameRate = 60;
  102902. this._trackerDuration = 2000;
  102903. this._currentFrameRate = 0;
  102904. this._improvementMode = false;
  102905. /**
  102906. * Defines an observable called when the optimizer reaches the target frame rate
  102907. */
  102908. this.onSuccessObservable = new BABYLON.Observable();
  102909. /**
  102910. * Defines an observable called when the optimizer enables an optimization
  102911. */
  102912. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  102913. /**
  102914. * Defines an observable called when the optimizer is not able to reach the target frame rate
  102915. */
  102916. this.onFailureObservable = new BABYLON.Observable();
  102917. if (!options) {
  102918. this._options = new SceneOptimizerOptions();
  102919. }
  102920. else {
  102921. this._options = options;
  102922. }
  102923. if (this._options.targetFrameRate) {
  102924. this._targetFrameRate = this._options.targetFrameRate;
  102925. }
  102926. if (this._options.trackerDuration) {
  102927. this._trackerDuration = this._options.trackerDuration;
  102928. }
  102929. if (autoGeneratePriorities) {
  102930. var priority = 0;
  102931. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  102932. var optim = _a[_i];
  102933. optim.priority = priority++;
  102934. }
  102935. }
  102936. this._improvementMode = improvementMode;
  102937. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102938. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  102939. _this._sceneDisposeObserver = null;
  102940. _this.dispose();
  102941. });
  102942. }
  102943. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  102944. /**
  102945. * Gets a boolean indicating if the optimizer is in improvement mode
  102946. */
  102947. get: function () {
  102948. return this._improvementMode;
  102949. },
  102950. enumerable: true,
  102951. configurable: true
  102952. });
  102953. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  102954. /**
  102955. * Gets the current priority level (0 at start)
  102956. */
  102957. get: function () {
  102958. return this._currentPriorityLevel;
  102959. },
  102960. enumerable: true,
  102961. configurable: true
  102962. });
  102963. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  102964. /**
  102965. * Gets the current frame rate checked by the SceneOptimizer
  102966. */
  102967. get: function () {
  102968. return this._currentFrameRate;
  102969. },
  102970. enumerable: true,
  102971. configurable: true
  102972. });
  102973. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  102974. /**
  102975. * Gets or sets the current target frame rate (60 by default)
  102976. */
  102977. get: function () {
  102978. return this._targetFrameRate;
  102979. },
  102980. /**
  102981. * Gets or sets the current target frame rate (60 by default)
  102982. */
  102983. set: function (value) {
  102984. this._targetFrameRate = value;
  102985. },
  102986. enumerable: true,
  102987. configurable: true
  102988. });
  102989. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  102990. /**
  102991. * Gets or sets the current interval between two checks (every 2000ms by default)
  102992. */
  102993. get: function () {
  102994. return this._trackerDuration;
  102995. },
  102996. /**
  102997. * Gets or sets the current interval between two checks (every 2000ms by default)
  102998. */
  102999. set: function (value) {
  103000. this._trackerDuration = value;
  103001. },
  103002. enumerable: true,
  103003. configurable: true
  103004. });
  103005. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  103006. /**
  103007. * Gets the list of active optimizations
  103008. */
  103009. get: function () {
  103010. return this._options.optimizations;
  103011. },
  103012. enumerable: true,
  103013. configurable: true
  103014. });
  103015. /**
  103016. * Stops the current optimizer
  103017. */
  103018. SceneOptimizer.prototype.stop = function () {
  103019. this._isRunning = false;
  103020. };
  103021. /**
  103022. * Reset the optimizer to initial step (current priority level = 0)
  103023. */
  103024. SceneOptimizer.prototype.reset = function () {
  103025. this._currentPriorityLevel = 0;
  103026. };
  103027. /**
  103028. * Start the optimizer. By default it will try to reach a specific framerate
  103029. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  103030. */
  103031. SceneOptimizer.prototype.start = function () {
  103032. var _this = this;
  103033. if (this._isRunning) {
  103034. return;
  103035. }
  103036. this._isRunning = true;
  103037. // Let's wait for the scene to be ready before running our check
  103038. this._scene.executeWhenReady(function () {
  103039. setTimeout(function () {
  103040. _this._checkCurrentState();
  103041. }, _this._trackerDuration);
  103042. });
  103043. };
  103044. SceneOptimizer.prototype._checkCurrentState = function () {
  103045. var _this = this;
  103046. if (!this._isRunning) {
  103047. return;
  103048. }
  103049. var scene = this._scene;
  103050. var options = this._options;
  103051. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  103052. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  103053. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  103054. this._isRunning = false;
  103055. this.onSuccessObservable.notifyObservers(this);
  103056. return;
  103057. }
  103058. // Apply current level of optimizations
  103059. var allDone = true;
  103060. var noOptimizationApplied = true;
  103061. for (var index = 0; index < options.optimizations.length; index++) {
  103062. var optimization = options.optimizations[index];
  103063. if (optimization.priority === this._currentPriorityLevel) {
  103064. noOptimizationApplied = false;
  103065. allDone = allDone && optimization.apply(scene, this);
  103066. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  103067. }
  103068. }
  103069. // If no optimization was applied, this is a failure :(
  103070. if (noOptimizationApplied) {
  103071. this._isRunning = false;
  103072. this.onFailureObservable.notifyObservers(this);
  103073. return;
  103074. }
  103075. // If all optimizations were done, move to next level
  103076. if (allDone) {
  103077. this._currentPriorityLevel++;
  103078. }
  103079. // Let's the system running for a specific amount of time before checking FPS
  103080. scene.executeWhenReady(function () {
  103081. setTimeout(function () {
  103082. _this._checkCurrentState();
  103083. }, _this._trackerDuration);
  103084. });
  103085. };
  103086. /**
  103087. * Release all resources
  103088. */
  103089. SceneOptimizer.prototype.dispose = function () {
  103090. this.stop();
  103091. this.onSuccessObservable.clear();
  103092. this.onFailureObservable.clear();
  103093. this.onNewOptimizationAppliedObservable.clear();
  103094. if (this._sceneDisposeObserver) {
  103095. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  103096. }
  103097. };
  103098. /**
  103099. * Helper function to create a SceneOptimizer with one single line of code
  103100. * @param scene defines the scene to work on
  103101. * @param options defines the options to use with the SceneOptimizer
  103102. * @param onSuccess defines a callback to call on success
  103103. * @param onFailure defines a callback to call on failure
  103104. * @returns the new SceneOptimizer object
  103105. */
  103106. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  103107. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  103108. if (onSuccess) {
  103109. optimizer.onSuccessObservable.add(function () {
  103110. onSuccess();
  103111. });
  103112. }
  103113. if (onFailure) {
  103114. optimizer.onFailureObservable.add(function () {
  103115. onFailure();
  103116. });
  103117. }
  103118. optimizer.start();
  103119. return optimizer;
  103120. };
  103121. return SceneOptimizer;
  103122. }());
  103123. BABYLON.SceneOptimizer = SceneOptimizer;
  103124. })(BABYLON || (BABYLON = {}));
  103125. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  103126. var BABYLON;
  103127. (function (BABYLON) {
  103128. /**
  103129. * Gets the outline renderer associated with the scene
  103130. * @returns a OutlineRenderer
  103131. */
  103132. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  103133. if (!this._outlineRenderer) {
  103134. this._outlineRenderer = new OutlineRenderer(this);
  103135. }
  103136. return this._outlineRenderer;
  103137. };
  103138. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  103139. get: function () {
  103140. return this._renderOutline;
  103141. },
  103142. set: function (value) {
  103143. if (value) {
  103144. // Lazy Load the component.
  103145. this.getScene().getOutlineRenderer();
  103146. }
  103147. this._renderOutline = value;
  103148. },
  103149. enumerable: true,
  103150. configurable: true
  103151. });
  103152. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  103153. get: function () {
  103154. return this._renderOverlay;
  103155. },
  103156. set: function (value) {
  103157. if (value) {
  103158. // Lazy Load the component.
  103159. this.getScene().getOutlineRenderer();
  103160. }
  103161. this._renderOverlay = value;
  103162. },
  103163. enumerable: true,
  103164. configurable: true
  103165. });
  103166. /**
  103167. * This class is responsible to draw bothe outline/overlay of meshes.
  103168. * It should not be used directly but through the available method on mesh.
  103169. */
  103170. var OutlineRenderer = /** @class */ (function () {
  103171. /**
  103172. * Instantiates a new outline renderer. (There could be only one per scene).
  103173. * @param scene Defines the scene it belongs to
  103174. */
  103175. function OutlineRenderer(scene) {
  103176. /**
  103177. * The name of the component. Each component must have a unique name.
  103178. */
  103179. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  103180. /**
  103181. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  103182. */
  103183. this.zOffset = 1;
  103184. this.scene = scene;
  103185. this._engine = scene.getEngine();
  103186. this.scene._addComponent(this);
  103187. }
  103188. /**
  103189. * Register the component to one instance of a scene.
  103190. */
  103191. OutlineRenderer.prototype.register = function () {
  103192. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  103193. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  103194. };
  103195. /**
  103196. * Rebuilds the elements related to this component in case of
  103197. * context lost for instance.
  103198. */
  103199. OutlineRenderer.prototype.rebuild = function () {
  103200. // Nothing to do here.
  103201. };
  103202. /**
  103203. * Disposes the component and the associated ressources.
  103204. */
  103205. OutlineRenderer.prototype.dispose = function () {
  103206. // Nothing to do here.
  103207. };
  103208. /**
  103209. * Renders the outline in the canvas.
  103210. * @param subMesh Defines the sumesh to render
  103211. * @param batch Defines the batch of meshes in case of instances
  103212. * @param useOverlay Defines if the rendering is for the overlay or the outline
  103213. */
  103214. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  103215. var _this = this;
  103216. if (useOverlay === void 0) { useOverlay = false; }
  103217. var scene = this.scene;
  103218. var engine = scene.getEngine();
  103219. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  103220. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  103221. return;
  103222. }
  103223. var mesh = subMesh.getRenderingMesh();
  103224. var material = subMesh.getMaterial();
  103225. if (!material || !scene.activeCamera) {
  103226. return;
  103227. }
  103228. engine.enableEffect(this._effect);
  103229. // Logarithmic depth
  103230. if (material.useLogarithmicDepth) {
  103231. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  103232. }
  103233. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  103234. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  103235. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  103236. // Bones
  103237. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  103238. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  103239. }
  103240. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  103241. // Alpha test
  103242. if (material && material.needAlphaTesting()) {
  103243. var alphaTexture = material.getAlphaTestTexture();
  103244. if (alphaTexture) {
  103245. this._effect.setTexture("diffuseSampler", alphaTexture);
  103246. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  103247. }
  103248. }
  103249. engine.setZOffset(-this.zOffset);
  103250. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  103251. engine.setZOffset(0);
  103252. };
  103253. /**
  103254. * Returns whether or not the outline renderer is ready for a given submesh.
  103255. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  103256. * @param subMesh Defines the submesh to check readyness for
  103257. * @param useInstances Defines wheter wee are trying to render instances or not
  103258. * @returns true if ready otherwise false
  103259. */
  103260. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  103261. var defines = [];
  103262. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  103263. var mesh = subMesh.getMesh();
  103264. var material = subMesh.getMaterial();
  103265. if (material) {
  103266. // Alpha test
  103267. if (material.needAlphaTesting()) {
  103268. defines.push("#define ALPHATEST");
  103269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  103270. attribs.push(BABYLON.VertexBuffer.UVKind);
  103271. defines.push("#define UV1");
  103272. }
  103273. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  103274. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103275. defines.push("#define UV2");
  103276. }
  103277. }
  103278. //Logarithmic depth
  103279. if (material.useLogarithmicDepth) {
  103280. defines.push("#define LOGARITHMICDEPTH");
  103281. }
  103282. }
  103283. // Bones
  103284. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  103285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  103286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  103287. if (mesh.numBoneInfluencers > 4) {
  103288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  103289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  103290. }
  103291. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  103292. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  103293. }
  103294. else {
  103295. defines.push("#define NUM_BONE_INFLUENCERS 0");
  103296. }
  103297. // Instances
  103298. if (useInstances) {
  103299. defines.push("#define INSTANCES");
  103300. attribs.push("world0");
  103301. attribs.push("world1");
  103302. attribs.push("world2");
  103303. attribs.push("world3");
  103304. }
  103305. // Get correct effect
  103306. var join = defines.join("\n");
  103307. if (this._cachedDefines !== join) {
  103308. this._cachedDefines = join;
  103309. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  103310. }
  103311. return this._effect.isReady();
  103312. };
  103313. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  103314. // Outline - step 1
  103315. this._savedDepthWrite = this._engine.getDepthWrite();
  103316. if (mesh.renderOutline) {
  103317. this._engine.setDepthWrite(false);
  103318. this.render(subMesh, batch);
  103319. this._engine.setDepthWrite(this._savedDepthWrite);
  103320. }
  103321. };
  103322. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  103323. // Outline - step 2
  103324. if (mesh.renderOutline && this._savedDepthWrite) {
  103325. this._engine.setDepthWrite(true);
  103326. this._engine.setColorWrite(false);
  103327. this.render(subMesh, batch);
  103328. this._engine.setColorWrite(true);
  103329. }
  103330. // Overlay
  103331. if (mesh.renderOverlay) {
  103332. var currentMode = this._engine.getAlphaMode();
  103333. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  103334. this.render(subMesh, batch, true);
  103335. this._engine.setAlphaMode(currentMode);
  103336. }
  103337. };
  103338. return OutlineRenderer;
  103339. }());
  103340. BABYLON.OutlineRenderer = OutlineRenderer;
  103341. })(BABYLON || (BABYLON = {}));
  103342. //# sourceMappingURL=babylon.outlineRenderer.js.map
  103343. var BABYLON;
  103344. (function (BABYLON) {
  103345. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  103346. if (this._edgesRenderer) {
  103347. this._edgesRenderer.dispose();
  103348. this._edgesRenderer = null;
  103349. }
  103350. return this;
  103351. };
  103352. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  103353. if (epsilon === void 0) { epsilon = 0.95; }
  103354. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103355. this.disableEdgesRendering();
  103356. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  103357. return this;
  103358. };
  103359. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  103360. get: function () {
  103361. return this._edgesRenderer;
  103362. },
  103363. enumerable: true,
  103364. configurable: true
  103365. });
  103366. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  103367. if (epsilon === void 0) { epsilon = 0.95; }
  103368. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103369. this.disableEdgesRendering();
  103370. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  103371. return this;
  103372. };
  103373. /**
  103374. * FaceAdjacencies Helper class to generate edges
  103375. */
  103376. var FaceAdjacencies = /** @class */ (function () {
  103377. function FaceAdjacencies() {
  103378. this.edges = new Array();
  103379. this.edgesConnectedCount = 0;
  103380. }
  103381. return FaceAdjacencies;
  103382. }());
  103383. /**
  103384. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  103385. */
  103386. var EdgesRenderer = /** @class */ (function () {
  103387. /**
  103388. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  103389. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  103390. * @param source Mesh used to create edges
  103391. * @param epsilon sum of angles in adjacency to check for edge
  103392. * @param checkVerticesInsteadOfIndices
  103393. * @param generateEdgesLines - should generate Lines or only prepare resources.
  103394. */
  103395. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  103396. if (epsilon === void 0) { epsilon = 0.95; }
  103397. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103398. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  103399. var _this = this;
  103400. this.edgesWidthScalerForOrthographic = 1000.0;
  103401. this.edgesWidthScalerForPerspective = 50.0;
  103402. this._linesPositions = new Array();
  103403. this._linesNormals = new Array();
  103404. this._linesIndices = new Array();
  103405. this._buffers = {};
  103406. this._checkVerticesInsteadOfIndices = false;
  103407. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  103408. this.isEnabled = true;
  103409. this._source = source;
  103410. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  103411. this._epsilon = epsilon;
  103412. this._prepareRessources();
  103413. if (generateEdgesLines) {
  103414. this._generateEdgesLines();
  103415. }
  103416. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  103417. _this._rebuild();
  103418. });
  103419. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  103420. _this.dispose();
  103421. });
  103422. }
  103423. EdgesRenderer.prototype._prepareRessources = function () {
  103424. if (this._lineShader) {
  103425. return;
  103426. }
  103427. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  103428. attributes: ["position", "normal"],
  103429. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  103430. });
  103431. this._lineShader.disableDepthWrite = true;
  103432. this._lineShader.backFaceCulling = false;
  103433. };
  103434. /** @hidden */
  103435. EdgesRenderer.prototype._rebuild = function () {
  103436. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  103437. if (buffer) {
  103438. buffer._rebuild();
  103439. }
  103440. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  103441. if (buffer) {
  103442. buffer._rebuild();
  103443. }
  103444. var scene = this._source.getScene();
  103445. var engine = scene.getEngine();
  103446. this._ib = engine.createIndexBuffer(this._linesIndices);
  103447. };
  103448. /**
  103449. * Releases the required resources for the edges renderer
  103450. */
  103451. EdgesRenderer.prototype.dispose = function () {
  103452. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  103453. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  103454. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  103455. if (buffer) {
  103456. buffer.dispose();
  103457. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  103458. }
  103459. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  103460. if (buffer) {
  103461. buffer.dispose();
  103462. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  103463. }
  103464. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  103465. this._lineShader.dispose();
  103466. };
  103467. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  103468. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  103469. return 0;
  103470. }
  103471. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  103472. return 1;
  103473. }
  103474. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  103475. return 2;
  103476. }
  103477. return -1;
  103478. };
  103479. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  103480. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  103481. return 0;
  103482. }
  103483. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  103484. return 1;
  103485. }
  103486. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  103487. return 2;
  103488. }
  103489. return -1;
  103490. };
  103491. /**
  103492. * Checks if the pair of p0 and p1 is en edge
  103493. * @param faceIndex
  103494. * @param edge
  103495. * @param faceNormals
  103496. * @param p0
  103497. * @param p1
  103498. * @private
  103499. */
  103500. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  103501. var needToCreateLine;
  103502. if (edge === undefined) {
  103503. needToCreateLine = true;
  103504. }
  103505. else {
  103506. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  103507. needToCreateLine = dotProduct < this._epsilon;
  103508. }
  103509. if (needToCreateLine) {
  103510. var offset = this._linesPositions.length / 3;
  103511. var normal = p0.subtract(p1);
  103512. normal.normalize();
  103513. // Positions
  103514. this._linesPositions.push(p0.x);
  103515. this._linesPositions.push(p0.y);
  103516. this._linesPositions.push(p0.z);
  103517. this._linesPositions.push(p0.x);
  103518. this._linesPositions.push(p0.y);
  103519. this._linesPositions.push(p0.z);
  103520. this._linesPositions.push(p1.x);
  103521. this._linesPositions.push(p1.y);
  103522. this._linesPositions.push(p1.z);
  103523. this._linesPositions.push(p1.x);
  103524. this._linesPositions.push(p1.y);
  103525. this._linesPositions.push(p1.z);
  103526. // Normals
  103527. this._linesNormals.push(p1.x);
  103528. this._linesNormals.push(p1.y);
  103529. this._linesNormals.push(p1.z);
  103530. this._linesNormals.push(-1);
  103531. this._linesNormals.push(p1.x);
  103532. this._linesNormals.push(p1.y);
  103533. this._linesNormals.push(p1.z);
  103534. this._linesNormals.push(1);
  103535. this._linesNormals.push(p0.x);
  103536. this._linesNormals.push(p0.y);
  103537. this._linesNormals.push(p0.z);
  103538. this._linesNormals.push(-1);
  103539. this._linesNormals.push(p0.x);
  103540. this._linesNormals.push(p0.y);
  103541. this._linesNormals.push(p0.z);
  103542. this._linesNormals.push(1);
  103543. // Indices
  103544. this._linesIndices.push(offset);
  103545. this._linesIndices.push(offset + 1);
  103546. this._linesIndices.push(offset + 2);
  103547. this._linesIndices.push(offset);
  103548. this._linesIndices.push(offset + 2);
  103549. this._linesIndices.push(offset + 3);
  103550. }
  103551. };
  103552. /**
  103553. * Generates lines edges from adjacencjes
  103554. * @private
  103555. */
  103556. EdgesRenderer.prototype._generateEdgesLines = function () {
  103557. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  103558. var indices = this._source.getIndices();
  103559. if (!indices || !positions) {
  103560. return;
  103561. }
  103562. // First let's find adjacencies
  103563. var adjacencies = new Array();
  103564. var faceNormals = new Array();
  103565. var index;
  103566. var faceAdjacencies;
  103567. // Prepare faces
  103568. for (index = 0; index < indices.length; index += 3) {
  103569. faceAdjacencies = new FaceAdjacencies();
  103570. var p0Index = indices[index];
  103571. var p1Index = indices[index + 1];
  103572. var p2Index = indices[index + 2];
  103573. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  103574. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  103575. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  103576. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  103577. faceNormal.normalize();
  103578. faceNormals.push(faceNormal);
  103579. adjacencies.push(faceAdjacencies);
  103580. }
  103581. // Scan
  103582. for (index = 0; index < adjacencies.length; index++) {
  103583. faceAdjacencies = adjacencies[index];
  103584. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  103585. var otherFaceAdjacencies = adjacencies[otherIndex];
  103586. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  103587. break;
  103588. }
  103589. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  103590. continue;
  103591. }
  103592. var otherP0 = indices[otherIndex * 3];
  103593. var otherP1 = indices[otherIndex * 3 + 1];
  103594. var otherP2 = indices[otherIndex * 3 + 2];
  103595. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  103596. var otherEdgeIndex = 0;
  103597. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  103598. continue;
  103599. }
  103600. switch (edgeIndex) {
  103601. case 0:
  103602. if (this._checkVerticesInsteadOfIndices) {
  103603. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103604. }
  103605. else {
  103606. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  103607. }
  103608. break;
  103609. case 1:
  103610. if (this._checkVerticesInsteadOfIndices) {
  103611. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103612. }
  103613. else {
  103614. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  103615. }
  103616. break;
  103617. case 2:
  103618. if (this._checkVerticesInsteadOfIndices) {
  103619. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103620. }
  103621. else {
  103622. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  103623. }
  103624. break;
  103625. }
  103626. if (otherEdgeIndex === -1) {
  103627. continue;
  103628. }
  103629. faceAdjacencies.edges[edgeIndex] = otherIndex;
  103630. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  103631. faceAdjacencies.edgesConnectedCount++;
  103632. otherFaceAdjacencies.edgesConnectedCount++;
  103633. if (faceAdjacencies.edgesConnectedCount === 3) {
  103634. break;
  103635. }
  103636. }
  103637. }
  103638. }
  103639. // Create lines
  103640. for (index = 0; index < adjacencies.length; index++) {
  103641. // 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
  103642. var current = adjacencies[index];
  103643. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  103644. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  103645. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  103646. }
  103647. // Merge into a single mesh
  103648. var engine = this._source.getScene().getEngine();
  103649. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  103650. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  103651. this._ib = engine.createIndexBuffer(this._linesIndices);
  103652. this._indicesCount = this._linesIndices.length;
  103653. };
  103654. /**
  103655. * Checks wether or not the edges renderer is ready to render.
  103656. * @return true if ready, otherwise false.
  103657. */
  103658. EdgesRenderer.prototype.isReady = function () {
  103659. return this._lineShader.isReady();
  103660. };
  103661. /**
  103662. * Renders the edges of the attached mesh,
  103663. */
  103664. EdgesRenderer.prototype.render = function () {
  103665. var scene = this._source.getScene();
  103666. if (!this.isReady() || !scene.activeCamera) {
  103667. return;
  103668. }
  103669. var engine = scene.getEngine();
  103670. this._lineShader._preBind();
  103671. if (this._source.edgesColor.a !== 1) {
  103672. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  103673. }
  103674. else {
  103675. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  103676. }
  103677. // VBOs
  103678. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  103679. scene.resetCachedMaterial();
  103680. this._lineShader.setColor4("color", this._source.edgesColor);
  103681. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  103682. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  103683. }
  103684. else {
  103685. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  103686. }
  103687. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  103688. this._lineShader.bind(this._source.getWorldMatrix());
  103689. // Draw order
  103690. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  103691. this._lineShader.unbind();
  103692. };
  103693. return EdgesRenderer;
  103694. }());
  103695. BABYLON.EdgesRenderer = EdgesRenderer;
  103696. })(BABYLON || (BABYLON = {}));
  103697. //# sourceMappingURL=babylon.edgesRenderer.js.map
  103698. var BABYLON;
  103699. (function (BABYLON) {
  103700. /**
  103701. * FaceAdjacencies Helper class to generate edges
  103702. */
  103703. var FaceAdjacencies = /** @class */ (function () {
  103704. function FaceAdjacencies() {
  103705. this.edges = new Array();
  103706. this.edgesConnectedCount = 0;
  103707. }
  103708. return FaceAdjacencies;
  103709. }());
  103710. /**
  103711. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  103712. */
  103713. var LineEdgesRenderer = /** @class */ (function (_super) {
  103714. __extends(LineEdgesRenderer, _super);
  103715. /**
  103716. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  103717. * @param source LineMesh used to generate edges
  103718. * @param epsilon not important (specified angle for edge detection)
  103719. * @param checkVerticesInsteadOfIndices not important for LineMesh
  103720. */
  103721. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  103722. if (epsilon === void 0) { epsilon = 0.95; }
  103723. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103724. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  103725. _this._generateEdgesLines();
  103726. return _this;
  103727. }
  103728. /**
  103729. * Always create the edge since its a line so only important things are p0 and p1
  103730. * @param faceIndex not important for LineMesh
  103731. * @param edge not important for LineMesh
  103732. * @param faceNormals not important for LineMesh
  103733. * @param p0 beginnig of line
  103734. * @param p1 end of line
  103735. */
  103736. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  103737. var offset = this._linesPositions.length / 3;
  103738. var normal = p0.subtract(p1);
  103739. normal.normalize();
  103740. // Positions
  103741. this._linesPositions.push(p0.x);
  103742. this._linesPositions.push(p0.y);
  103743. this._linesPositions.push(p0.z);
  103744. this._linesPositions.push(p0.x);
  103745. this._linesPositions.push(p0.y);
  103746. this._linesPositions.push(p0.z);
  103747. this._linesPositions.push(p1.x);
  103748. this._linesPositions.push(p1.y);
  103749. this._linesPositions.push(p1.z);
  103750. this._linesPositions.push(p1.x);
  103751. this._linesPositions.push(p1.y);
  103752. this._linesPositions.push(p1.z);
  103753. // Normals
  103754. this._linesNormals.push(p1.x);
  103755. this._linesNormals.push(p1.y);
  103756. this._linesNormals.push(p1.z);
  103757. this._linesNormals.push(-1);
  103758. this._linesNormals.push(p1.x);
  103759. this._linesNormals.push(p1.y);
  103760. this._linesNormals.push(p1.z);
  103761. this._linesNormals.push(1);
  103762. this._linesNormals.push(p0.x);
  103763. this._linesNormals.push(p0.y);
  103764. this._linesNormals.push(p0.z);
  103765. this._linesNormals.push(-1);
  103766. this._linesNormals.push(p0.x);
  103767. this._linesNormals.push(p0.y);
  103768. this._linesNormals.push(p0.z);
  103769. this._linesNormals.push(1);
  103770. // Indices
  103771. this._linesIndices.push(offset);
  103772. this._linesIndices.push(offset + 1);
  103773. this._linesIndices.push(offset + 2);
  103774. this._linesIndices.push(offset);
  103775. this._linesIndices.push(offset + 2);
  103776. this._linesIndices.push(offset + 3);
  103777. };
  103778. /**
  103779. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  103780. */
  103781. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  103782. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  103783. var indices = this._source.getIndices();
  103784. if (!indices || !positions) {
  103785. return;
  103786. }
  103787. // First let's find adjacencies
  103788. var adjacencies = new Array();
  103789. var faceNormals = new Array();
  103790. var index;
  103791. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  103792. var currentAdjecancy = new FaceAdjacencies();
  103793. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  103794. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  103795. adjacencies.push(currentAdjecancy);
  103796. }
  103797. // Create lines
  103798. for (index = 0; index < adjacencies.length; index++) {
  103799. // 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
  103800. var current = adjacencies[index];
  103801. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  103802. }
  103803. // Merge into a single mesh
  103804. var engine = this._source.getScene().getEngine();
  103805. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  103806. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  103807. this._ib = engine.createIndexBuffer(this._linesIndices);
  103808. this._indicesCount = this._linesIndices.length;
  103809. };
  103810. return LineEdgesRenderer;
  103811. }(BABYLON.EdgesRenderer));
  103812. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  103813. })(BABYLON || (BABYLON = {}));
  103814. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  103815. var BABYLON;
  103816. (function (BABYLON) {
  103817. // Adds the parser to the scene parsers.
  103818. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  103819. if (parsedData.effectLayers) {
  103820. if (!container.effectLayers) {
  103821. container.effectLayers = new Array();
  103822. }
  103823. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  103824. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  103825. container.effectLayers.push(effectLayer);
  103826. }
  103827. }
  103828. });
  103829. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  103830. var index = this.effectLayers.indexOf(toRemove);
  103831. if (index !== -1) {
  103832. this.effectLayers.splice(index, 1);
  103833. }
  103834. return index;
  103835. };
  103836. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  103837. this.effectLayers.push(newEffectLayer);
  103838. };
  103839. /**
  103840. * Defines the layer scene component responsible to manage any effect layers
  103841. * in a given scene.
  103842. */
  103843. var EffectLayerSceneComponent = /** @class */ (function () {
  103844. /**
  103845. * Creates a new instance of the component for the given scene
  103846. * @param scene Defines the scene to register the component in
  103847. */
  103848. function EffectLayerSceneComponent(scene) {
  103849. /**
  103850. * The component name helpfull to identify the component in the list of scene components.
  103851. */
  103852. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  103853. this._renderEffects = false;
  103854. this._needStencil = false;
  103855. this._previousStencilState = false;
  103856. this.scene = scene;
  103857. this._engine = scene.getEngine();
  103858. scene.effectLayers = new Array();
  103859. }
  103860. /**
  103861. * Registers the component in a given scene
  103862. */
  103863. EffectLayerSceneComponent.prototype.register = function () {
  103864. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  103865. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  103866. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  103867. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  103868. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  103869. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  103870. };
  103871. /**
  103872. * Rebuilds the elements related to this component in case of
  103873. * context lost for instance.
  103874. */
  103875. EffectLayerSceneComponent.prototype.rebuild = function () {
  103876. var layers = this.scene.effectLayers;
  103877. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  103878. var effectLayer = layers_1[_i];
  103879. effectLayer._rebuild();
  103880. }
  103881. };
  103882. /**
  103883. * Serializes the component data to the specified json object
  103884. * @param serializationObject The object to serialize to
  103885. */
  103886. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  103887. // Effect layers
  103888. serializationObject.effectLayers = [];
  103889. var layers = this.scene.effectLayers;
  103890. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  103891. var effectLayer = layers_2[_i];
  103892. if (effectLayer.serialize) {
  103893. serializationObject.effectLayers.push(effectLayer.serialize());
  103894. }
  103895. }
  103896. };
  103897. /**
  103898. * Adds all the element from the container to the scene
  103899. * @param container the container holding the elements
  103900. */
  103901. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  103902. var _this = this;
  103903. if (!container.effectLayers) {
  103904. return;
  103905. }
  103906. container.effectLayers.forEach(function (o) {
  103907. _this.scene.addEffectLayer(o);
  103908. });
  103909. };
  103910. /**
  103911. * Removes all the elements in the container from the scene
  103912. * @param container contains the elements to remove
  103913. */
  103914. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  103915. var _this = this;
  103916. if (!container.effectLayers) {
  103917. return;
  103918. }
  103919. container.effectLayers.forEach(function (o) {
  103920. _this.scene.removeEffectLayer(o);
  103921. });
  103922. };
  103923. /**
  103924. * Disposes the component and the associated ressources.
  103925. */
  103926. EffectLayerSceneComponent.prototype.dispose = function () {
  103927. var layers = this.scene.effectLayers;
  103928. while (layers.length) {
  103929. layers[0].dispose();
  103930. }
  103931. };
  103932. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  103933. var layers = this.scene.effectLayers;
  103934. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  103935. var layer = layers_3[_i];
  103936. if (!layer.hasMesh(mesh)) {
  103937. continue;
  103938. }
  103939. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  103940. var subMesh = _b[_a];
  103941. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  103942. return false;
  103943. }
  103944. }
  103945. }
  103946. return true;
  103947. };
  103948. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  103949. this._renderEffects = false;
  103950. this._needStencil = false;
  103951. var layers = this.scene.effectLayers;
  103952. if (layers && layers.length > 0) {
  103953. this._previousStencilState = this._engine.getStencilBuffer();
  103954. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  103955. var effectLayer = layers_4[_i];
  103956. if (effectLayer.shouldRender() &&
  103957. (!effectLayer.camera ||
  103958. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  103959. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  103960. this._renderEffects = true;
  103961. this._needStencil = this._needStencil || effectLayer.needStencil();
  103962. var renderTarget = effectLayer._mainTexture;
  103963. if (renderTarget._shouldRender()) {
  103964. this.scene.incrementRenderId();
  103965. renderTarget.render(false, false);
  103966. }
  103967. }
  103968. }
  103969. this.scene.incrementRenderId();
  103970. }
  103971. };
  103972. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  103973. // Activate effect Layer stencil
  103974. if (this._needStencil) {
  103975. this._engine.setStencilBuffer(true);
  103976. }
  103977. };
  103978. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  103979. // Restore effect Layer stencil
  103980. if (this._needStencil) {
  103981. this._engine.setStencilBuffer(this._previousStencilState);
  103982. }
  103983. };
  103984. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  103985. if (this._renderEffects) {
  103986. this._engine.setDepthBuffer(false);
  103987. var layers = this.scene.effectLayers;
  103988. for (var i = 0; i < layers.length; i++) {
  103989. var effectLayer = layers[i];
  103990. if (effectLayer.renderingGroupId === renderingGroupId) {
  103991. if (effectLayer.shouldRender()) {
  103992. effectLayer.render();
  103993. }
  103994. }
  103995. }
  103996. this._engine.setDepthBuffer(true);
  103997. }
  103998. };
  103999. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  104000. if (this._renderEffects) {
  104001. this._draw(-1);
  104002. }
  104003. };
  104004. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  104005. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  104006. this._draw(index);
  104007. }
  104008. };
  104009. return EffectLayerSceneComponent;
  104010. }());
  104011. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  104012. })(BABYLON || (BABYLON = {}));
  104013. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  104014. var __assign = (this && this.__assign) || function () {
  104015. __assign = Object.assign || function(t) {
  104016. for (var s, i = 1, n = arguments.length; i < n; i++) {
  104017. s = arguments[i];
  104018. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  104019. t[p] = s[p];
  104020. }
  104021. return t;
  104022. };
  104023. return __assign.apply(this, arguments);
  104024. };
  104025. var BABYLON;
  104026. (function (BABYLON) {
  104027. /**
  104028. * The effect layer Helps adding post process effect blended with the main pass.
  104029. *
  104030. * This can be for instance use to generate glow or higlight effects on the scene.
  104031. *
  104032. * The effect layer class can not be used directly and is intented to inherited from to be
  104033. * customized per effects.
  104034. */
  104035. var EffectLayer = /** @class */ (function () {
  104036. /**
  104037. * Instantiates a new effect Layer and references it in the scene.
  104038. * @param name The name of the layer
  104039. * @param scene The scene to use the layer in
  104040. */
  104041. function EffectLayer(
  104042. /** The Friendly of the effect in the scene */
  104043. name, scene) {
  104044. this._vertexBuffers = {};
  104045. this._maxSize = 0;
  104046. this._mainTextureDesiredSize = { width: 0, height: 0 };
  104047. this._shouldRender = true;
  104048. this._postProcesses = [];
  104049. this._textures = [];
  104050. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  104051. /**
  104052. * The clear color of the texture used to generate the glow map.
  104053. */
  104054. this.neutralColor = new BABYLON.Color4();
  104055. /**
  104056. * Specifies wether the highlight layer is enabled or not.
  104057. */
  104058. this.isEnabled = true;
  104059. /**
  104060. * An event triggered when the effect layer has been disposed.
  104061. */
  104062. this.onDisposeObservable = new BABYLON.Observable();
  104063. /**
  104064. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  104065. */
  104066. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  104067. /**
  104068. * An event triggered when the generated texture is being merged in the scene.
  104069. */
  104070. this.onBeforeComposeObservable = new BABYLON.Observable();
  104071. /**
  104072. * An event triggered when the generated texture has been merged in the scene.
  104073. */
  104074. this.onAfterComposeObservable = new BABYLON.Observable();
  104075. /**
  104076. * An event triggered when the efffect layer changes its size.
  104077. */
  104078. this.onSizeChangedObservable = new BABYLON.Observable();
  104079. this.name = name;
  104080. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104081. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  104082. if (!component) {
  104083. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  104084. this._scene._addComponent(component);
  104085. }
  104086. this._engine = this._scene.getEngine();
  104087. this._maxSize = this._engine.getCaps().maxTextureSize;
  104088. this._scene.effectLayers.push(this);
  104089. // Generate Buffers
  104090. this._generateIndexBuffer();
  104091. this._genrateVertexBuffer();
  104092. }
  104093. Object.defineProperty(EffectLayer.prototype, "camera", {
  104094. /**
  104095. * Gets the camera attached to the layer.
  104096. */
  104097. get: function () {
  104098. return this._effectLayerOptions.camera;
  104099. },
  104100. enumerable: true,
  104101. configurable: true
  104102. });
  104103. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  104104. /**
  104105. * Gets the rendering group id the layer should render in.
  104106. */
  104107. get: function () {
  104108. return this._effectLayerOptions.renderingGroupId;
  104109. },
  104110. enumerable: true,
  104111. configurable: true
  104112. });
  104113. /**
  104114. * Initializes the effect layer with the required options.
  104115. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  104116. */
  104117. EffectLayer.prototype._init = function (options) {
  104118. // Adapt options
  104119. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  104120. this._setMainTextureSize();
  104121. this._createMainTexture();
  104122. this._createTextureAndPostProcesses();
  104123. this._mergeEffect = this._createMergeEffect();
  104124. };
  104125. /**
  104126. * Generates the index buffer of the full screen quad blending to the main canvas.
  104127. */
  104128. EffectLayer.prototype._generateIndexBuffer = function () {
  104129. // Indices
  104130. var indices = [];
  104131. indices.push(0);
  104132. indices.push(1);
  104133. indices.push(2);
  104134. indices.push(0);
  104135. indices.push(2);
  104136. indices.push(3);
  104137. this._indexBuffer = this._engine.createIndexBuffer(indices);
  104138. };
  104139. /**
  104140. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  104141. */
  104142. EffectLayer.prototype._genrateVertexBuffer = function () {
  104143. // VBO
  104144. var vertices = [];
  104145. vertices.push(1, 1);
  104146. vertices.push(-1, 1);
  104147. vertices.push(-1, -1);
  104148. vertices.push(1, -1);
  104149. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  104150. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  104151. };
  104152. /**
  104153. * Sets the main texture desired size which is the closest power of two
  104154. * of the engine canvas size.
  104155. */
  104156. EffectLayer.prototype._setMainTextureSize = function () {
  104157. if (this._effectLayerOptions.mainTextureFixedSize) {
  104158. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  104159. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  104160. }
  104161. else {
  104162. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  104163. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  104164. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  104165. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  104166. }
  104167. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  104168. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  104169. };
  104170. /**
  104171. * Creates the main texture for the effect layer.
  104172. */
  104173. EffectLayer.prototype._createMainTexture = function () {
  104174. var _this = this;
  104175. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  104176. width: this._mainTextureDesiredSize.width,
  104177. height: this._mainTextureDesiredSize.height
  104178. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  104179. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  104180. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104181. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104182. this._mainTexture.anisotropicFilteringLevel = 1;
  104183. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  104184. this._mainTexture.renderParticles = false;
  104185. this._mainTexture.renderList = null;
  104186. this._mainTexture.ignoreCameraViewport = true;
  104187. // Custom render function
  104188. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  104189. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  104190. var index;
  104191. var engine = _this._scene.getEngine();
  104192. if (depthOnlySubMeshes.length) {
  104193. engine.setColorWrite(false);
  104194. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  104195. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  104196. }
  104197. engine.setColorWrite(true);
  104198. }
  104199. for (index = 0; index < opaqueSubMeshes.length; index++) {
  104200. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  104201. }
  104202. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  104203. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  104204. }
  104205. for (index = 0; index < transparentSubMeshes.length; index++) {
  104206. _this._renderSubMesh(transparentSubMeshes.data[index]);
  104207. }
  104208. };
  104209. this._mainTexture.onClearObservable.add(function (engine) {
  104210. engine.clear(_this.neutralColor, true, true, true);
  104211. });
  104212. };
  104213. /**
  104214. * Checks for the readiness of the element composing the layer.
  104215. * @param subMesh the mesh to check for
  104216. * @param useInstances specify wether or not to use instances to render the mesh
  104217. * @param emissiveTexture the associated emissive texture used to generate the glow
  104218. * @return true if ready otherwise, false
  104219. */
  104220. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  104221. var material = subMesh.getMaterial();
  104222. if (!material) {
  104223. return false;
  104224. }
  104225. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  104226. return false;
  104227. }
  104228. var defines = [];
  104229. var attribs = [BABYLON.VertexBuffer.PositionKind];
  104230. var mesh = subMesh.getMesh();
  104231. var uv1 = false;
  104232. var uv2 = false;
  104233. // Alpha test
  104234. if (material && material.needAlphaTesting()) {
  104235. var alphaTexture = material.getAlphaTestTexture();
  104236. if (alphaTexture) {
  104237. defines.push("#define ALPHATEST");
  104238. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  104239. alphaTexture.coordinatesIndex === 1) {
  104240. defines.push("#define DIFFUSEUV2");
  104241. uv2 = true;
  104242. }
  104243. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104244. defines.push("#define DIFFUSEUV1");
  104245. uv1 = true;
  104246. }
  104247. }
  104248. }
  104249. // Emissive
  104250. if (emissiveTexture) {
  104251. defines.push("#define EMISSIVE");
  104252. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  104253. emissiveTexture.coordinatesIndex === 1) {
  104254. defines.push("#define EMISSIVEUV2");
  104255. uv2 = true;
  104256. }
  104257. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104258. defines.push("#define EMISSIVEUV1");
  104259. uv1 = true;
  104260. }
  104261. }
  104262. if (uv1) {
  104263. attribs.push(BABYLON.VertexBuffer.UVKind);
  104264. defines.push("#define UV1");
  104265. }
  104266. if (uv2) {
  104267. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104268. defines.push("#define UV2");
  104269. }
  104270. // Bones
  104271. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104272. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104273. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104274. if (mesh.numBoneInfluencers > 4) {
  104275. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104276. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104277. }
  104278. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104279. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  104280. }
  104281. else {
  104282. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104283. }
  104284. // Morph targets
  104285. var manager = mesh.morphTargetManager;
  104286. var morphInfluencers = 0;
  104287. if (manager) {
  104288. if (manager.numInfluencers > 0) {
  104289. defines.push("#define MORPHTARGETS");
  104290. morphInfluencers = manager.numInfluencers;
  104291. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  104292. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  104293. }
  104294. }
  104295. // Instances
  104296. if (useInstances) {
  104297. defines.push("#define INSTANCES");
  104298. attribs.push("world0");
  104299. attribs.push("world1");
  104300. attribs.push("world2");
  104301. attribs.push("world3");
  104302. }
  104303. // Get correct effect
  104304. var join = defines.join("\n");
  104305. if (this._cachedDefines !== join) {
  104306. this._cachedDefines = join;
  104307. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  104308. }
  104309. return this._effectLayerMapGenerationEffect.isReady();
  104310. };
  104311. /**
  104312. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  104313. */
  104314. EffectLayer.prototype.render = function () {
  104315. var currentEffect = this._mergeEffect;
  104316. // Check
  104317. if (!currentEffect.isReady())
  104318. return;
  104319. for (var i = 0; i < this._postProcesses.length; i++) {
  104320. if (!this._postProcesses[i].isReady()) {
  104321. return;
  104322. }
  104323. }
  104324. var engine = this._scene.getEngine();
  104325. this.onBeforeComposeObservable.notifyObservers(this);
  104326. // Render
  104327. engine.enableEffect(currentEffect);
  104328. engine.setState(false);
  104329. // VBOs
  104330. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  104331. // Cache
  104332. var previousAlphaMode = engine.getAlphaMode();
  104333. // Go Blend.
  104334. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  104335. // Blends the map on the main canvas.
  104336. this._internalRender(currentEffect);
  104337. // Restore Alpha
  104338. engine.setAlphaMode(previousAlphaMode);
  104339. this.onAfterComposeObservable.notifyObservers(this);
  104340. // Handle size changes.
  104341. var size = this._mainTexture.getSize();
  104342. this._setMainTextureSize();
  104343. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  104344. // Recreate RTT and post processes on size change.
  104345. this.onSizeChangedObservable.notifyObservers(this);
  104346. this._disposeTextureAndPostProcesses();
  104347. this._createMainTexture();
  104348. this._createTextureAndPostProcesses();
  104349. }
  104350. };
  104351. /**
  104352. * Determine if a given mesh will be used in the current effect.
  104353. * @param mesh mesh to test
  104354. * @returns true if the mesh will be used
  104355. */
  104356. EffectLayer.prototype.hasMesh = function (mesh) {
  104357. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  104358. return true;
  104359. }
  104360. return false;
  104361. };
  104362. /**
  104363. * Returns true if the layer contains information to display, otherwise false.
  104364. * @returns true if the glow layer should be rendered
  104365. */
  104366. EffectLayer.prototype.shouldRender = function () {
  104367. return this.isEnabled && this._shouldRender;
  104368. };
  104369. /**
  104370. * Returns true if the mesh should render, otherwise false.
  104371. * @param mesh The mesh to render
  104372. * @returns true if it should render otherwise false
  104373. */
  104374. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  104375. return true;
  104376. };
  104377. /**
  104378. * Returns true if the mesh should render, otherwise false.
  104379. * @param mesh The mesh to render
  104380. * @returns true if it should render otherwise false
  104381. */
  104382. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  104383. return true;
  104384. };
  104385. /**
  104386. * Renders the submesh passed in parameter to the generation map.
  104387. */
  104388. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  104389. var _this = this;
  104390. if (!this.shouldRender()) {
  104391. return;
  104392. }
  104393. var material = subMesh.getMaterial();
  104394. var mesh = subMesh.getRenderingMesh();
  104395. var scene = this._scene;
  104396. var engine = scene.getEngine();
  104397. if (!material) {
  104398. return;
  104399. }
  104400. // Do not block in blend mode.
  104401. if (material.needAlphaBlendingForMesh(mesh)) {
  104402. return;
  104403. }
  104404. // Culling
  104405. engine.setState(material.backFaceCulling);
  104406. // Managing instances
  104407. var batch = mesh._getInstancesRenderList(subMesh._id);
  104408. if (batch.mustReturn) {
  104409. return;
  104410. }
  104411. // Early Exit per mesh
  104412. if (!this._shouldRenderMesh(mesh)) {
  104413. return;
  104414. }
  104415. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104416. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  104417. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  104418. engine.enableEffect(this._effectLayerMapGenerationEffect);
  104419. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  104420. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  104421. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  104422. // Alpha test
  104423. if (material && material.needAlphaTesting()) {
  104424. var alphaTexture = material.getAlphaTestTexture();
  104425. if (alphaTexture) {
  104426. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  104427. var textureMatrix = alphaTexture.getTextureMatrix();
  104428. if (textureMatrix) {
  104429. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  104430. }
  104431. }
  104432. }
  104433. // Glow emissive only
  104434. if (this._emissiveTextureAndColor.texture) {
  104435. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  104436. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  104437. }
  104438. // Bones
  104439. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104440. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104441. }
  104442. // Morph targets
  104443. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  104444. // Draw
  104445. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  104446. }
  104447. else {
  104448. // Need to reset refresh rate of the main map
  104449. this._mainTexture.resetRefreshCounter();
  104450. }
  104451. };
  104452. /**
  104453. * Rebuild the required buffers.
  104454. * @hidden Internal use only.
  104455. */
  104456. EffectLayer.prototype._rebuild = function () {
  104457. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104458. if (vb) {
  104459. vb._rebuild();
  104460. }
  104461. this._generateIndexBuffer();
  104462. };
  104463. /**
  104464. * Dispose only the render target textures and post process.
  104465. */
  104466. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  104467. this._mainTexture.dispose();
  104468. for (var i = 0; i < this._postProcesses.length; i++) {
  104469. if (this._postProcesses[i]) {
  104470. this._postProcesses[i].dispose();
  104471. }
  104472. }
  104473. this._postProcesses = [];
  104474. for (var i = 0; i < this._textures.length; i++) {
  104475. if (this._textures[i]) {
  104476. this._textures[i].dispose();
  104477. }
  104478. }
  104479. this._textures = [];
  104480. };
  104481. /**
  104482. * Dispose the highlight layer and free resources.
  104483. */
  104484. EffectLayer.prototype.dispose = function () {
  104485. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104486. if (vertexBuffer) {
  104487. vertexBuffer.dispose();
  104488. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  104489. }
  104490. if (this._indexBuffer) {
  104491. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  104492. this._indexBuffer = null;
  104493. }
  104494. // Clean textures and post processes
  104495. this._disposeTextureAndPostProcesses();
  104496. // Remove from scene
  104497. var index = this._scene.effectLayers.indexOf(this, 0);
  104498. if (index > -1) {
  104499. this._scene.effectLayers.splice(index, 1);
  104500. }
  104501. // Callback
  104502. this.onDisposeObservable.notifyObservers(this);
  104503. this.onDisposeObservable.clear();
  104504. this.onBeforeRenderMainTextureObservable.clear();
  104505. this.onBeforeComposeObservable.clear();
  104506. this.onAfterComposeObservable.clear();
  104507. this.onSizeChangedObservable.clear();
  104508. };
  104509. /**
  104510. * Gets the class name of the effect layer
  104511. * @returns the string with the class name of the effect layer
  104512. */
  104513. EffectLayer.prototype.getClassName = function () {
  104514. return "EffectLayer";
  104515. };
  104516. /**
  104517. * Creates an effect layer from parsed effect layer data
  104518. * @param parsedEffectLayer defines effect layer data
  104519. * @param scene defines the current scene
  104520. * @param rootUrl defines the root URL containing the effect layer information
  104521. * @returns a parsed effect Layer
  104522. */
  104523. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  104524. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  104525. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  104526. };
  104527. __decorate([
  104528. BABYLON.serialize()
  104529. ], EffectLayer.prototype, "name", void 0);
  104530. __decorate([
  104531. BABYLON.serializeAsColor4()
  104532. ], EffectLayer.prototype, "neutralColor", void 0);
  104533. __decorate([
  104534. BABYLON.serialize()
  104535. ], EffectLayer.prototype, "isEnabled", void 0);
  104536. __decorate([
  104537. BABYLON.serializeAsCameraReference()
  104538. ], EffectLayer.prototype, "camera", null);
  104539. __decorate([
  104540. BABYLON.serialize()
  104541. ], EffectLayer.prototype, "renderingGroupId", null);
  104542. return EffectLayer;
  104543. }());
  104544. BABYLON.EffectLayer = EffectLayer;
  104545. })(BABYLON || (BABYLON = {}));
  104546. //# sourceMappingURL=babylon.effectLayer.js.map
  104547. var BABYLON;
  104548. (function (BABYLON) {
  104549. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  104550. for (var index = 0; index < this.effectLayers.length; index++) {
  104551. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  104552. return this.effectLayers[index];
  104553. }
  104554. }
  104555. return null;
  104556. };
  104557. /**
  104558. * Special Glow Blur post process only blurring the alpha channel
  104559. * It enforces keeping the most luminous color in the color channel.
  104560. */
  104561. var GlowBlurPostProcess = /** @class */ (function (_super) {
  104562. __extends(GlowBlurPostProcess, _super);
  104563. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  104564. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  104565. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  104566. _this.direction = direction;
  104567. _this.kernel = kernel;
  104568. _this.onApplyObservable.add(function (effect) {
  104569. effect.setFloat2("screenSize", _this.width, _this.height);
  104570. effect.setVector2("direction", _this.direction);
  104571. effect.setFloat("blurWidth", _this.kernel);
  104572. });
  104573. return _this;
  104574. }
  104575. return GlowBlurPostProcess;
  104576. }(BABYLON.PostProcess));
  104577. /**
  104578. * The highlight layer Helps adding a glow effect around a mesh.
  104579. *
  104580. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  104581. * glowy meshes to your scene.
  104582. *
  104583. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  104584. */
  104585. var HighlightLayer = /** @class */ (function (_super) {
  104586. __extends(HighlightLayer, _super);
  104587. /**
  104588. * Instantiates a new highlight Layer and references it to the scene..
  104589. * @param name The name of the layer
  104590. * @param scene The scene to use the layer in
  104591. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  104592. */
  104593. function HighlightLayer(name, scene, options) {
  104594. var _this = _super.call(this, name, scene) || this;
  104595. _this.name = name;
  104596. /**
  104597. * Specifies whether or not the inner glow is ACTIVE in the layer.
  104598. */
  104599. _this.innerGlow = true;
  104600. /**
  104601. * Specifies whether or not the outer glow is ACTIVE in the layer.
  104602. */
  104603. _this.outerGlow = true;
  104604. /**
  104605. * An event triggered when the highlight layer is being blurred.
  104606. */
  104607. _this.onBeforeBlurObservable = new BABYLON.Observable();
  104608. /**
  104609. * An event triggered when the highlight layer has been blurred.
  104610. */
  104611. _this.onAfterBlurObservable = new BABYLON.Observable();
  104612. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  104613. _this._meshes = {};
  104614. _this._excludedMeshes = {};
  104615. _this.neutralColor = HighlightLayer.NeutralColor;
  104616. // Warn on stencil
  104617. if (!_this._engine.isStencilEnable) {
  104618. 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 }");
  104619. }
  104620. // Adapt options
  104621. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  104622. // Initialize the layer
  104623. _this._init({
  104624. alphaBlendingMode: _this._options.alphaBlendingMode,
  104625. camera: _this._options.camera,
  104626. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  104627. mainTextureRatio: _this._options.mainTextureRatio,
  104628. renderingGroupId: _this._options.renderingGroupId
  104629. });
  104630. // Do not render as long as no meshes have been added
  104631. _this._shouldRender = false;
  104632. return _this;
  104633. }
  104634. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  104635. /**
  104636. * Gets the horizontal size of the blur.
  104637. */
  104638. get: function () {
  104639. return this._horizontalBlurPostprocess.kernel;
  104640. },
  104641. /**
  104642. * Specifies the horizontal size of the blur.
  104643. */
  104644. set: function (value) {
  104645. this._horizontalBlurPostprocess.kernel = value;
  104646. },
  104647. enumerable: true,
  104648. configurable: true
  104649. });
  104650. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  104651. /**
  104652. * Gets the vertical size of the blur.
  104653. */
  104654. get: function () {
  104655. return this._verticalBlurPostprocess.kernel;
  104656. },
  104657. /**
  104658. * Specifies the vertical size of the blur.
  104659. */
  104660. set: function (value) {
  104661. this._verticalBlurPostprocess.kernel = value;
  104662. },
  104663. enumerable: true,
  104664. configurable: true
  104665. });
  104666. /**
  104667. * Get the effect name of the layer.
  104668. * @return The effect name
  104669. */
  104670. HighlightLayer.prototype.getEffectName = function () {
  104671. return HighlightLayer.EffectName;
  104672. };
  104673. /**
  104674. * Create the merge effect. This is the shader use to blit the information back
  104675. * to the main canvas at the end of the scene rendering.
  104676. */
  104677. HighlightLayer.prototype._createMergeEffect = function () {
  104678. // Effect
  104679. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  104680. };
  104681. /**
  104682. * Creates the render target textures and post processes used in the highlight layer.
  104683. */
  104684. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  104685. var _this = this;
  104686. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  104687. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  104688. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  104689. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  104690. var textureType = 0;
  104691. if (this._engine.getCaps().textureHalfFloatRender) {
  104692. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  104693. }
  104694. else {
  104695. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104696. }
  104697. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  104698. width: blurTextureWidth,
  104699. height: blurTextureHeight
  104700. }, this._scene, false, true, textureType);
  104701. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104702. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104703. this._blurTexture.anisotropicFilteringLevel = 16;
  104704. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  104705. this._blurTexture.renderParticles = false;
  104706. this._blurTexture.ignoreCameraViewport = true;
  104707. this._textures = [this._blurTexture];
  104708. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  104709. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104710. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  104711. effect.setTexture("textureSampler", _this._mainTexture);
  104712. });
  104713. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104714. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  104715. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  104716. });
  104717. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104718. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  104719. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  104720. });
  104721. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  104722. }
  104723. else {
  104724. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  104725. width: blurTextureWidth,
  104726. height: blurTextureHeight
  104727. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  104728. this._horizontalBlurPostprocess.width = blurTextureWidth;
  104729. this._horizontalBlurPostprocess.height = blurTextureHeight;
  104730. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  104731. effect.setTexture("textureSampler", _this._mainTexture);
  104732. });
  104733. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  104734. width: blurTextureWidth,
  104735. height: blurTextureHeight
  104736. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  104737. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  104738. }
  104739. this._mainTexture.onAfterUnbindObservable.add(function () {
  104740. _this.onBeforeBlurObservable.notifyObservers(_this);
  104741. var internalTexture = _this._blurTexture.getInternalTexture();
  104742. if (internalTexture) {
  104743. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  104744. }
  104745. _this.onAfterBlurObservable.notifyObservers(_this);
  104746. });
  104747. // Prevent autoClear.
  104748. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  104749. };
  104750. /**
  104751. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  104752. */
  104753. HighlightLayer.prototype.needStencil = function () {
  104754. return true;
  104755. };
  104756. /**
  104757. * Checks for the readiness of the element composing the layer.
  104758. * @param subMesh the mesh to check for
  104759. * @param useInstances specify wether or not to use instances to render the mesh
  104760. * @param emissiveTexture the associated emissive texture used to generate the glow
  104761. * @return true if ready otherwise, false
  104762. */
  104763. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  104764. var material = subMesh.getMaterial();
  104765. var mesh = subMesh.getRenderingMesh();
  104766. if (!material || !mesh || !this._meshes) {
  104767. return false;
  104768. }
  104769. var emissiveTexture = null;
  104770. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  104771. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  104772. emissiveTexture = material.emissiveTexture;
  104773. }
  104774. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  104775. };
  104776. /**
  104777. * Implementation specific of rendering the generating effect on the main canvas.
  104778. * @param effect The effect used to render through
  104779. */
  104780. HighlightLayer.prototype._internalRender = function (effect) {
  104781. // Texture
  104782. effect.setTexture("textureSampler", this._blurTexture);
  104783. // Cache
  104784. var engine = this._engine;
  104785. var previousStencilBuffer = engine.getStencilBuffer();
  104786. var previousStencilFunction = engine.getStencilFunction();
  104787. var previousStencilMask = engine.getStencilMask();
  104788. var previousStencilOperationPass = engine.getStencilOperationPass();
  104789. var previousStencilOperationFail = engine.getStencilOperationFail();
  104790. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  104791. var previousStencilReference = engine.getStencilFunctionReference();
  104792. // Stencil operations
  104793. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  104794. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  104795. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  104796. // Draw order
  104797. engine.setStencilMask(0x00);
  104798. engine.setStencilBuffer(true);
  104799. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  104800. // 2 passes inner outer
  104801. if (this.outerGlow) {
  104802. effect.setFloat("offset", 0);
  104803. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  104804. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104805. }
  104806. if (this.innerGlow) {
  104807. effect.setFloat("offset", 1);
  104808. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  104809. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104810. }
  104811. // Restore Cache
  104812. engine.setStencilFunction(previousStencilFunction);
  104813. engine.setStencilMask(previousStencilMask);
  104814. engine.setStencilBuffer(previousStencilBuffer);
  104815. engine.setStencilOperationPass(previousStencilOperationPass);
  104816. engine.setStencilOperationFail(previousStencilOperationFail);
  104817. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  104818. engine.setStencilFunctionReference(previousStencilReference);
  104819. };
  104820. /**
  104821. * Returns true if the layer contains information to display, otherwise false.
  104822. */
  104823. HighlightLayer.prototype.shouldRender = function () {
  104824. if (_super.prototype.shouldRender.call(this)) {
  104825. return this._meshes ? true : false;
  104826. }
  104827. return false;
  104828. };
  104829. /**
  104830. * Returns true if the mesh should render, otherwise false.
  104831. * @param mesh The mesh to render
  104832. * @returns true if it should render otherwise false
  104833. */
  104834. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  104835. // Excluded Mesh
  104836. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  104837. return false;
  104838. }
  104839. ;
  104840. if (!_super.prototype.hasMesh.call(this, mesh)) {
  104841. return false;
  104842. }
  104843. return true;
  104844. };
  104845. /**
  104846. * Sets the required values for both the emissive texture and and the main color.
  104847. */
  104848. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  104849. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  104850. if (highlightLayerMesh) {
  104851. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  104852. }
  104853. else {
  104854. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  104855. }
  104856. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  104857. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  104858. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  104859. }
  104860. else {
  104861. this._emissiveTextureAndColor.texture = null;
  104862. }
  104863. };
  104864. /**
  104865. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  104866. * @param mesh The mesh to exclude from the highlight layer
  104867. */
  104868. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  104869. if (!this._excludedMeshes) {
  104870. return;
  104871. }
  104872. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  104873. if (!meshExcluded) {
  104874. this._excludedMeshes[mesh.uniqueId] = {
  104875. mesh: mesh,
  104876. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  104877. mesh.getEngine().setStencilBuffer(false);
  104878. }),
  104879. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  104880. mesh.getEngine().setStencilBuffer(true);
  104881. }),
  104882. };
  104883. }
  104884. };
  104885. /**
  104886. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  104887. * @param mesh The mesh to highlight
  104888. */
  104889. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  104890. if (!this._excludedMeshes) {
  104891. return;
  104892. }
  104893. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  104894. if (meshExcluded) {
  104895. if (meshExcluded.beforeRender) {
  104896. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  104897. }
  104898. if (meshExcluded.afterRender) {
  104899. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  104900. }
  104901. }
  104902. this._excludedMeshes[mesh.uniqueId] = null;
  104903. };
  104904. /**
  104905. * Determine if a given mesh will be highlighted by the current HighlightLayer
  104906. * @param mesh mesh to test
  104907. * @returns true if the mesh will be highlighted by the current HighlightLayer
  104908. */
  104909. HighlightLayer.prototype.hasMesh = function (mesh) {
  104910. if (!this._meshes) {
  104911. return false;
  104912. }
  104913. if (!_super.prototype.hasMesh.call(this, mesh)) {
  104914. return false;
  104915. }
  104916. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  104917. };
  104918. /**
  104919. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  104920. * @param mesh The mesh to highlight
  104921. * @param color The color of the highlight
  104922. * @param glowEmissiveOnly Extract the glow from the emissive texture
  104923. */
  104924. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  104925. var _this = this;
  104926. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  104927. if (!this._meshes) {
  104928. return;
  104929. }
  104930. var meshHighlight = this._meshes[mesh.uniqueId];
  104931. if (meshHighlight) {
  104932. meshHighlight.color = color;
  104933. }
  104934. else {
  104935. this._meshes[mesh.uniqueId] = {
  104936. mesh: mesh,
  104937. color: color,
  104938. // Lambda required for capture due to Observable this context
  104939. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  104940. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  104941. _this._defaultStencilReference(mesh);
  104942. }
  104943. else {
  104944. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  104945. }
  104946. }),
  104947. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  104948. glowEmissiveOnly: glowEmissiveOnly
  104949. };
  104950. mesh.onDisposeObservable.add(function () {
  104951. _this._disposeMesh(mesh);
  104952. });
  104953. }
  104954. this._shouldRender = true;
  104955. };
  104956. /**
  104957. * Remove a mesh from the highlight layer in order to make it stop glowing.
  104958. * @param mesh The mesh to highlight
  104959. */
  104960. HighlightLayer.prototype.removeMesh = function (mesh) {
  104961. if (!this._meshes) {
  104962. return;
  104963. }
  104964. var meshHighlight = this._meshes[mesh.uniqueId];
  104965. if (meshHighlight) {
  104966. if (meshHighlight.observerHighlight) {
  104967. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  104968. }
  104969. if (meshHighlight.observerDefault) {
  104970. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  104971. }
  104972. delete this._meshes[mesh.uniqueId];
  104973. }
  104974. this._shouldRender = false;
  104975. for (var meshHighlightToCheck in this._meshes) {
  104976. if (this._meshes[meshHighlightToCheck]) {
  104977. this._shouldRender = true;
  104978. break;
  104979. }
  104980. }
  104981. };
  104982. /**
  104983. * Force the stencil to the normal expected value for none glowing parts
  104984. */
  104985. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  104986. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  104987. };
  104988. /**
  104989. * Free any resources and references associated to a mesh.
  104990. * Internal use
  104991. * @param mesh The mesh to free.
  104992. * @hidden
  104993. */
  104994. HighlightLayer.prototype._disposeMesh = function (mesh) {
  104995. this.removeMesh(mesh);
  104996. this.removeExcludedMesh(mesh);
  104997. };
  104998. /**
  104999. * Dispose the highlight layer and free resources.
  105000. */
  105001. HighlightLayer.prototype.dispose = function () {
  105002. if (this._meshes) {
  105003. // Clean mesh references
  105004. for (var id in this._meshes) {
  105005. var meshHighlight = this._meshes[id];
  105006. if (meshHighlight && meshHighlight.mesh) {
  105007. if (meshHighlight.observerHighlight) {
  105008. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  105009. }
  105010. if (meshHighlight.observerDefault) {
  105011. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  105012. }
  105013. }
  105014. }
  105015. this._meshes = null;
  105016. }
  105017. if (this._excludedMeshes) {
  105018. for (var id in this._excludedMeshes) {
  105019. var meshHighlight = this._excludedMeshes[id];
  105020. if (meshHighlight) {
  105021. if (meshHighlight.beforeRender) {
  105022. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  105023. }
  105024. if (meshHighlight.afterRender) {
  105025. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  105026. }
  105027. }
  105028. }
  105029. this._excludedMeshes = null;
  105030. }
  105031. _super.prototype.dispose.call(this);
  105032. };
  105033. /**
  105034. * Gets the class name of the effect layer
  105035. * @returns the string with the class name of the effect layer
  105036. */
  105037. HighlightLayer.prototype.getClassName = function () {
  105038. return "HighlightLayer";
  105039. };
  105040. /**
  105041. * Serializes this Highlight layer
  105042. * @returns a serialized Highlight layer object
  105043. */
  105044. HighlightLayer.prototype.serialize = function () {
  105045. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105046. serializationObject.customType = "BABYLON.HighlightLayer";
  105047. // Highlighted meshes
  105048. serializationObject.meshes = [];
  105049. if (this._meshes) {
  105050. for (var m in this._meshes) {
  105051. var mesh = this._meshes[m];
  105052. if (mesh) {
  105053. serializationObject.meshes.push({
  105054. glowEmissiveOnly: mesh.glowEmissiveOnly,
  105055. color: mesh.color.asArray(),
  105056. meshId: mesh.mesh.id
  105057. });
  105058. }
  105059. }
  105060. }
  105061. // Excluded meshes
  105062. serializationObject.excludedMeshes = [];
  105063. if (this._excludedMeshes) {
  105064. for (var e in this._excludedMeshes) {
  105065. var excludedMesh = this._excludedMeshes[e];
  105066. if (excludedMesh) {
  105067. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  105068. }
  105069. }
  105070. }
  105071. return serializationObject;
  105072. };
  105073. /**
  105074. * Creates a Highlight layer from parsed Highlight layer data
  105075. * @param parsedHightlightLayer defines the Highlight layer data
  105076. * @param scene defines the current scene
  105077. * @param rootUrl defines the root URL containing the Highlight layer information
  105078. * @returns a parsed Highlight layer
  105079. */
  105080. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  105081. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  105082. var index;
  105083. // Excluded meshes
  105084. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  105085. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  105086. if (mesh) {
  105087. hl.addExcludedMesh(mesh);
  105088. }
  105089. }
  105090. // Included meshes
  105091. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  105092. var highlightedMesh = parsedHightlightLayer.meshes[index];
  105093. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  105094. if (mesh) {
  105095. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  105096. }
  105097. }
  105098. return hl;
  105099. };
  105100. /**
  105101. * Effect Name of the highlight layer.
  105102. */
  105103. HighlightLayer.EffectName = "HighlightLayer";
  105104. /**
  105105. * The neutral color used during the preparation of the glow effect.
  105106. * This is black by default as the blend operation is a blend operation.
  105107. */
  105108. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  105109. /**
  105110. * Stencil value used for glowing meshes.
  105111. */
  105112. HighlightLayer.GlowingMeshStencilReference = 0x02;
  105113. /**
  105114. * Stencil value used for the other meshes in the scene.
  105115. */
  105116. HighlightLayer.NormalMeshStencilReference = 0x01;
  105117. __decorate([
  105118. BABYLON.serialize()
  105119. ], HighlightLayer.prototype, "innerGlow", void 0);
  105120. __decorate([
  105121. BABYLON.serialize()
  105122. ], HighlightLayer.prototype, "outerGlow", void 0);
  105123. __decorate([
  105124. BABYLON.serialize()
  105125. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  105126. __decorate([
  105127. BABYLON.serialize()
  105128. ], HighlightLayer.prototype, "blurVerticalSize", null);
  105129. __decorate([
  105130. BABYLON.serialize("options")
  105131. ], HighlightLayer.prototype, "_options", void 0);
  105132. return HighlightLayer;
  105133. }(BABYLON.EffectLayer));
  105134. BABYLON.HighlightLayer = HighlightLayer;
  105135. })(BABYLON || (BABYLON = {}));
  105136. //# sourceMappingURL=babylon.highlightLayer.js.map
  105137. var BABYLON;
  105138. (function (BABYLON) {
  105139. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  105140. for (var index = 0; index < this.effectLayers.length; index++) {
  105141. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  105142. return this.effectLayers[index];
  105143. }
  105144. }
  105145. return null;
  105146. };
  105147. /**
  105148. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  105149. *
  105150. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105151. * glowy meshes to your scene.
  105152. *
  105153. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  105154. */
  105155. var GlowLayer = /** @class */ (function (_super) {
  105156. __extends(GlowLayer, _super);
  105157. /**
  105158. * Instantiates a new glow Layer and references it to the scene.
  105159. * @param name The name of the layer
  105160. * @param scene The scene to use the layer in
  105161. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  105162. */
  105163. function GlowLayer(name, scene, options) {
  105164. var _this = _super.call(this, name, scene) || this;
  105165. _this._intensity = 1.0;
  105166. _this._includedOnlyMeshes = [];
  105167. _this._excludedMeshes = [];
  105168. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  105169. // Adapt options
  105170. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  105171. // Initialize the layer
  105172. _this._init({
  105173. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  105174. camera: _this._options.camera,
  105175. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105176. mainTextureRatio: _this._options.mainTextureRatio,
  105177. renderingGroupId: _this._options.renderingGroupId
  105178. });
  105179. return _this;
  105180. }
  105181. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  105182. /**
  105183. * Gets the kernel size of the blur.
  105184. */
  105185. get: function () {
  105186. return this._horizontalBlurPostprocess1.kernel;
  105187. },
  105188. /**
  105189. * Sets the kernel size of the blur.
  105190. */
  105191. set: function (value) {
  105192. this._horizontalBlurPostprocess1.kernel = value;
  105193. this._verticalBlurPostprocess1.kernel = value;
  105194. this._horizontalBlurPostprocess2.kernel = value;
  105195. this._verticalBlurPostprocess2.kernel = value;
  105196. },
  105197. enumerable: true,
  105198. configurable: true
  105199. });
  105200. Object.defineProperty(GlowLayer.prototype, "intensity", {
  105201. /**
  105202. * Gets the glow intensity.
  105203. */
  105204. get: function () {
  105205. return this._intensity;
  105206. },
  105207. /**
  105208. * Sets the glow intensity.
  105209. */
  105210. set: function (value) {
  105211. this._intensity = value;
  105212. },
  105213. enumerable: true,
  105214. configurable: true
  105215. });
  105216. /**
  105217. * Get the effect name of the layer.
  105218. * @return The effect name
  105219. */
  105220. GlowLayer.prototype.getEffectName = function () {
  105221. return GlowLayer.EffectName;
  105222. };
  105223. /**
  105224. * Create the merge effect. This is the shader use to blit the information back
  105225. * to the main canvas at the end of the scene rendering.
  105226. */
  105227. GlowLayer.prototype._createMergeEffect = function () {
  105228. // Effect
  105229. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  105230. };
  105231. /**
  105232. * Creates the render target textures and post processes used in the glow layer.
  105233. */
  105234. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  105235. var _this = this;
  105236. var blurTextureWidth = this._mainTextureDesiredSize.width;
  105237. var blurTextureHeight = this._mainTextureDesiredSize.height;
  105238. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105239. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105240. var textureType = 0;
  105241. if (this._engine.getCaps().textureHalfFloatRender) {
  105242. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105243. }
  105244. else {
  105245. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105246. }
  105247. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  105248. width: blurTextureWidth,
  105249. height: blurTextureHeight
  105250. }, this._scene, false, true, textureType);
  105251. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105252. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105253. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105254. this._blurTexture1.renderParticles = false;
  105255. this._blurTexture1.ignoreCameraViewport = true;
  105256. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  105257. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  105258. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  105259. width: blurTextureWidth2,
  105260. height: blurTextureHeight2
  105261. }, this._scene, false, true, textureType);
  105262. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105263. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105264. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105265. this._blurTexture2.renderParticles = false;
  105266. this._blurTexture2.ignoreCameraViewport = true;
  105267. this._textures = [this._blurTexture1, this._blurTexture2];
  105268. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  105269. width: blurTextureWidth,
  105270. height: blurTextureHeight
  105271. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105272. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  105273. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  105274. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  105275. effect.setTexture("textureSampler", _this._mainTexture);
  105276. });
  105277. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  105278. width: blurTextureWidth,
  105279. height: blurTextureHeight
  105280. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105281. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  105282. width: blurTextureWidth2,
  105283. height: blurTextureHeight2
  105284. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105285. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  105286. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  105287. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  105288. effect.setTexture("textureSampler", _this._blurTexture1);
  105289. });
  105290. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  105291. width: blurTextureWidth2,
  105292. height: blurTextureHeight2
  105293. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105294. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  105295. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  105296. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  105297. this._mainTexture.samples = this._options.mainTextureSamples;
  105298. this._mainTexture.onAfterUnbindObservable.add(function () {
  105299. var internalTexture = _this._blurTexture1.getInternalTexture();
  105300. if (internalTexture) {
  105301. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  105302. internalTexture = _this._blurTexture2.getInternalTexture();
  105303. if (internalTexture) {
  105304. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  105305. }
  105306. }
  105307. });
  105308. // Prevent autoClear.
  105309. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105310. };
  105311. /**
  105312. * Checks for the readiness of the element composing the layer.
  105313. * @param subMesh the mesh to check for
  105314. * @param useInstances specify wether or not to use instances to render the mesh
  105315. * @param emissiveTexture the associated emissive texture used to generate the glow
  105316. * @return true if ready otherwise, false
  105317. */
  105318. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  105319. var material = subMesh.getMaterial();
  105320. var mesh = subMesh.getRenderingMesh();
  105321. if (!material || !mesh) {
  105322. return false;
  105323. }
  105324. var emissiveTexture = material.emissiveTexture;
  105325. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105326. };
  105327. /**
  105328. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105329. */
  105330. GlowLayer.prototype.needStencil = function () {
  105331. return false;
  105332. };
  105333. /**
  105334. * Implementation specific of rendering the generating effect on the main canvas.
  105335. * @param effect The effect used to render through
  105336. */
  105337. GlowLayer.prototype._internalRender = function (effect) {
  105338. // Texture
  105339. effect.setTexture("textureSampler", this._blurTexture1);
  105340. effect.setTexture("textureSampler2", this._blurTexture2);
  105341. effect.setFloat("offset", this._intensity);
  105342. // Cache
  105343. var engine = this._engine;
  105344. var previousStencilBuffer = engine.getStencilBuffer();
  105345. // Draw order
  105346. engine.setStencilBuffer(false);
  105347. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105348. // Draw order
  105349. engine.setStencilBuffer(previousStencilBuffer);
  105350. };
  105351. /**
  105352. * Sets the required values for both the emissive texture and and the main color.
  105353. */
  105354. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105355. var textureLevel = 1.0;
  105356. if (this.customEmissiveTextureSelector) {
  105357. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  105358. }
  105359. else {
  105360. if (material) {
  105361. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105362. if (this._emissiveTextureAndColor.texture) {
  105363. textureLevel = this._emissiveTextureAndColor.texture.level;
  105364. }
  105365. }
  105366. else {
  105367. this._emissiveTextureAndColor.texture = null;
  105368. }
  105369. }
  105370. if (this.customEmissiveColorSelector) {
  105371. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  105372. }
  105373. else {
  105374. if (material.emissiveColor) {
  105375. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  105376. }
  105377. else {
  105378. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105379. }
  105380. }
  105381. };
  105382. /**
  105383. * Returns true if the mesh should render, otherwise false.
  105384. * @param mesh The mesh to render
  105385. * @returns true if it should render otherwise false
  105386. */
  105387. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  105388. return this.hasMesh(mesh);
  105389. };
  105390. /**
  105391. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  105392. * @param mesh The mesh to exclude from the glow layer
  105393. */
  105394. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  105395. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  105396. this._excludedMeshes.push(mesh.uniqueId);
  105397. }
  105398. };
  105399. /**
  105400. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  105401. * @param mesh The mesh to remove
  105402. */
  105403. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  105404. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  105405. if (index !== -1) {
  105406. this._excludedMeshes.splice(index, 1);
  105407. }
  105408. };
  105409. /**
  105410. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  105411. * @param mesh The mesh to include in the glow layer
  105412. */
  105413. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  105414. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  105415. this._includedOnlyMeshes.push(mesh.uniqueId);
  105416. }
  105417. };
  105418. /**
  105419. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  105420. * @param mesh The mesh to remove
  105421. */
  105422. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  105423. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  105424. if (index !== -1) {
  105425. this._includedOnlyMeshes.splice(index, 1);
  105426. }
  105427. };
  105428. /**
  105429. * Determine if a given mesh will be used in the glow layer
  105430. * @param mesh The mesh to test
  105431. * @returns true if the mesh will be highlighted by the current glow layer
  105432. */
  105433. GlowLayer.prototype.hasMesh = function (mesh) {
  105434. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105435. return false;
  105436. }
  105437. // Included Mesh
  105438. if (this._includedOnlyMeshes.length) {
  105439. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  105440. }
  105441. ;
  105442. // Excluded Mesh
  105443. if (this._excludedMeshes.length) {
  105444. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  105445. }
  105446. ;
  105447. return true;
  105448. };
  105449. /**
  105450. * Free any resources and references associated to a mesh.
  105451. * Internal use
  105452. * @param mesh The mesh to free.
  105453. * @hidden
  105454. */
  105455. GlowLayer.prototype._disposeMesh = function (mesh) {
  105456. this.removeIncludedOnlyMesh(mesh);
  105457. this.removeExcludedMesh(mesh);
  105458. };
  105459. /**
  105460. * Gets the class name of the effect layer
  105461. * @returns the string with the class name of the effect layer
  105462. */
  105463. GlowLayer.prototype.getClassName = function () {
  105464. return "GlowLayer";
  105465. };
  105466. /**
  105467. * Serializes this glow layer
  105468. * @returns a serialized glow layer object
  105469. */
  105470. GlowLayer.prototype.serialize = function () {
  105471. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105472. serializationObject.customType = "BABYLON.GlowLayer";
  105473. var index;
  105474. // Included meshes
  105475. serializationObject.includedMeshes = [];
  105476. if (this._includedOnlyMeshes.length) {
  105477. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  105478. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  105479. if (mesh) {
  105480. serializationObject.includedMeshes.push(mesh.id);
  105481. }
  105482. }
  105483. }
  105484. // Excluded meshes
  105485. serializationObject.excludedMeshes = [];
  105486. if (this._excludedMeshes.length) {
  105487. for (index = 0; index < this._excludedMeshes.length; index++) {
  105488. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  105489. if (mesh) {
  105490. serializationObject.excludedMeshes.push(mesh.id);
  105491. }
  105492. }
  105493. }
  105494. return serializationObject;
  105495. };
  105496. /**
  105497. * Creates a Glow Layer from parsed glow layer data
  105498. * @param parsedGlowLayer defines glow layer data
  105499. * @param scene defines the current scene
  105500. * @param rootUrl defines the root URL containing the glow layer information
  105501. * @returns a parsed Glow Layer
  105502. */
  105503. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  105504. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  105505. var index;
  105506. // Excluded meshes
  105507. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  105508. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  105509. if (mesh) {
  105510. gl.addExcludedMesh(mesh);
  105511. }
  105512. }
  105513. // Included meshes
  105514. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  105515. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  105516. if (mesh) {
  105517. gl.addIncludedOnlyMesh(mesh);
  105518. }
  105519. }
  105520. return gl;
  105521. };
  105522. /**
  105523. * Effect Name of the layer.
  105524. */
  105525. GlowLayer.EffectName = "GlowLayer";
  105526. /**
  105527. * The default blur kernel size used for the glow.
  105528. */
  105529. GlowLayer.DefaultBlurKernelSize = 32;
  105530. /**
  105531. * The default texture size ratio used for the glow.
  105532. */
  105533. GlowLayer.DefaultTextureRatio = 0.5;
  105534. __decorate([
  105535. BABYLON.serialize()
  105536. ], GlowLayer.prototype, "blurKernelSize", null);
  105537. __decorate([
  105538. BABYLON.serialize()
  105539. ], GlowLayer.prototype, "intensity", null);
  105540. __decorate([
  105541. BABYLON.serialize("options")
  105542. ], GlowLayer.prototype, "_options", void 0);
  105543. return GlowLayer;
  105544. }(BABYLON.EffectLayer));
  105545. BABYLON.GlowLayer = GlowLayer;
  105546. })(BABYLON || (BABYLON = {}));
  105547. //# sourceMappingURL=babylon.glowLayer.js.map
  105548. var BABYLON;
  105549. (function (BABYLON) {
  105550. /**
  105551. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  105552. */
  105553. var AssetTaskState;
  105554. (function (AssetTaskState) {
  105555. /**
  105556. * Initialization
  105557. */
  105558. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  105559. /**
  105560. * Running
  105561. */
  105562. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  105563. /**
  105564. * Done
  105565. */
  105566. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  105567. /**
  105568. * Error
  105569. */
  105570. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  105571. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  105572. /**
  105573. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  105574. */
  105575. var AbstractAssetTask = /** @class */ (function () {
  105576. /**
  105577. * Creates a new {BABYLON.AssetsManager}
  105578. * @param name defines the name of the task
  105579. */
  105580. function AbstractAssetTask(
  105581. /**
  105582. * Task name
  105583. */ name) {
  105584. this.name = name;
  105585. this._isCompleted = false;
  105586. this._taskState = AssetTaskState.INIT;
  105587. }
  105588. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  105589. /**
  105590. * Get if the task is completed
  105591. */
  105592. get: function () {
  105593. return this._isCompleted;
  105594. },
  105595. enumerable: true,
  105596. configurable: true
  105597. });
  105598. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  105599. /**
  105600. * Gets the current state of the task
  105601. */
  105602. get: function () {
  105603. return this._taskState;
  105604. },
  105605. enumerable: true,
  105606. configurable: true
  105607. });
  105608. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  105609. /**
  105610. * Gets the current error object (if task is in error)
  105611. */
  105612. get: function () {
  105613. return this._errorObject;
  105614. },
  105615. enumerable: true,
  105616. configurable: true
  105617. });
  105618. /**
  105619. * Internal only
  105620. * @hidden
  105621. */
  105622. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  105623. if (this._errorObject) {
  105624. return;
  105625. }
  105626. this._errorObject = {
  105627. message: message,
  105628. exception: exception
  105629. };
  105630. };
  105631. /**
  105632. * Execute the current task
  105633. * @param scene defines the scene where you want your assets to be loaded
  105634. * @param onSuccess is a callback called when the task is successfully executed
  105635. * @param onError is a callback called if an error occurs
  105636. */
  105637. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  105638. var _this = this;
  105639. this._taskState = AssetTaskState.RUNNING;
  105640. this.runTask(scene, function () {
  105641. _this.onDoneCallback(onSuccess, onError);
  105642. }, function (msg, exception) {
  105643. _this.onErrorCallback(onError, msg, exception);
  105644. });
  105645. };
  105646. /**
  105647. * Execute the current task
  105648. * @param scene defines the scene where you want your assets to be loaded
  105649. * @param onSuccess is a callback called when the task is successfully executed
  105650. * @param onError is a callback called if an error occurs
  105651. */
  105652. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105653. throw new Error("runTask is not implemented");
  105654. };
  105655. /**
  105656. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  105657. * This can be used with failed tasks that have the reason for failure fixed.
  105658. */
  105659. AbstractAssetTask.prototype.reset = function () {
  105660. this._taskState = AssetTaskState.INIT;
  105661. };
  105662. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  105663. this._taskState = AssetTaskState.ERROR;
  105664. this._errorObject = {
  105665. message: message,
  105666. exception: exception
  105667. };
  105668. if (this.onError) {
  105669. this.onError(this, message, exception);
  105670. }
  105671. onError();
  105672. };
  105673. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  105674. try {
  105675. this._taskState = AssetTaskState.DONE;
  105676. this._isCompleted = true;
  105677. if (this.onSuccess) {
  105678. this.onSuccess(this);
  105679. }
  105680. onSuccess();
  105681. }
  105682. catch (e) {
  105683. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  105684. }
  105685. };
  105686. return AbstractAssetTask;
  105687. }());
  105688. BABYLON.AbstractAssetTask = AbstractAssetTask;
  105689. /**
  105690. * Class used to share progress information about assets loading
  105691. */
  105692. var AssetsProgressEvent = /** @class */ (function () {
  105693. /**
  105694. * Creates a {BABYLON.AssetsProgressEvent}
  105695. * @param remainingCount defines the number of remaining tasks to process
  105696. * @param totalCount defines the total number of tasks
  105697. * @param task defines the task that was just processed
  105698. */
  105699. function AssetsProgressEvent(remainingCount, totalCount, task) {
  105700. this.remainingCount = remainingCount;
  105701. this.totalCount = totalCount;
  105702. this.task = task;
  105703. }
  105704. return AssetsProgressEvent;
  105705. }());
  105706. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  105707. /**
  105708. * Define a task used by {BABYLON.AssetsManager} to load meshes
  105709. */
  105710. var MeshAssetTask = /** @class */ (function (_super) {
  105711. __extends(MeshAssetTask, _super);
  105712. /**
  105713. * Creates a new {BABYLON.MeshAssetTask}
  105714. * @param name defines the name of the task
  105715. * @param meshesNames defines the list of mesh's names you want to load
  105716. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  105717. * @param sceneFilename defines the filename of the scene to load from
  105718. */
  105719. function MeshAssetTask(
  105720. /**
  105721. * Defines the name of the task
  105722. */
  105723. name,
  105724. /**
  105725. * Defines the list of mesh's names you want to load
  105726. */
  105727. meshesNames,
  105728. /**
  105729. * Defines the root url to use as a base to load your meshes and associated resources
  105730. */
  105731. rootUrl,
  105732. /**
  105733. * Defines the filename of the scene to load from
  105734. */
  105735. sceneFilename) {
  105736. var _this = _super.call(this, name) || this;
  105737. _this.name = name;
  105738. _this.meshesNames = meshesNames;
  105739. _this.rootUrl = rootUrl;
  105740. _this.sceneFilename = sceneFilename;
  105741. return _this;
  105742. }
  105743. /**
  105744. * Execute the current task
  105745. * @param scene defines the scene where you want your assets to be loaded
  105746. * @param onSuccess is a callback called when the task is successfully executed
  105747. * @param onError is a callback called if an error occurs
  105748. */
  105749. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105750. var _this = this;
  105751. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  105752. _this.loadedMeshes = meshes;
  105753. _this.loadedParticleSystems = particleSystems;
  105754. _this.loadedSkeletons = skeletons;
  105755. onSuccess();
  105756. }, null, function (scene, message, exception) {
  105757. onError(message, exception);
  105758. });
  105759. };
  105760. return MeshAssetTask;
  105761. }(AbstractAssetTask));
  105762. BABYLON.MeshAssetTask = MeshAssetTask;
  105763. /**
  105764. * Define a task used by {BABYLON.AssetsManager} to load text content
  105765. */
  105766. var TextFileAssetTask = /** @class */ (function (_super) {
  105767. __extends(TextFileAssetTask, _super);
  105768. /**
  105769. * Creates a new TextFileAssetTask object
  105770. * @param name defines the name of the task
  105771. * @param url defines the location of the file to load
  105772. */
  105773. function TextFileAssetTask(
  105774. /**
  105775. * Defines the name of the task
  105776. */
  105777. name,
  105778. /**
  105779. * Defines the location of the file to load
  105780. */
  105781. url) {
  105782. var _this = _super.call(this, name) || this;
  105783. _this.name = name;
  105784. _this.url = url;
  105785. return _this;
  105786. }
  105787. /**
  105788. * Execute the current task
  105789. * @param scene defines the scene where you want your assets to be loaded
  105790. * @param onSuccess is a callback called when the task is successfully executed
  105791. * @param onError is a callback called if an error occurs
  105792. */
  105793. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105794. var _this = this;
  105795. scene._loadFile(this.url, function (data) {
  105796. _this.text = data;
  105797. onSuccess();
  105798. }, undefined, false, false, function (request, exception) {
  105799. if (request) {
  105800. onError(request.status + " " + request.statusText, exception);
  105801. }
  105802. });
  105803. };
  105804. return TextFileAssetTask;
  105805. }(AbstractAssetTask));
  105806. BABYLON.TextFileAssetTask = TextFileAssetTask;
  105807. /**
  105808. * Define a task used by {BABYLON.AssetsManager} to load binary data
  105809. */
  105810. var BinaryFileAssetTask = /** @class */ (function (_super) {
  105811. __extends(BinaryFileAssetTask, _super);
  105812. /**
  105813. * Creates a new BinaryFileAssetTask object
  105814. * @param name defines the name of the new task
  105815. * @param url defines the location of the file to load
  105816. */
  105817. function BinaryFileAssetTask(
  105818. /**
  105819. * Defines the name of the task
  105820. */
  105821. name,
  105822. /**
  105823. * Defines the location of the file to load
  105824. */
  105825. url) {
  105826. var _this = _super.call(this, name) || this;
  105827. _this.name = name;
  105828. _this.url = url;
  105829. return _this;
  105830. }
  105831. /**
  105832. * Execute the current task
  105833. * @param scene defines the scene where you want your assets to be loaded
  105834. * @param onSuccess is a callback called when the task is successfully executed
  105835. * @param onError is a callback called if an error occurs
  105836. */
  105837. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105838. var _this = this;
  105839. scene._loadFile(this.url, function (data) {
  105840. _this.data = data;
  105841. onSuccess();
  105842. }, undefined, true, true, function (request, exception) {
  105843. if (request) {
  105844. onError(request.status + " " + request.statusText, exception);
  105845. }
  105846. });
  105847. };
  105848. return BinaryFileAssetTask;
  105849. }(AbstractAssetTask));
  105850. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  105851. /**
  105852. * Define a task used by {BABYLON.AssetsManager} to load images
  105853. */
  105854. var ImageAssetTask = /** @class */ (function (_super) {
  105855. __extends(ImageAssetTask, _super);
  105856. /**
  105857. * Creates a new ImageAssetTask
  105858. * @param name defines the name of the task
  105859. * @param url defines the location of the image to load
  105860. */
  105861. function ImageAssetTask(
  105862. /**
  105863. * Defines the name of the task
  105864. */
  105865. name,
  105866. /**
  105867. * Defines the location of the image to load
  105868. */
  105869. url) {
  105870. var _this = _super.call(this, name) || this;
  105871. _this.name = name;
  105872. _this.url = url;
  105873. return _this;
  105874. }
  105875. /**
  105876. * Execute the current task
  105877. * @param scene defines the scene where you want your assets to be loaded
  105878. * @param onSuccess is a callback called when the task is successfully executed
  105879. * @param onError is a callback called if an error occurs
  105880. */
  105881. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105882. var _this = this;
  105883. var img = new Image();
  105884. BABYLON.Tools.SetCorsBehavior(this.url, img);
  105885. img.onload = function () {
  105886. _this.image = img;
  105887. onSuccess();
  105888. };
  105889. img.onerror = function (err) {
  105890. onError("Error loading image", err);
  105891. };
  105892. img.src = this.url;
  105893. };
  105894. return ImageAssetTask;
  105895. }(AbstractAssetTask));
  105896. BABYLON.ImageAssetTask = ImageAssetTask;
  105897. /**
  105898. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  105899. */
  105900. var TextureAssetTask = /** @class */ (function (_super) {
  105901. __extends(TextureAssetTask, _super);
  105902. /**
  105903. * Creates a new TextureAssetTask object
  105904. * @param name defines the name of the task
  105905. * @param url defines the location of the file to load
  105906. * @param noMipmap defines if mipmap should not be generated (default is false)
  105907. * @param invertY defines if texture must be inverted on Y axis (default is false)
  105908. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  105909. */
  105910. function TextureAssetTask(
  105911. /**
  105912. * Defines the name of the task
  105913. */
  105914. name,
  105915. /**
  105916. * Defines the location of the file to load
  105917. */
  105918. url,
  105919. /**
  105920. * Defines if mipmap should not be generated (default is false)
  105921. */
  105922. noMipmap,
  105923. /**
  105924. * Defines if texture must be inverted on Y axis (default is false)
  105925. */
  105926. invertY,
  105927. /**
  105928. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  105929. */
  105930. samplingMode) {
  105931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  105932. var _this = _super.call(this, name) || this;
  105933. _this.name = name;
  105934. _this.url = url;
  105935. _this.noMipmap = noMipmap;
  105936. _this.invertY = invertY;
  105937. _this.samplingMode = samplingMode;
  105938. return _this;
  105939. }
  105940. /**
  105941. * Execute the current task
  105942. * @param scene defines the scene where you want your assets to be loaded
  105943. * @param onSuccess is a callback called when the task is successfully executed
  105944. * @param onError is a callback called if an error occurs
  105945. */
  105946. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105947. var onload = function () {
  105948. onSuccess();
  105949. };
  105950. var onerror = function (message, exception) {
  105951. onError(message, exception);
  105952. };
  105953. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  105954. };
  105955. return TextureAssetTask;
  105956. }(AbstractAssetTask));
  105957. BABYLON.TextureAssetTask = TextureAssetTask;
  105958. /**
  105959. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  105960. */
  105961. var CubeTextureAssetTask = /** @class */ (function (_super) {
  105962. __extends(CubeTextureAssetTask, _super);
  105963. /**
  105964. * Creates a new CubeTextureAssetTask
  105965. * @param name defines the name of the task
  105966. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  105967. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  105968. * @param noMipmap defines if mipmaps should not be generated (default is false)
  105969. * @param files defines the explicit list of files (undefined by default)
  105970. */
  105971. function CubeTextureAssetTask(
  105972. /**
  105973. * Defines the name of the task
  105974. */
  105975. name,
  105976. /**
  105977. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  105978. */
  105979. url,
  105980. /**
  105981. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  105982. */
  105983. extensions,
  105984. /**
  105985. * Defines if mipmaps should not be generated (default is false)
  105986. */
  105987. noMipmap,
  105988. /**
  105989. * Defines the explicit list of files (undefined by default)
  105990. */
  105991. files) {
  105992. var _this = _super.call(this, name) || this;
  105993. _this.name = name;
  105994. _this.url = url;
  105995. _this.extensions = extensions;
  105996. _this.noMipmap = noMipmap;
  105997. _this.files = files;
  105998. return _this;
  105999. }
  106000. /**
  106001. * Execute the current task
  106002. * @param scene defines the scene where you want your assets to be loaded
  106003. * @param onSuccess is a callback called when the task is successfully executed
  106004. * @param onError is a callback called if an error occurs
  106005. */
  106006. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106007. var onload = function () {
  106008. onSuccess();
  106009. };
  106010. var onerror = function (message, exception) {
  106011. onError(message, exception);
  106012. };
  106013. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  106014. };
  106015. return CubeTextureAssetTask;
  106016. }(AbstractAssetTask));
  106017. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  106018. /**
  106019. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  106020. */
  106021. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  106022. __extends(HDRCubeTextureAssetTask, _super);
  106023. /**
  106024. * Creates a new HDRCubeTextureAssetTask object
  106025. * @param name defines the name of the task
  106026. * @param url defines the location of the file to load
  106027. * @param size defines the 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.
  106028. * @param noMipmap defines if mipmaps should not be generated (default is false)
  106029. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  106030. * @param gammaSpace 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) (default is false)
  106031. * @param reserved Internal use only
  106032. */
  106033. function HDRCubeTextureAssetTask(
  106034. /**
  106035. * Defines the name of the task
  106036. */
  106037. name,
  106038. /**
  106039. * Defines the location of the file to load
  106040. */
  106041. url,
  106042. /**
  106043. * Defines the desired size (the more it increases the longer the generation will be)
  106044. */
  106045. size,
  106046. /**
  106047. * Defines if mipmaps should not be generated (default is false)
  106048. */
  106049. noMipmap,
  106050. /**
  106051. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  106052. */
  106053. generateHarmonics,
  106054. /**
  106055. * 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) (default is false)
  106056. */
  106057. gammaSpace,
  106058. /**
  106059. * Internal Use Only
  106060. */
  106061. reserved) {
  106062. if (noMipmap === void 0) { noMipmap = false; }
  106063. if (generateHarmonics === void 0) { generateHarmonics = true; }
  106064. if (gammaSpace === void 0) { gammaSpace = false; }
  106065. if (reserved === void 0) { reserved = false; }
  106066. var _this = _super.call(this, name) || this;
  106067. _this.name = name;
  106068. _this.url = url;
  106069. _this.size = size;
  106070. _this.noMipmap = noMipmap;
  106071. _this.generateHarmonics = generateHarmonics;
  106072. _this.gammaSpace = gammaSpace;
  106073. _this.reserved = reserved;
  106074. return _this;
  106075. }
  106076. /**
  106077. * Execute the current task
  106078. * @param scene defines the scene where you want your assets to be loaded
  106079. * @param onSuccess is a callback called when the task is successfully executed
  106080. * @param onError is a callback called if an error occurs
  106081. */
  106082. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106083. var onload = function () {
  106084. onSuccess();
  106085. };
  106086. var onerror = function (message, exception) {
  106087. onError(message, exception);
  106088. };
  106089. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  106090. };
  106091. return HDRCubeTextureAssetTask;
  106092. }(AbstractAssetTask));
  106093. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  106094. /**
  106095. * This class can be used to easily import assets into a scene
  106096. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  106097. */
  106098. var AssetsManager = /** @class */ (function () {
  106099. /**
  106100. * Creates a new AssetsManager
  106101. * @param scene defines the scene to work on
  106102. */
  106103. function AssetsManager(scene) {
  106104. this._isLoading = false;
  106105. this._tasks = new Array();
  106106. this._waitingTasksCount = 0;
  106107. this._totalTasksCount = 0;
  106108. /**
  106109. * Observable called when all tasks are processed
  106110. */
  106111. this.onTaskSuccessObservable = new BABYLON.Observable();
  106112. /**
  106113. * Observable called when a task had an error
  106114. */
  106115. this.onTaskErrorObservable = new BABYLON.Observable();
  106116. /**
  106117. * Observable called when a task is successful
  106118. */
  106119. this.onTasksDoneObservable = new BABYLON.Observable();
  106120. /**
  106121. * Observable called when a task is done (whatever the result is)
  106122. */
  106123. this.onProgressObservable = new BABYLON.Observable();
  106124. /**
  106125. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  106126. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  106127. */
  106128. this.useDefaultLoadingScreen = true;
  106129. this._scene = scene;
  106130. }
  106131. /**
  106132. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  106133. * @param taskName defines the name of the new task
  106134. * @param meshesNames defines the name of meshes to load
  106135. * @param rootUrl defines the root url to use to locate files
  106136. * @param sceneFilename defines the filename of the scene file
  106137. * @returns a new {BABYLON.MeshAssetTask} object
  106138. */
  106139. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  106140. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  106141. this._tasks.push(task);
  106142. return task;
  106143. };
  106144. /**
  106145. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  106146. * @param taskName defines the name of the new task
  106147. * @param url defines the url of the file to load
  106148. * @returns a new {BABYLON.TextFileAssetTask} object
  106149. */
  106150. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  106151. var task = new TextFileAssetTask(taskName, url);
  106152. this._tasks.push(task);
  106153. return task;
  106154. };
  106155. /**
  106156. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  106157. * @param taskName defines the name of the new task
  106158. * @param url defines the url of the file to load
  106159. * @returns a new {BABYLON.BinaryFileAssetTask} object
  106160. */
  106161. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  106162. var task = new BinaryFileAssetTask(taskName, url);
  106163. this._tasks.push(task);
  106164. return task;
  106165. };
  106166. /**
  106167. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  106168. * @param taskName defines the name of the new task
  106169. * @param url defines the url of the file to load
  106170. * @returns a new {BABYLON.ImageAssetTask} object
  106171. */
  106172. AssetsManager.prototype.addImageTask = function (taskName, url) {
  106173. var task = new ImageAssetTask(taskName, url);
  106174. this._tasks.push(task);
  106175. return task;
  106176. };
  106177. /**
  106178. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  106179. * @param taskName defines the name of the new task
  106180. * @param url defines the url of the file to load
  106181. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106182. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  106183. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  106184. * @returns a new {BABYLON.TextureAssetTask} object
  106185. */
  106186. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  106187. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106188. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  106189. this._tasks.push(task);
  106190. return task;
  106191. };
  106192. /**
  106193. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  106194. * @param taskName defines the name of the new task
  106195. * @param url defines the url of the file to load
  106196. * @param extensions defines the extension to use to load the cube map (can be null)
  106197. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106198. * @param files defines the list of files to load (can be null)
  106199. * @returns a new {BABYLON.CubeTextureAssetTask} object
  106200. */
  106201. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  106202. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  106203. this._tasks.push(task);
  106204. return task;
  106205. };
  106206. /**
  106207. *
  106208. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  106209. * @param taskName defines the name of the new task
  106210. * @param url defines the url of the file to load
  106211. * @param size defines the size you want for the cubemap (can be null)
  106212. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106213. * @param generateHarmonics defines if you want to automatically generate (true by default)
  106214. * @param gammaSpace 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) (default is false)
  106215. * @param reserved Internal use only
  106216. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  106217. */
  106218. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  106219. if (noMipmap === void 0) { noMipmap = false; }
  106220. if (generateHarmonics === void 0) { generateHarmonics = true; }
  106221. if (gammaSpace === void 0) { gammaSpace = false; }
  106222. if (reserved === void 0) { reserved = false; }
  106223. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  106224. this._tasks.push(task);
  106225. return task;
  106226. };
  106227. /**
  106228. * Remove a task from the assets manager.
  106229. * @param task the task to remove
  106230. */
  106231. AssetsManager.prototype.removeTask = function (task) {
  106232. var index = this._tasks.indexOf(task);
  106233. if (index > -1) {
  106234. this._tasks.splice(index, 1);
  106235. }
  106236. };
  106237. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  106238. this._waitingTasksCount--;
  106239. try {
  106240. if (this.onProgress) {
  106241. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  106242. }
  106243. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  106244. }
  106245. catch (e) {
  106246. BABYLON.Tools.Error("Error running progress callbacks.");
  106247. console.log(e);
  106248. }
  106249. if (this._waitingTasksCount === 0) {
  106250. try {
  106251. if (this.onFinish) {
  106252. this.onFinish(this._tasks);
  106253. }
  106254. // Let's remove successfull tasks
  106255. var currentTasks = this._tasks.slice();
  106256. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  106257. var task = currentTasks_1[_i];
  106258. if (task.taskState === AssetTaskState.DONE) {
  106259. var index = this._tasks.indexOf(task);
  106260. if (index > -1) {
  106261. this._tasks.splice(index, 1);
  106262. }
  106263. }
  106264. }
  106265. this.onTasksDoneObservable.notifyObservers(this._tasks);
  106266. }
  106267. catch (e) {
  106268. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  106269. console.log(e);
  106270. }
  106271. this._isLoading = false;
  106272. this._scene.getEngine().hideLoadingUI();
  106273. }
  106274. };
  106275. AssetsManager.prototype._runTask = function (task) {
  106276. var _this = this;
  106277. var done = function () {
  106278. try {
  106279. if (_this.onTaskSuccess) {
  106280. _this.onTaskSuccess(task);
  106281. }
  106282. _this.onTaskSuccessObservable.notifyObservers(task);
  106283. _this._decreaseWaitingTasksCount(task);
  106284. }
  106285. catch (e) {
  106286. error("Error executing task success callbacks", e);
  106287. }
  106288. };
  106289. var error = function (message, exception) {
  106290. task._setErrorObject(message, exception);
  106291. if (_this.onTaskError) {
  106292. _this.onTaskError(task);
  106293. }
  106294. _this.onTaskErrorObservable.notifyObservers(task);
  106295. _this._decreaseWaitingTasksCount(task);
  106296. };
  106297. task.run(this._scene, done, error);
  106298. };
  106299. /**
  106300. * Reset the {BABYLON.AssetsManager} and remove all tasks
  106301. * @return the current instance of the {BABYLON.AssetsManager}
  106302. */
  106303. AssetsManager.prototype.reset = function () {
  106304. this._isLoading = false;
  106305. this._tasks = new Array();
  106306. return this;
  106307. };
  106308. /**
  106309. * Start the loading process
  106310. * @return the current instance of the {BABYLON.AssetsManager}
  106311. */
  106312. AssetsManager.prototype.load = function () {
  106313. if (this._isLoading) {
  106314. return this;
  106315. }
  106316. this._isLoading = true;
  106317. this._waitingTasksCount = this._tasks.length;
  106318. this._totalTasksCount = this._tasks.length;
  106319. if (this._waitingTasksCount === 0) {
  106320. this._isLoading = false;
  106321. if (this.onFinish) {
  106322. this.onFinish(this._tasks);
  106323. }
  106324. this.onTasksDoneObservable.notifyObservers(this._tasks);
  106325. return this;
  106326. }
  106327. if (this.useDefaultLoadingScreen) {
  106328. this._scene.getEngine().displayLoadingUI();
  106329. }
  106330. for (var index = 0; index < this._tasks.length; index++) {
  106331. var task = this._tasks[index];
  106332. if (task.taskState === AssetTaskState.INIT) {
  106333. this._runTask(task);
  106334. }
  106335. }
  106336. return this;
  106337. };
  106338. return AssetsManager;
  106339. }());
  106340. BABYLON.AssetsManager = AssetsManager;
  106341. })(BABYLON || (BABYLON = {}));
  106342. //# sourceMappingURL=babylon.assetsManager.js.map
  106343. var BABYLON;
  106344. (function (BABYLON) {
  106345. var serializedGeometries = [];
  106346. var serializeGeometry = function (geometry, serializationGeometries) {
  106347. if (serializedGeometries[geometry.id]) {
  106348. return;
  106349. }
  106350. if (geometry.doNotSerialize) {
  106351. return;
  106352. }
  106353. if (geometry instanceof BABYLON.BoxGeometry) {
  106354. serializationGeometries.boxes.push(geometry.serialize());
  106355. }
  106356. else if (geometry instanceof BABYLON.SphereGeometry) {
  106357. serializationGeometries.spheres.push(geometry.serialize());
  106358. }
  106359. else if (geometry instanceof BABYLON.CylinderGeometry) {
  106360. serializationGeometries.cylinders.push(geometry.serialize());
  106361. }
  106362. else if (geometry instanceof BABYLON.TorusGeometry) {
  106363. serializationGeometries.toruses.push(geometry.serialize());
  106364. }
  106365. else if (geometry instanceof BABYLON.GroundGeometry) {
  106366. serializationGeometries.grounds.push(geometry.serialize());
  106367. }
  106368. else if (geometry instanceof BABYLON.Plane) {
  106369. serializationGeometries.planes.push(geometry.serialize());
  106370. }
  106371. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  106372. serializationGeometries.torusKnots.push(geometry.serialize());
  106373. }
  106374. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  106375. throw new Error("Unknown primitive type");
  106376. }
  106377. else {
  106378. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  106379. }
  106380. serializedGeometries[geometry.id] = true;
  106381. };
  106382. var serializeMesh = function (mesh, serializationScene) {
  106383. var serializationObject = {};
  106384. // Geometry
  106385. var geometry = mesh._geometry;
  106386. if (geometry) {
  106387. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  106388. // 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
  106389. serializeGeometry(geometry, serializationScene.geometries);
  106390. }
  106391. }
  106392. // Custom
  106393. if (mesh.serialize) {
  106394. mesh.serialize(serializationObject);
  106395. }
  106396. return serializationObject;
  106397. };
  106398. var finalizeSingleMesh = function (mesh, serializationObject) {
  106399. //only works if the mesh is already loaded
  106400. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  106401. //serialize material
  106402. if (mesh.material) {
  106403. if (mesh.material instanceof BABYLON.MultiMaterial) {
  106404. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  106405. serializationObject.materials = serializationObject.materials || [];
  106406. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  106407. serializationObject.multiMaterials.push(mesh.material.serialize());
  106408. var _loop_1 = function (submaterial) {
  106409. if (submaterial) {
  106410. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  106411. serializationObject.materials.push(submaterial.serialize());
  106412. }
  106413. }
  106414. };
  106415. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  106416. var submaterial = _a[_i];
  106417. _loop_1(submaterial);
  106418. }
  106419. }
  106420. }
  106421. else {
  106422. serializationObject.materials = serializationObject.materials || [];
  106423. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  106424. serializationObject.materials.push(mesh.material.serialize());
  106425. }
  106426. }
  106427. }
  106428. //serialize geometry
  106429. var geometry = mesh._geometry;
  106430. if (geometry) {
  106431. if (!serializationObject.geometries) {
  106432. serializationObject.geometries = {};
  106433. serializationObject.geometries.boxes = [];
  106434. serializationObject.geometries.spheres = [];
  106435. serializationObject.geometries.cylinders = [];
  106436. serializationObject.geometries.toruses = [];
  106437. serializationObject.geometries.grounds = [];
  106438. serializationObject.geometries.planes = [];
  106439. serializationObject.geometries.torusKnots = [];
  106440. serializationObject.geometries.vertexData = [];
  106441. }
  106442. serializeGeometry(geometry, serializationObject.geometries);
  106443. }
  106444. // Skeletons
  106445. if (mesh.skeleton) {
  106446. serializationObject.skeletons = serializationObject.skeletons || [];
  106447. serializationObject.skeletons.push(mesh.skeleton.serialize());
  106448. }
  106449. //serialize the actual mesh
  106450. serializationObject.meshes = serializationObject.meshes || [];
  106451. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  106452. }
  106453. };
  106454. var SceneSerializer = /** @class */ (function () {
  106455. function SceneSerializer() {
  106456. }
  106457. SceneSerializer.ClearCache = function () {
  106458. serializedGeometries = [];
  106459. };
  106460. SceneSerializer.Serialize = function (scene) {
  106461. var serializationObject = {};
  106462. SceneSerializer.ClearCache();
  106463. // Scene
  106464. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  106465. serializationObject.autoClear = scene.autoClear;
  106466. serializationObject.clearColor = scene.clearColor.asArray();
  106467. serializationObject.ambientColor = scene.ambientColor.asArray();
  106468. serializationObject.gravity = scene.gravity.asArray();
  106469. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  106470. serializationObject.workerCollisions = scene.workerCollisions;
  106471. // Fog
  106472. if (scene.fogMode && scene.fogMode !== 0) {
  106473. serializationObject.fogMode = scene.fogMode;
  106474. serializationObject.fogColor = scene.fogColor.asArray();
  106475. serializationObject.fogStart = scene.fogStart;
  106476. serializationObject.fogEnd = scene.fogEnd;
  106477. serializationObject.fogDensity = scene.fogDensity;
  106478. }
  106479. //Physics
  106480. if (scene.isPhysicsEnabled()) {
  106481. var physicEngine = scene.getPhysicsEngine();
  106482. if (physicEngine) {
  106483. serializationObject.physicsEnabled = true;
  106484. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  106485. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  106486. }
  106487. }
  106488. // Metadata
  106489. if (scene.metadata) {
  106490. serializationObject.metadata = scene.metadata;
  106491. }
  106492. // Morph targets
  106493. serializationObject.morphTargetManagers = [];
  106494. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  106495. var abstractMesh = _a[_i];
  106496. var manager = abstractMesh.morphTargetManager;
  106497. if (manager) {
  106498. serializationObject.morphTargetManagers.push(manager.serialize());
  106499. }
  106500. }
  106501. // Lights
  106502. serializationObject.lights = [];
  106503. var index;
  106504. var light;
  106505. for (index = 0; index < scene.lights.length; index++) {
  106506. light = scene.lights[index];
  106507. if (!light.doNotSerialize) {
  106508. serializationObject.lights.push(light.serialize());
  106509. }
  106510. }
  106511. // Cameras
  106512. serializationObject.cameras = [];
  106513. for (index = 0; index < scene.cameras.length; index++) {
  106514. var camera = scene.cameras[index];
  106515. if (!camera.doNotSerialize) {
  106516. serializationObject.cameras.push(camera.serialize());
  106517. }
  106518. }
  106519. if (scene.activeCamera) {
  106520. serializationObject.activeCameraID = scene.activeCamera.id;
  106521. }
  106522. // Animations
  106523. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  106524. // Materials
  106525. serializationObject.materials = [];
  106526. serializationObject.multiMaterials = [];
  106527. var material;
  106528. for (index = 0; index < scene.materials.length; index++) {
  106529. material = scene.materials[index];
  106530. if (!material.doNotSerialize) {
  106531. serializationObject.materials.push(material.serialize());
  106532. }
  106533. }
  106534. // MultiMaterials
  106535. serializationObject.multiMaterials = [];
  106536. for (index = 0; index < scene.multiMaterials.length; index++) {
  106537. var multiMaterial = scene.multiMaterials[index];
  106538. serializationObject.multiMaterials.push(multiMaterial.serialize());
  106539. }
  106540. // Environment texture
  106541. if (scene.environmentTexture) {
  106542. serializationObject.environmentTexture = scene.environmentTexture.name;
  106543. }
  106544. // Skeletons
  106545. serializationObject.skeletons = [];
  106546. for (index = 0; index < scene.skeletons.length; index++) {
  106547. var skeleton = scene.skeletons[index];
  106548. if (!skeleton.doNotSerialize) {
  106549. serializationObject.skeletons.push(skeleton.serialize());
  106550. }
  106551. }
  106552. // Transform nodes
  106553. serializationObject.transformNodes = [];
  106554. for (index = 0; index < scene.transformNodes.length; index++) {
  106555. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  106556. }
  106557. // Geometries
  106558. serializationObject.geometries = {};
  106559. serializationObject.geometries.boxes = [];
  106560. serializationObject.geometries.spheres = [];
  106561. serializationObject.geometries.cylinders = [];
  106562. serializationObject.geometries.toruses = [];
  106563. serializationObject.geometries.grounds = [];
  106564. serializationObject.geometries.planes = [];
  106565. serializationObject.geometries.torusKnots = [];
  106566. serializationObject.geometries.vertexData = [];
  106567. serializedGeometries = [];
  106568. var geometries = scene.getGeometries();
  106569. for (index = 0; index < geometries.length; index++) {
  106570. var geometry = geometries[index];
  106571. if (geometry.isReady()) {
  106572. serializeGeometry(geometry, serializationObject.geometries);
  106573. }
  106574. }
  106575. // Meshes
  106576. serializationObject.meshes = [];
  106577. for (index = 0; index < scene.meshes.length; index++) {
  106578. var abstractMesh = scene.meshes[index];
  106579. if (abstractMesh instanceof BABYLON.Mesh) {
  106580. var mesh = abstractMesh;
  106581. if (!mesh.doNotSerialize) {
  106582. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  106583. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  106584. }
  106585. }
  106586. }
  106587. }
  106588. // Particles Systems
  106589. serializationObject.particleSystems = [];
  106590. for (index = 0; index < scene.particleSystems.length; index++) {
  106591. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  106592. }
  106593. // Action Manager
  106594. if (scene.actionManager) {
  106595. serializationObject.actions = scene.actionManager.serialize("scene");
  106596. }
  106597. // Components
  106598. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  106599. var component = _c[_b];
  106600. component.serialize(serializationObject);
  106601. }
  106602. return serializationObject;
  106603. };
  106604. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  106605. if (withParents === void 0) { withParents = false; }
  106606. if (withChildren === void 0) { withChildren = false; }
  106607. var serializationObject = {};
  106608. SceneSerializer.ClearCache();
  106609. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  106610. if (withParents || withChildren) {
  106611. //deliberate for loop! not for each, appended should be processed as well.
  106612. for (var i = 0; i < toSerialize.length; ++i) {
  106613. if (withChildren) {
  106614. toSerialize[i].getDescendants().forEach(function (node) {
  106615. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  106616. toSerialize.push(node);
  106617. }
  106618. });
  106619. }
  106620. //make sure the array doesn't contain the object already
  106621. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  106622. toSerialize.push(toSerialize[i].parent);
  106623. }
  106624. }
  106625. }
  106626. toSerialize.forEach(function (mesh) {
  106627. finalizeSingleMesh(mesh, serializationObject);
  106628. });
  106629. return serializationObject;
  106630. };
  106631. return SceneSerializer;
  106632. }());
  106633. BABYLON.SceneSerializer = SceneSerializer;
  106634. })(BABYLON || (BABYLON = {}));
  106635. //# sourceMappingURL=babylon.sceneSerializer.js.map
  106636. var BABYLON;
  106637. (function (BABYLON) {
  106638. /**
  106639. * Class used to generate realtime reflection / refraction cube textures
  106640. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  106641. */
  106642. var ReflectionProbe = /** @class */ (function () {
  106643. /**
  106644. * Creates a new reflection probe
  106645. * @param name defines the name of the probe
  106646. * @param size defines the texture resolution (for each face)
  106647. * @param scene defines the hosting scene
  106648. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  106649. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  106650. */
  106651. function ReflectionProbe(
  106652. /** defines the name of the probe */
  106653. name, size, scene, generateMipMaps, useFloat) {
  106654. if (generateMipMaps === void 0) { generateMipMaps = true; }
  106655. if (useFloat === void 0) { useFloat = false; }
  106656. var _this = this;
  106657. this.name = name;
  106658. this._viewMatrix = BABYLON.Matrix.Identity();
  106659. this._target = BABYLON.Vector3.Zero();
  106660. this._add = BABYLON.Vector3.Zero();
  106661. this._invertYAxis = false;
  106662. /** Gets or sets probe position (center of the cube map) */
  106663. this.position = BABYLON.Vector3.Zero();
  106664. this._scene = scene;
  106665. // Create the scene field if not exist.
  106666. if (!this._scene.reflectionProbes) {
  106667. this._scene.reflectionProbes = new Array();
  106668. }
  106669. this._scene.reflectionProbes.push(this);
  106670. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  106671. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  106672. switch (faceIndex) {
  106673. case 0:
  106674. _this._add.copyFromFloats(1, 0, 0);
  106675. break;
  106676. case 1:
  106677. _this._add.copyFromFloats(-1, 0, 0);
  106678. break;
  106679. case 2:
  106680. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  106681. break;
  106682. case 3:
  106683. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  106684. break;
  106685. case 4:
  106686. _this._add.copyFromFloats(0, 0, 1);
  106687. break;
  106688. case 5:
  106689. _this._add.copyFromFloats(0, 0, -1);
  106690. break;
  106691. }
  106692. if (_this._attachedMesh) {
  106693. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  106694. }
  106695. _this.position.addToRef(_this._add, _this._target);
  106696. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  106697. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  106698. scene._forcedViewPosition = _this.position;
  106699. });
  106700. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  106701. scene._forcedViewPosition = null;
  106702. scene.updateTransformMatrix(true);
  106703. });
  106704. if (scene.activeCamera) {
  106705. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  106706. }
  106707. }
  106708. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  106709. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  106710. get: function () {
  106711. return this._renderTargetTexture.samples;
  106712. },
  106713. set: function (value) {
  106714. this._renderTargetTexture.samples = value;
  106715. },
  106716. enumerable: true,
  106717. configurable: true
  106718. });
  106719. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  106720. /** Gets or sets the refresh rate to use (on every frame by default) */
  106721. get: function () {
  106722. return this._renderTargetTexture.refreshRate;
  106723. },
  106724. set: function (value) {
  106725. this._renderTargetTexture.refreshRate = value;
  106726. },
  106727. enumerable: true,
  106728. configurable: true
  106729. });
  106730. /**
  106731. * Gets the hosting scene
  106732. * @returns a Scene
  106733. */
  106734. ReflectionProbe.prototype.getScene = function () {
  106735. return this._scene;
  106736. };
  106737. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  106738. /** Gets the internal CubeTexture used to render to */
  106739. get: function () {
  106740. return this._renderTargetTexture;
  106741. },
  106742. enumerable: true,
  106743. configurable: true
  106744. });
  106745. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  106746. /** Gets the list of meshes to render */
  106747. get: function () {
  106748. return this._renderTargetTexture.renderList;
  106749. },
  106750. enumerable: true,
  106751. configurable: true
  106752. });
  106753. /**
  106754. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  106755. * @param mesh defines the mesh to attach to
  106756. */
  106757. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  106758. this._attachedMesh = mesh;
  106759. };
  106760. /**
  106761. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  106762. * @param renderingGroupId The rendering group id corresponding to its index
  106763. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  106764. */
  106765. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  106766. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  106767. };
  106768. /**
  106769. * Clean all associated resources
  106770. */
  106771. ReflectionProbe.prototype.dispose = function () {
  106772. var index = this._scene.reflectionProbes.indexOf(this);
  106773. if (index !== -1) {
  106774. // Remove from the scene if found
  106775. this._scene.reflectionProbes.splice(index, 1);
  106776. }
  106777. if (this._renderTargetTexture) {
  106778. this._renderTargetTexture.dispose();
  106779. this._renderTargetTexture = null;
  106780. }
  106781. };
  106782. return ReflectionProbe;
  106783. }());
  106784. BABYLON.ReflectionProbe = ReflectionProbe;
  106785. })(BABYLON || (BABYLON = {}));
  106786. //# sourceMappingURL=babylon.reflectionProbe.js.map
  106787. var BABYLON;
  106788. (function (BABYLON) {
  106789. /**
  106790. * Defines the layer scene component responsible to manage any layers
  106791. * in a given scene.
  106792. */
  106793. var LayerSceneComponent = /** @class */ (function () {
  106794. /**
  106795. * Creates a new instance of the component for the given scene
  106796. * @param scene Defines the scene to register the component in
  106797. */
  106798. function LayerSceneComponent(scene) {
  106799. /**
  106800. * The component name helpfull to identify the component in the list of scene components.
  106801. */
  106802. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  106803. this.scene = scene;
  106804. this._engine = scene.getEngine();
  106805. scene.layers = new Array();
  106806. }
  106807. /**
  106808. * Registers the component in a given scene
  106809. */
  106810. LayerSceneComponent.prototype.register = function () {
  106811. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  106812. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  106813. };
  106814. /**
  106815. * Rebuilds the elements related to this component in case of
  106816. * context lost for instance.
  106817. */
  106818. LayerSceneComponent.prototype.rebuild = function () {
  106819. var layers = this.scene.layers;
  106820. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  106821. var layer = layers_1[_i];
  106822. layer._rebuild();
  106823. }
  106824. };
  106825. /**
  106826. * Disposes the component and the associated ressources.
  106827. */
  106828. LayerSceneComponent.prototype.dispose = function () {
  106829. var layers = this.scene.layers;
  106830. while (layers.length) {
  106831. layers[0].dispose();
  106832. }
  106833. };
  106834. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  106835. var layers = this.scene.layers;
  106836. if (layers.length) {
  106837. this._engine.setDepthBuffer(false);
  106838. var cameraLayerMask = camera.layerMask;
  106839. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  106840. var layer = layers_2[_i];
  106841. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  106842. layer.render();
  106843. }
  106844. }
  106845. this._engine.setDepthBuffer(true);
  106846. }
  106847. };
  106848. LayerSceneComponent.prototype._drawBackground = function (camera) {
  106849. this._draw(camera, true);
  106850. };
  106851. LayerSceneComponent.prototype._drawForeground = function (camera) {
  106852. this._draw(camera, false);
  106853. };
  106854. return LayerSceneComponent;
  106855. }());
  106856. BABYLON.LayerSceneComponent = LayerSceneComponent;
  106857. })(BABYLON || (BABYLON = {}));
  106858. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  106859. var BABYLON;
  106860. (function (BABYLON) {
  106861. var Layer = /** @class */ (function () {
  106862. function Layer(name, imgUrl, scene, isBackground, color) {
  106863. this.name = name;
  106864. this.scale = new BABYLON.Vector2(1, 1);
  106865. this.offset = new BABYLON.Vector2(0, 0);
  106866. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  106867. this.layerMask = 0x0FFFFFFF;
  106868. this._vertexBuffers = {};
  106869. // Events
  106870. /**
  106871. * An event triggered when the layer is disposed.
  106872. */
  106873. this.onDisposeObservable = new BABYLON.Observable();
  106874. /**
  106875. * An event triggered before rendering the scene
  106876. */
  106877. this.onBeforeRenderObservable = new BABYLON.Observable();
  106878. /**
  106879. * An event triggered after rendering the scene
  106880. */
  106881. this.onAfterRenderObservable = new BABYLON.Observable();
  106882. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  106883. this.isBackground = isBackground === undefined ? true : isBackground;
  106884. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  106885. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  106886. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  106887. if (!layerComponent) {
  106888. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  106889. this._scene._addComponent(layerComponent);
  106890. }
  106891. this._scene.layers.push(this);
  106892. var engine = this._scene.getEngine();
  106893. // VBO
  106894. var vertices = [];
  106895. vertices.push(1, 1);
  106896. vertices.push(-1, 1);
  106897. vertices.push(-1, -1);
  106898. vertices.push(1, -1);
  106899. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  106900. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  106901. this._createIndexBuffer();
  106902. // Effects
  106903. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  106904. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  106905. }
  106906. Object.defineProperty(Layer.prototype, "onDispose", {
  106907. set: function (callback) {
  106908. if (this._onDisposeObserver) {
  106909. this.onDisposeObservable.remove(this._onDisposeObserver);
  106910. }
  106911. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  106912. },
  106913. enumerable: true,
  106914. configurable: true
  106915. });
  106916. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  106917. set: function (callback) {
  106918. if (this._onBeforeRenderObserver) {
  106919. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  106920. }
  106921. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  106922. },
  106923. enumerable: true,
  106924. configurable: true
  106925. });
  106926. Object.defineProperty(Layer.prototype, "onAfterRender", {
  106927. set: function (callback) {
  106928. if (this._onAfterRenderObserver) {
  106929. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  106930. }
  106931. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  106932. },
  106933. enumerable: true,
  106934. configurable: true
  106935. });
  106936. Layer.prototype._createIndexBuffer = function () {
  106937. var engine = this._scene.getEngine();
  106938. // Indices
  106939. var indices = [];
  106940. indices.push(0);
  106941. indices.push(1);
  106942. indices.push(2);
  106943. indices.push(0);
  106944. indices.push(2);
  106945. indices.push(3);
  106946. this._indexBuffer = engine.createIndexBuffer(indices);
  106947. };
  106948. /** @hidden */
  106949. Layer.prototype._rebuild = function () {
  106950. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106951. if (vb) {
  106952. vb._rebuild();
  106953. }
  106954. this._createIndexBuffer();
  106955. };
  106956. Layer.prototype.render = function () {
  106957. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  106958. // Check
  106959. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  106960. return;
  106961. var engine = this._scene.getEngine();
  106962. this.onBeforeRenderObservable.notifyObservers(this);
  106963. // Render
  106964. engine.enableEffect(currentEffect);
  106965. engine.setState(false);
  106966. // Texture
  106967. currentEffect.setTexture("textureSampler", this.texture);
  106968. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  106969. // Color
  106970. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  106971. // Scale / offset
  106972. currentEffect.setVector2("offset", this.offset);
  106973. currentEffect.setVector2("scale", this.scale);
  106974. // VBOs
  106975. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  106976. // Draw order
  106977. if (!this.alphaTest) {
  106978. engine.setAlphaMode(this.alphaBlendingMode);
  106979. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106980. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  106981. }
  106982. else {
  106983. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106984. }
  106985. this.onAfterRenderObservable.notifyObservers(this);
  106986. };
  106987. Layer.prototype.dispose = function () {
  106988. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106989. if (vertexBuffer) {
  106990. vertexBuffer.dispose();
  106991. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  106992. }
  106993. if (this._indexBuffer) {
  106994. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  106995. this._indexBuffer = null;
  106996. }
  106997. if (this.texture) {
  106998. this.texture.dispose();
  106999. this.texture = null;
  107000. }
  107001. // Remove from scene
  107002. var index = this._scene.layers.indexOf(this);
  107003. this._scene.layers.splice(index, 1);
  107004. // Callback
  107005. this.onDisposeObservable.notifyObservers(this);
  107006. this.onDisposeObservable.clear();
  107007. this.onAfterRenderObservable.clear();
  107008. this.onBeforeRenderObservable.clear();
  107009. };
  107010. return Layer;
  107011. }());
  107012. BABYLON.Layer = Layer;
  107013. })(BABYLON || (BABYLON = {}));
  107014. //# sourceMappingURL=babylon.layer.js.map
  107015. var BABYLON;
  107016. (function (BABYLON) {
  107017. var TextureTools = /** @class */ (function () {
  107018. function TextureTools() {
  107019. }
  107020. /**
  107021. * Uses the GPU to create a copy texture rescaled at a given size
  107022. * @param texture Texture to copy from
  107023. * @param width Desired width
  107024. * @param height Desired height
  107025. * @return Generated texture
  107026. */
  107027. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  107028. if (useBilinearMode === void 0) { useBilinearMode = true; }
  107029. var scene = texture.getScene();
  107030. var engine = scene.getEngine();
  107031. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  107032. rtt.wrapU = texture.wrapU;
  107033. rtt.wrapV = texture.wrapV;
  107034. rtt.uOffset = texture.uOffset;
  107035. rtt.vOffset = texture.vOffset;
  107036. rtt.uScale = texture.uScale;
  107037. rtt.vScale = texture.vScale;
  107038. rtt.uAng = texture.uAng;
  107039. rtt.vAng = texture.vAng;
  107040. rtt.wAng = texture.wAng;
  107041. rtt.coordinatesIndex = texture.coordinatesIndex;
  107042. rtt.level = texture.level;
  107043. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  107044. rtt._texture.isReady = false;
  107045. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107046. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107047. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  107048. passPostProcess.getEffect().executeWhenCompiled(function () {
  107049. passPostProcess.onApply = function (effect) {
  107050. effect.setTexture("textureSampler", texture);
  107051. };
  107052. var internalTexture = rtt.getInternalTexture();
  107053. if (internalTexture) {
  107054. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  107055. engine.unBindFramebuffer(internalTexture);
  107056. rtt.disposeFramebufferObjects();
  107057. passPostProcess.dispose();
  107058. internalTexture.isReady = true;
  107059. }
  107060. });
  107061. return rtt;
  107062. };
  107063. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  107064. if (!scene._environmentBRDFTexture) {
  107065. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107066. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107067. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107068. scene._environmentBRDFTexture = texture;
  107069. }
  107070. return scene._environmentBRDFTexture;
  107071. };
  107072. 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=";
  107073. return TextureTools;
  107074. }());
  107075. BABYLON.TextureTools = TextureTools;
  107076. })(BABYLON || (BABYLON = {}));
  107077. //# sourceMappingURL=babylon.textureTools.js.map
  107078. var BABYLON;
  107079. (function (BABYLON) {
  107080. /**
  107081. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  107082. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  107083. */
  107084. var FramingBehavior = /** @class */ (function () {
  107085. function FramingBehavior() {
  107086. this._mode = FramingBehavior.FitFrustumSidesMode;
  107087. this._radiusScale = 1.0;
  107088. this._positionScale = 0.5;
  107089. this._defaultElevation = 0.3;
  107090. this._elevationReturnTime = 1500;
  107091. this._elevationReturnWaitTime = 1000;
  107092. this._zoomStopsAnimation = false;
  107093. this._framingTime = 1500;
  107094. this._isPointerDown = false;
  107095. this._lastInteractionTime = -Infinity;
  107096. // Framing control
  107097. this._animatables = new Array();
  107098. this._betaIsAnimating = false;
  107099. }
  107100. Object.defineProperty(FramingBehavior.prototype, "name", {
  107101. /**
  107102. * Gets the name of the behavior.
  107103. */
  107104. get: function () {
  107105. return "Framing";
  107106. },
  107107. enumerable: true,
  107108. configurable: true
  107109. });
  107110. Object.defineProperty(FramingBehavior.prototype, "mode", {
  107111. /**
  107112. * Gets current mode used by the behavior.
  107113. */
  107114. get: function () {
  107115. return this._mode;
  107116. },
  107117. /**
  107118. * Sets the current mode used by the behavior
  107119. */
  107120. set: function (mode) {
  107121. this._mode = mode;
  107122. },
  107123. enumerable: true,
  107124. configurable: true
  107125. });
  107126. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  107127. /**
  107128. * Gets the scale applied to the radius
  107129. */
  107130. get: function () {
  107131. return this._radiusScale;
  107132. },
  107133. /**
  107134. * Sets the scale applied to the radius (1 by default)
  107135. */
  107136. set: function (radius) {
  107137. this._radiusScale = radius;
  107138. },
  107139. enumerable: true,
  107140. configurable: true
  107141. });
  107142. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  107143. /**
  107144. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  107145. */
  107146. get: function () {
  107147. return this._positionScale;
  107148. },
  107149. /**
  107150. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  107151. */
  107152. set: function (scale) {
  107153. this._positionScale = scale;
  107154. },
  107155. enumerable: true,
  107156. configurable: true
  107157. });
  107158. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  107159. /**
  107160. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  107161. * behaviour is triggered, in radians.
  107162. */
  107163. get: function () {
  107164. return this._defaultElevation;
  107165. },
  107166. /**
  107167. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  107168. * behaviour is triggered, in radians.
  107169. */
  107170. set: function (elevation) {
  107171. this._defaultElevation = elevation;
  107172. },
  107173. enumerable: true,
  107174. configurable: true
  107175. });
  107176. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  107177. /**
  107178. * Gets the time (in milliseconds) taken to return to the default beta position.
  107179. * Negative value indicates camera should not return to default.
  107180. */
  107181. get: function () {
  107182. return this._elevationReturnTime;
  107183. },
  107184. /**
  107185. * Sets the time (in milliseconds) taken to return to the default beta position.
  107186. * Negative value indicates camera should not return to default.
  107187. */
  107188. set: function (speed) {
  107189. this._elevationReturnTime = speed;
  107190. },
  107191. enumerable: true,
  107192. configurable: true
  107193. });
  107194. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  107195. /**
  107196. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  107197. */
  107198. get: function () {
  107199. return this._elevationReturnWaitTime;
  107200. },
  107201. /**
  107202. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  107203. */
  107204. set: function (time) {
  107205. this._elevationReturnWaitTime = time;
  107206. },
  107207. enumerable: true,
  107208. configurable: true
  107209. });
  107210. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  107211. /**
  107212. * Gets the flag that indicates if user zooming should stop animation.
  107213. */
  107214. get: function () {
  107215. return this._zoomStopsAnimation;
  107216. },
  107217. /**
  107218. * Sets the flag that indicates if user zooming should stop animation.
  107219. */
  107220. set: function (flag) {
  107221. this._zoomStopsAnimation = flag;
  107222. },
  107223. enumerable: true,
  107224. configurable: true
  107225. });
  107226. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  107227. /**
  107228. * Gets the transition time when framing the mesh, in milliseconds
  107229. */
  107230. get: function () {
  107231. return this._framingTime;
  107232. },
  107233. /**
  107234. * Sets the transition time when framing the mesh, in milliseconds
  107235. */
  107236. set: function (time) {
  107237. this._framingTime = time;
  107238. },
  107239. enumerable: true,
  107240. configurable: true
  107241. });
  107242. /**
  107243. * Initializes the behavior.
  107244. */
  107245. FramingBehavior.prototype.init = function () {
  107246. // Do notihng
  107247. };
  107248. /**
  107249. * Attaches the behavior to its arc rotate camera.
  107250. * @param camera Defines the camera to attach the behavior to
  107251. */
  107252. FramingBehavior.prototype.attach = function (camera) {
  107253. var _this = this;
  107254. this._attachedCamera = camera;
  107255. var scene = this._attachedCamera.getScene();
  107256. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  107257. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  107258. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  107259. _this._isPointerDown = true;
  107260. return;
  107261. }
  107262. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  107263. _this._isPointerDown = false;
  107264. }
  107265. });
  107266. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  107267. if (mesh) {
  107268. _this.zoomOnMesh(mesh);
  107269. }
  107270. });
  107271. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107272. // Stop the animation if there is user interaction and the animation should stop for this interaction
  107273. _this._applyUserInteraction();
  107274. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  107275. // back to the default position after a given timeout
  107276. _this._maintainCameraAboveGround();
  107277. });
  107278. };
  107279. /**
  107280. * Detaches the behavior from its current arc rotate camera.
  107281. */
  107282. FramingBehavior.prototype.detach = function () {
  107283. if (!this._attachedCamera) {
  107284. return;
  107285. }
  107286. var scene = this._attachedCamera.getScene();
  107287. if (this._onPrePointerObservableObserver) {
  107288. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  107289. }
  107290. if (this._onAfterCheckInputsObserver) {
  107291. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107292. }
  107293. if (this._onMeshTargetChangedObserver) {
  107294. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107295. }
  107296. this._attachedCamera = null;
  107297. };
  107298. /**
  107299. * Targets the given mesh and updates zoom level accordingly.
  107300. * @param mesh The mesh to target.
  107301. * @param radius Optional. If a cached radius position already exists, overrides default.
  107302. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107303. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107304. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107305. */
  107306. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  107307. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107308. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107309. mesh.computeWorldMatrix(true);
  107310. var boundingBox = mesh.getBoundingInfo().boundingBox;
  107311. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  107312. };
  107313. /**
  107314. * Targets the given mesh with its children and updates zoom level accordingly.
  107315. * @param mesh The mesh to target.
  107316. * @param radius Optional. If a cached radius position already exists, overrides default.
  107317. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107318. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107319. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107320. */
  107321. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  107322. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107323. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107324. mesh.computeWorldMatrix(true);
  107325. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  107326. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  107327. };
  107328. /**
  107329. * Targets the given meshes with their children and updates zoom level accordingly.
  107330. * @param meshes The mesh to target.
  107331. * @param radius Optional. If a cached radius position already exists, overrides default.
  107332. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107333. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107334. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107335. */
  107336. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  107337. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107338. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107339. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  107340. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  107341. for (var i = 0; i < meshes.length; i++) {
  107342. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  107343. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  107344. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  107345. }
  107346. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  107347. };
  107348. /**
  107349. * Targets the given mesh and updates zoom level accordingly.
  107350. * @param mesh The mesh to target.
  107351. * @param radius Optional. If a cached radius position already exists, overrides default.
  107352. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107353. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107354. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107355. */
  107356. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  107357. var _this = this;
  107358. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107359. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107360. var zoomTarget;
  107361. if (!this._attachedCamera) {
  107362. return;
  107363. }
  107364. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  107365. var bottom = minimumWorld.y;
  107366. var top = maximumWorld.y;
  107367. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  107368. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  107369. if (focusOnOriginXZ) {
  107370. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  107371. }
  107372. else {
  107373. var centerWorld = minimumWorld.add(radiusWorld);
  107374. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  107375. }
  107376. if (!this._vectorTransition) {
  107377. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  107378. }
  107379. this._betaIsAnimating = true;
  107380. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  107381. if (animatable) {
  107382. this._animatables.push(animatable);
  107383. }
  107384. // sets the radius and lower radius bounds
  107385. // Small delta ensures camera is not always at lower zoom limit.
  107386. var radius = 0;
  107387. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  107388. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  107389. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  107390. radius = position;
  107391. }
  107392. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  107393. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  107394. if (this._attachedCamera.lowerRadiusLimit === null) {
  107395. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  107396. }
  107397. }
  107398. // Set sensibilities
  107399. var extend = maximumWorld.subtract(minimumWorld).length();
  107400. this._attachedCamera.panningSensibility = 5000 / extend;
  107401. this._attachedCamera.wheelPrecision = 100 / radius;
  107402. // transition to new radius
  107403. if (!this._radiusTransition) {
  107404. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  107405. }
  107406. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  107407. _this.stopAllAnimations();
  107408. if (onAnimationEnd) {
  107409. onAnimationEnd();
  107410. }
  107411. if (_this._attachedCamera) {
  107412. _this._attachedCamera.storeState();
  107413. }
  107414. });
  107415. if (animatable) {
  107416. this._animatables.push(animatable);
  107417. }
  107418. };
  107419. /**
  107420. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  107421. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  107422. * frustum width.
  107423. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  107424. * to fully enclose the mesh in the viewing frustum.
  107425. */
  107426. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  107427. var size = maximumWorld.subtract(minimumWorld);
  107428. var boxVectorGlobalDiagonal = size.length();
  107429. var frustumSlope = this._getFrustumSlope();
  107430. // Formula for setting distance
  107431. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  107432. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  107433. // Horizon distance
  107434. var radius = radiusWithoutFraming * this._radiusScale;
  107435. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  107436. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  107437. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  107438. var camera = this._attachedCamera;
  107439. if (!camera) {
  107440. return 0;
  107441. }
  107442. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  107443. // Don't exceed the requested limit
  107444. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  107445. }
  107446. // Don't exceed the upper radius limit
  107447. if (camera.upperRadiusLimit) {
  107448. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  107449. }
  107450. return distance;
  107451. };
  107452. /**
  107453. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  107454. * is automatically returned to its default position (expected to be above ground plane).
  107455. */
  107456. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  107457. var _this = this;
  107458. if (this._elevationReturnTime < 0) {
  107459. return;
  107460. }
  107461. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  107462. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  107463. var limitBeta = Math.PI * 0.5;
  107464. // Bring the camera back up if below the ground plane
  107465. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  107466. this._betaIsAnimating = true;
  107467. //Transition to new position
  107468. this.stopAllAnimations();
  107469. if (!this._betaTransition) {
  107470. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  107471. }
  107472. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  107473. _this._clearAnimationLocks();
  107474. _this.stopAllAnimations();
  107475. });
  107476. if (animatabe) {
  107477. this._animatables.push(animatabe);
  107478. }
  107479. }
  107480. };
  107481. /**
  107482. * Returns the frustum slope based on the canvas ratio and camera FOV
  107483. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  107484. */
  107485. FramingBehavior.prototype._getFrustumSlope = function () {
  107486. // Calculate the viewport ratio
  107487. // Aspect Ratio is Height/Width.
  107488. var camera = this._attachedCamera;
  107489. if (!camera) {
  107490. return BABYLON.Vector2.Zero();
  107491. }
  107492. var engine = camera.getScene().getEngine();
  107493. var aspectRatio = engine.getAspectRatio(camera);
  107494. // Camera FOV is the vertical field of view (top-bottom) in radians.
  107495. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  107496. var frustumSlopeY = Math.tan(camera.fov / 2);
  107497. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  107498. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  107499. // along the forward vector.
  107500. var frustumSlopeX = frustumSlopeY * aspectRatio;
  107501. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  107502. };
  107503. /**
  107504. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  107505. */
  107506. FramingBehavior.prototype._clearAnimationLocks = function () {
  107507. this._betaIsAnimating = false;
  107508. };
  107509. /**
  107510. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  107511. */
  107512. FramingBehavior.prototype._applyUserInteraction = function () {
  107513. if (this.isUserIsMoving) {
  107514. this._lastInteractionTime = BABYLON.Tools.Now;
  107515. this.stopAllAnimations();
  107516. this._clearAnimationLocks();
  107517. }
  107518. };
  107519. /**
  107520. * Stops and removes all animations that have been applied to the camera
  107521. */
  107522. FramingBehavior.prototype.stopAllAnimations = function () {
  107523. if (this._attachedCamera) {
  107524. this._attachedCamera.animations = [];
  107525. }
  107526. while (this._animatables.length) {
  107527. if (this._animatables[0]) {
  107528. this._animatables[0].onAnimationEnd = null;
  107529. this._animatables[0].stop();
  107530. }
  107531. this._animatables.shift();
  107532. }
  107533. };
  107534. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  107535. /**
  107536. * Gets a value indicating if the user is moving the camera
  107537. */
  107538. get: function () {
  107539. if (!this._attachedCamera) {
  107540. return false;
  107541. }
  107542. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  107543. this._attachedCamera.inertialBetaOffset !== 0 ||
  107544. this._attachedCamera.inertialRadiusOffset !== 0 ||
  107545. this._attachedCamera.inertialPanningX !== 0 ||
  107546. this._attachedCamera.inertialPanningY !== 0 ||
  107547. this._isPointerDown;
  107548. },
  107549. enumerable: true,
  107550. configurable: true
  107551. });
  107552. /**
  107553. * The easing function used by animations
  107554. */
  107555. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  107556. /**
  107557. * The easing mode used by animations
  107558. */
  107559. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  107560. // Statics
  107561. /**
  107562. * The camera can move all the way towards the mesh.
  107563. */
  107564. FramingBehavior.IgnoreBoundsSizeMode = 0;
  107565. /**
  107566. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  107567. */
  107568. FramingBehavior.FitFrustumSidesMode = 1;
  107569. return FramingBehavior;
  107570. }());
  107571. BABYLON.FramingBehavior = FramingBehavior;
  107572. })(BABYLON || (BABYLON = {}));
  107573. //# sourceMappingURL=babylon.framingBehavior.js.map
  107574. var BABYLON;
  107575. (function (BABYLON) {
  107576. /**
  107577. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  107578. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  107579. */
  107580. var BouncingBehavior = /** @class */ (function () {
  107581. function BouncingBehavior() {
  107582. /**
  107583. * The duration of the animation, in milliseconds
  107584. */
  107585. this.transitionDuration = 450;
  107586. /**
  107587. * Length of the distance animated by the transition when lower radius is reached
  107588. */
  107589. this.lowerRadiusTransitionRange = 2;
  107590. /**
  107591. * Length of the distance animated by the transition when upper radius is reached
  107592. */
  107593. this.upperRadiusTransitionRange = -2;
  107594. this._autoTransitionRange = false;
  107595. // Animations
  107596. this._radiusIsAnimating = false;
  107597. this._radiusBounceTransition = null;
  107598. this._animatables = new Array();
  107599. }
  107600. Object.defineProperty(BouncingBehavior.prototype, "name", {
  107601. /**
  107602. * Gets the name of the behavior.
  107603. */
  107604. get: function () {
  107605. return "Bouncing";
  107606. },
  107607. enumerable: true,
  107608. configurable: true
  107609. });
  107610. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  107611. /**
  107612. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  107613. */
  107614. get: function () {
  107615. return this._autoTransitionRange;
  107616. },
  107617. /**
  107618. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  107619. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  107620. */
  107621. set: function (value) {
  107622. var _this = this;
  107623. if (this._autoTransitionRange === value) {
  107624. return;
  107625. }
  107626. this._autoTransitionRange = value;
  107627. var camera = this._attachedCamera;
  107628. if (!camera) {
  107629. return;
  107630. }
  107631. if (value) {
  107632. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  107633. if (!mesh) {
  107634. return;
  107635. }
  107636. mesh.computeWorldMatrix(true);
  107637. var diagonal = mesh.getBoundingInfo().diagonalLength;
  107638. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  107639. _this.upperRadiusTransitionRange = diagonal * 0.05;
  107640. });
  107641. }
  107642. else if (this._onMeshTargetChangedObserver) {
  107643. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107644. }
  107645. },
  107646. enumerable: true,
  107647. configurable: true
  107648. });
  107649. /**
  107650. * Initializes the behavior.
  107651. */
  107652. BouncingBehavior.prototype.init = function () {
  107653. // Do notihng
  107654. };
  107655. /**
  107656. * Attaches the behavior to its arc rotate camera.
  107657. * @param camera Defines the camera to attach the behavior to
  107658. */
  107659. BouncingBehavior.prototype.attach = function (camera) {
  107660. var _this = this;
  107661. this._attachedCamera = camera;
  107662. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107663. if (!_this._attachedCamera) {
  107664. return;
  107665. }
  107666. // Add the bounce animation to the lower radius limit
  107667. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  107668. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  107669. }
  107670. // Add the bounce animation to the upper radius limit
  107671. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  107672. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  107673. }
  107674. });
  107675. };
  107676. /**
  107677. * Detaches the behavior from its current arc rotate camera.
  107678. */
  107679. BouncingBehavior.prototype.detach = function () {
  107680. if (!this._attachedCamera) {
  107681. return;
  107682. }
  107683. if (this._onAfterCheckInputsObserver) {
  107684. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107685. }
  107686. if (this._onMeshTargetChangedObserver) {
  107687. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107688. }
  107689. this._attachedCamera = null;
  107690. };
  107691. /**
  107692. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  107693. * @param radiusLimit The limit to check against.
  107694. * @return Bool to indicate if at limit.
  107695. */
  107696. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  107697. if (!this._attachedCamera) {
  107698. return false;
  107699. }
  107700. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  107701. return true;
  107702. }
  107703. return false;
  107704. };
  107705. /**
  107706. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  107707. * @param radiusDelta The delta by which to animate to. Can be negative.
  107708. */
  107709. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  107710. var _this = this;
  107711. if (!this._attachedCamera) {
  107712. return;
  107713. }
  107714. if (!this._radiusBounceTransition) {
  107715. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  107716. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  107717. }
  107718. // Prevent zoom until bounce has completed
  107719. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  107720. this._attachedCamera.wheelPrecision = Infinity;
  107721. this._attachedCamera.inertialRadiusOffset = 0;
  107722. // Animate to the radius limit
  107723. this.stopAllAnimations();
  107724. this._radiusIsAnimating = true;
  107725. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  107726. if (animatable) {
  107727. this._animatables.push(animatable);
  107728. }
  107729. };
  107730. /**
  107731. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  107732. */
  107733. BouncingBehavior.prototype._clearAnimationLocks = function () {
  107734. this._radiusIsAnimating = false;
  107735. if (this._attachedCamera) {
  107736. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  107737. }
  107738. };
  107739. /**
  107740. * Stops and removes all animations that have been applied to the camera
  107741. */
  107742. BouncingBehavior.prototype.stopAllAnimations = function () {
  107743. if (this._attachedCamera) {
  107744. this._attachedCamera.animations = [];
  107745. }
  107746. while (this._animatables.length) {
  107747. this._animatables[0].onAnimationEnd = null;
  107748. this._animatables[0].stop();
  107749. this._animatables.shift();
  107750. }
  107751. };
  107752. /**
  107753. * The easing function used by animations
  107754. */
  107755. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  107756. /**
  107757. * The easing mode used by animations
  107758. */
  107759. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  107760. return BouncingBehavior;
  107761. }());
  107762. BABYLON.BouncingBehavior = BouncingBehavior;
  107763. })(BABYLON || (BABYLON = {}));
  107764. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  107765. var BABYLON;
  107766. (function (BABYLON) {
  107767. /**
  107768. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  107769. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  107770. */
  107771. var AutoRotationBehavior = /** @class */ (function () {
  107772. function AutoRotationBehavior() {
  107773. this._zoomStopsAnimation = false;
  107774. this._idleRotationSpeed = 0.05;
  107775. this._idleRotationWaitTime = 2000;
  107776. this._idleRotationSpinupTime = 2000;
  107777. this._isPointerDown = false;
  107778. this._lastFrameTime = null;
  107779. this._lastInteractionTime = -Infinity;
  107780. this._cameraRotationSpeed = 0;
  107781. this._lastFrameRadius = 0;
  107782. }
  107783. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  107784. /**
  107785. * Gets the name of the behavior.
  107786. */
  107787. get: function () {
  107788. return "AutoRotation";
  107789. },
  107790. enumerable: true,
  107791. configurable: true
  107792. });
  107793. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  107794. /**
  107795. * Gets the flag that indicates if user zooming should stop animation.
  107796. */
  107797. get: function () {
  107798. return this._zoomStopsAnimation;
  107799. },
  107800. /**
  107801. * Sets the flag that indicates if user zooming should stop animation.
  107802. */
  107803. set: function (flag) {
  107804. this._zoomStopsAnimation = flag;
  107805. },
  107806. enumerable: true,
  107807. configurable: true
  107808. });
  107809. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  107810. /**
  107811. * Gets the default speed at which the camera rotates around the model.
  107812. */
  107813. get: function () {
  107814. return this._idleRotationSpeed;
  107815. },
  107816. /**
  107817. * Sets the default speed at which the camera rotates around the model.
  107818. */
  107819. set: function (speed) {
  107820. this._idleRotationSpeed = speed;
  107821. },
  107822. enumerable: true,
  107823. configurable: true
  107824. });
  107825. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  107826. /**
  107827. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  107828. */
  107829. get: function () {
  107830. return this._idleRotationWaitTime;
  107831. },
  107832. /**
  107833. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  107834. */
  107835. set: function (time) {
  107836. this._idleRotationWaitTime = time;
  107837. },
  107838. enumerable: true,
  107839. configurable: true
  107840. });
  107841. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  107842. /**
  107843. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  107844. */
  107845. get: function () {
  107846. return this._idleRotationSpinupTime;
  107847. },
  107848. /**
  107849. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  107850. */
  107851. set: function (time) {
  107852. this._idleRotationSpinupTime = time;
  107853. },
  107854. enumerable: true,
  107855. configurable: true
  107856. });
  107857. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  107858. /**
  107859. * Gets a value indicating if the camera is currently rotating because of this behavior
  107860. */
  107861. get: function () {
  107862. return Math.abs(this._cameraRotationSpeed) > 0;
  107863. },
  107864. enumerable: true,
  107865. configurable: true
  107866. });
  107867. /**
  107868. * Initializes the behavior.
  107869. */
  107870. AutoRotationBehavior.prototype.init = function () {
  107871. // Do notihng
  107872. };
  107873. /**
  107874. * Attaches the behavior to its arc rotate camera.
  107875. * @param camera Defines the camera to attach the behavior to
  107876. */
  107877. AutoRotationBehavior.prototype.attach = function (camera) {
  107878. var _this = this;
  107879. this._attachedCamera = camera;
  107880. var scene = this._attachedCamera.getScene();
  107881. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  107882. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  107883. _this._isPointerDown = true;
  107884. return;
  107885. }
  107886. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  107887. _this._isPointerDown = false;
  107888. }
  107889. });
  107890. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107891. var now = BABYLON.Tools.Now;
  107892. var dt = 0;
  107893. if (_this._lastFrameTime != null) {
  107894. dt = now - _this._lastFrameTime;
  107895. }
  107896. _this._lastFrameTime = now;
  107897. // Stop the animation if there is user interaction and the animation should stop for this interaction
  107898. _this._applyUserInteraction();
  107899. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  107900. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  107901. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  107902. // Step camera rotation by rotation speed
  107903. if (_this._attachedCamera) {
  107904. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  107905. }
  107906. });
  107907. };
  107908. /**
  107909. * Detaches the behavior from its current arc rotate camera.
  107910. */
  107911. AutoRotationBehavior.prototype.detach = function () {
  107912. if (!this._attachedCamera) {
  107913. return;
  107914. }
  107915. var scene = this._attachedCamera.getScene();
  107916. if (this._onPrePointerObservableObserver) {
  107917. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  107918. }
  107919. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107920. this._attachedCamera = null;
  107921. };
  107922. /**
  107923. * Returns true if user is scrolling.
  107924. * @return true if user is scrolling.
  107925. */
  107926. AutoRotationBehavior.prototype._userIsZooming = function () {
  107927. if (!this._attachedCamera) {
  107928. return false;
  107929. }
  107930. return this._attachedCamera.inertialRadiusOffset !== 0;
  107931. };
  107932. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  107933. if (!this._attachedCamera) {
  107934. return false;
  107935. }
  107936. var zoomHasHitLimit = false;
  107937. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  107938. zoomHasHitLimit = true;
  107939. }
  107940. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  107941. this._lastFrameRadius = this._attachedCamera.radius;
  107942. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  107943. };
  107944. /**
  107945. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  107946. */
  107947. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  107948. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  107949. this._lastInteractionTime = BABYLON.Tools.Now;
  107950. }
  107951. };
  107952. // Tools
  107953. AutoRotationBehavior.prototype._userIsMoving = function () {
  107954. if (!this._attachedCamera) {
  107955. return false;
  107956. }
  107957. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  107958. this._attachedCamera.inertialBetaOffset !== 0 ||
  107959. this._attachedCamera.inertialRadiusOffset !== 0 ||
  107960. this._attachedCamera.inertialPanningX !== 0 ||
  107961. this._attachedCamera.inertialPanningY !== 0 ||
  107962. this._isPointerDown;
  107963. };
  107964. return AutoRotationBehavior;
  107965. }());
  107966. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  107967. })(BABYLON || (BABYLON = {}));
  107968. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  107969. var BABYLON;
  107970. (function (BABYLON) {
  107971. var NullEngineOptions = /** @class */ (function () {
  107972. function NullEngineOptions() {
  107973. this.renderWidth = 512;
  107974. this.renderHeight = 256;
  107975. this.textureSize = 512;
  107976. this.deterministicLockstep = false;
  107977. this.lockstepMaxSteps = 4;
  107978. }
  107979. return NullEngineOptions;
  107980. }());
  107981. BABYLON.NullEngineOptions = NullEngineOptions;
  107982. /**
  107983. * The null engine class provides support for headless version of babylon.js.
  107984. * This can be used in server side scenario or for testing purposes
  107985. */
  107986. var NullEngine = /** @class */ (function (_super) {
  107987. __extends(NullEngine, _super);
  107988. function NullEngine(options) {
  107989. if (options === void 0) { options = new NullEngineOptions(); }
  107990. var _this = _super.call(this, null) || this;
  107991. if (options.deterministicLockstep === undefined) {
  107992. options.deterministicLockstep = false;
  107993. }
  107994. if (options.lockstepMaxSteps === undefined) {
  107995. options.lockstepMaxSteps = 4;
  107996. }
  107997. _this._options = options;
  107998. // Init caps
  107999. // We consider we are on a webgl1 capable device
  108000. _this._caps = new BABYLON.EngineCapabilities();
  108001. _this._caps.maxTexturesImageUnits = 16;
  108002. _this._caps.maxVertexTextureImageUnits = 16;
  108003. _this._caps.maxTextureSize = 512;
  108004. _this._caps.maxCubemapTextureSize = 512;
  108005. _this._caps.maxRenderTextureSize = 512;
  108006. _this._caps.maxVertexAttribs = 16;
  108007. _this._caps.maxVaryingVectors = 16;
  108008. _this._caps.maxFragmentUniformVectors = 16;
  108009. _this._caps.maxVertexUniformVectors = 16;
  108010. // Extensions
  108011. _this._caps.standardDerivatives = false;
  108012. _this._caps.astc = null;
  108013. _this._caps.s3tc = null;
  108014. _this._caps.pvrtc = null;
  108015. _this._caps.etc1 = null;
  108016. _this._caps.etc2 = null;
  108017. _this._caps.textureAnisotropicFilterExtension = null;
  108018. _this._caps.maxAnisotropy = 0;
  108019. _this._caps.uintIndices = false;
  108020. _this._caps.fragmentDepthSupported = false;
  108021. _this._caps.highPrecisionShaderSupported = true;
  108022. _this._caps.colorBufferFloat = false;
  108023. _this._caps.textureFloat = false;
  108024. _this._caps.textureFloatLinearFiltering = false;
  108025. _this._caps.textureFloatRender = false;
  108026. _this._caps.textureHalfFloat = false;
  108027. _this._caps.textureHalfFloatLinearFiltering = false;
  108028. _this._caps.textureHalfFloatRender = false;
  108029. _this._caps.textureLOD = false;
  108030. _this._caps.drawBuffersExtension = false;
  108031. _this._caps.depthTextureExtension = false;
  108032. _this._caps.vertexArrayObject = false;
  108033. _this._caps.instancedArrays = false;
  108034. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  108035. // Wrappers
  108036. if (typeof URL === "undefined") {
  108037. URL = {
  108038. createObjectURL: function () { },
  108039. revokeObjectURL: function () { }
  108040. };
  108041. }
  108042. if (typeof Blob === "undefined") {
  108043. Blob = function () { };
  108044. }
  108045. return _this;
  108046. }
  108047. NullEngine.prototype.isDeterministicLockStep = function () {
  108048. return this._options.deterministicLockstep;
  108049. };
  108050. NullEngine.prototype.getLockstepMaxSteps = function () {
  108051. return this._options.lockstepMaxSteps;
  108052. };
  108053. NullEngine.prototype.getHardwareScalingLevel = function () {
  108054. return 1.0;
  108055. };
  108056. NullEngine.prototype.createVertexBuffer = function (vertices) {
  108057. return {
  108058. capacity: 0,
  108059. references: 1,
  108060. is32Bits: false
  108061. };
  108062. };
  108063. NullEngine.prototype.createIndexBuffer = function (indices) {
  108064. return {
  108065. capacity: 0,
  108066. references: 1,
  108067. is32Bits: false
  108068. };
  108069. };
  108070. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  108071. if (stencil === void 0) { stencil = false; }
  108072. };
  108073. NullEngine.prototype.getRenderWidth = function (useScreen) {
  108074. if (useScreen === void 0) { useScreen = false; }
  108075. if (!useScreen && this._currentRenderTarget) {
  108076. return this._currentRenderTarget.width;
  108077. }
  108078. return this._options.renderWidth;
  108079. };
  108080. NullEngine.prototype.getRenderHeight = function (useScreen) {
  108081. if (useScreen === void 0) { useScreen = false; }
  108082. if (!useScreen && this._currentRenderTarget) {
  108083. return this._currentRenderTarget.height;
  108084. }
  108085. return this._options.renderHeight;
  108086. };
  108087. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  108088. this._cachedViewport = viewport;
  108089. };
  108090. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  108091. return {
  108092. transformFeedback: null,
  108093. __SPECTOR_rebuildProgram: null
  108094. };
  108095. };
  108096. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  108097. return [];
  108098. };
  108099. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  108100. return [];
  108101. };
  108102. NullEngine.prototype.bindSamplers = function (effect) {
  108103. this._currentEffect = null;
  108104. };
  108105. NullEngine.prototype.enableEffect = function (effect) {
  108106. this._currentEffect = effect;
  108107. if (effect.onBind) {
  108108. effect.onBind(effect);
  108109. }
  108110. if (effect._onBindObservable) {
  108111. effect._onBindObservable.notifyObservers(effect);
  108112. }
  108113. };
  108114. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  108115. if (zOffset === void 0) { zOffset = 0; }
  108116. if (reverseSide === void 0) { reverseSide = false; }
  108117. };
  108118. NullEngine.prototype.setIntArray = function (uniform, array) {
  108119. };
  108120. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  108121. };
  108122. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  108123. };
  108124. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  108125. };
  108126. NullEngine.prototype.setFloatArray = function (uniform, array) {
  108127. };
  108128. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  108129. };
  108130. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  108131. };
  108132. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  108133. };
  108134. NullEngine.prototype.setArray = function (uniform, array) {
  108135. };
  108136. NullEngine.prototype.setArray2 = function (uniform, array) {
  108137. };
  108138. NullEngine.prototype.setArray3 = function (uniform, array) {
  108139. };
  108140. NullEngine.prototype.setArray4 = function (uniform, array) {
  108141. };
  108142. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  108143. };
  108144. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  108145. };
  108146. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  108147. };
  108148. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  108149. };
  108150. NullEngine.prototype.setFloat = function (uniform, value) {
  108151. };
  108152. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  108153. };
  108154. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  108155. };
  108156. NullEngine.prototype.setBool = function (uniform, bool) {
  108157. };
  108158. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  108159. };
  108160. NullEngine.prototype.setColor3 = function (uniform, color3) {
  108161. };
  108162. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  108163. };
  108164. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  108165. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  108166. if (this._alphaMode === mode) {
  108167. return;
  108168. }
  108169. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  108170. if (!noDepthWriteChange) {
  108171. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  108172. }
  108173. this._alphaMode = mode;
  108174. };
  108175. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  108176. };
  108177. NullEngine.prototype.wipeCaches = function (bruteForce) {
  108178. if (this.preventCacheWipeBetweenFrames) {
  108179. return;
  108180. }
  108181. this.resetTextureCache();
  108182. this._currentEffect = null;
  108183. if (bruteForce) {
  108184. this._currentProgram = null;
  108185. this._stencilState.reset();
  108186. this._depthCullingState.reset();
  108187. this._alphaState.reset();
  108188. }
  108189. this._cachedVertexBuffers = null;
  108190. this._cachedIndexBuffer = null;
  108191. this._cachedEffectForVertexBuffers = null;
  108192. };
  108193. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  108194. };
  108195. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  108196. };
  108197. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  108198. };
  108199. /** @hidden */
  108200. NullEngine.prototype._createTexture = function () {
  108201. return {};
  108202. };
  108203. /** @hidden */
  108204. NullEngine.prototype._releaseTexture = function (texture) {
  108205. };
  108206. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  108207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  108208. if (onLoad === void 0) { onLoad = null; }
  108209. if (onError === void 0) { onError = null; }
  108210. if (buffer === void 0) { buffer = null; }
  108211. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  108212. var url = String(urlArg);
  108213. texture.url = url;
  108214. texture.generateMipMaps = !noMipmap;
  108215. texture.samplingMode = samplingMode;
  108216. texture.invertY = invertY;
  108217. texture.baseWidth = this._options.textureSize;
  108218. texture.baseHeight = this._options.textureSize;
  108219. texture.width = this._options.textureSize;
  108220. texture.height = this._options.textureSize;
  108221. if (format) {
  108222. texture.format = format;
  108223. }
  108224. texture.isReady = true;
  108225. if (onLoad) {
  108226. onLoad();
  108227. }
  108228. this._internalTexturesCache.push(texture);
  108229. return texture;
  108230. };
  108231. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  108232. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  108233. if (options !== undefined && typeof options === "object") {
  108234. fullOptions.generateMipMaps = options.generateMipMaps;
  108235. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  108236. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  108237. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  108238. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  108239. }
  108240. else {
  108241. fullOptions.generateMipMaps = options;
  108242. fullOptions.generateDepthBuffer = true;
  108243. fullOptions.generateStencilBuffer = false;
  108244. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108245. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108246. }
  108247. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  108248. var width = size.width || size;
  108249. var height = size.height || size;
  108250. texture._depthStencilBuffer = {};
  108251. texture._framebuffer = {};
  108252. texture.baseWidth = width;
  108253. texture.baseHeight = height;
  108254. texture.width = width;
  108255. texture.height = height;
  108256. texture.isReady = true;
  108257. texture.samples = 1;
  108258. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  108259. texture.samplingMode = fullOptions.samplingMode;
  108260. texture.type = fullOptions.type;
  108261. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  108262. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  108263. this._internalTexturesCache.push(texture);
  108264. return texture;
  108265. };
  108266. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  108267. texture.samplingMode = samplingMode;
  108268. };
  108269. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  108270. if (this._currentRenderTarget) {
  108271. this.unBindFramebuffer(this._currentRenderTarget);
  108272. }
  108273. this._currentRenderTarget = texture;
  108274. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  108275. if (this._cachedViewport && !forceFullscreenViewport) {
  108276. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  108277. }
  108278. };
  108279. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  108280. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  108281. this._currentRenderTarget = null;
  108282. if (onBeforeUnbind) {
  108283. if (texture._MSAAFramebuffer) {
  108284. this._currentFramebuffer = texture._framebuffer;
  108285. }
  108286. onBeforeUnbind();
  108287. }
  108288. this._currentFramebuffer = null;
  108289. };
  108290. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  108291. var vbo = {
  108292. capacity: 1,
  108293. references: 1,
  108294. is32Bits: false
  108295. };
  108296. return vbo;
  108297. };
  108298. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  108299. if (premulAlpha === void 0) { premulAlpha = false; }
  108300. };
  108301. /**
  108302. * @hidden
  108303. * Get the current error code of the webGL context
  108304. * @returns the error code
  108305. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  108306. */
  108307. NullEngine.prototype.getError = function () {
  108308. return 0;
  108309. };
  108310. /** @hidden */
  108311. NullEngine.prototype._getUnpackAlignement = function () {
  108312. return 1;
  108313. };
  108314. /** @hidden */
  108315. NullEngine.prototype._unpackFlipY = function (value) {
  108316. };
  108317. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  108318. if (offset === void 0) { offset = 0; }
  108319. };
  108320. /**
  108321. * Updates a dynamic vertex buffer.
  108322. * @param vertexBuffer the vertex buffer to update
  108323. * @param data the data used to update the vertex buffer
  108324. * @param byteOffset the byte offset of the data (optional)
  108325. * @param byteLength the byte length of the data (optional)
  108326. */
  108327. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  108328. };
  108329. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  108330. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  108331. this._boundTexturesCache[this._activeChannel] = texture;
  108332. return true;
  108333. }
  108334. return false;
  108335. };
  108336. /** @hidden */
  108337. NullEngine.prototype._bindTexture = function (channel, texture) {
  108338. if (channel < 0) {
  108339. return;
  108340. }
  108341. this._bindTextureDirectly(0, texture);
  108342. };
  108343. /** @hidden */
  108344. NullEngine.prototype._releaseBuffer = function (buffer) {
  108345. buffer.references--;
  108346. if (buffer.references === 0) {
  108347. return true;
  108348. }
  108349. return false;
  108350. };
  108351. NullEngine.prototype.releaseEffects = function () {
  108352. };
  108353. NullEngine.prototype.displayLoadingUI = function () {
  108354. };
  108355. NullEngine.prototype.hideLoadingUI = function () {
  108356. };
  108357. /** @hidden */
  108358. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  108359. if (faceIndex === void 0) { faceIndex = 0; }
  108360. if (lod === void 0) { lod = 0; }
  108361. };
  108362. /** @hidden */
  108363. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  108364. if (faceIndex === void 0) { faceIndex = 0; }
  108365. if (lod === void 0) { lod = 0; }
  108366. };
  108367. /** @hidden */
  108368. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  108369. if (faceIndex === void 0) { faceIndex = 0; }
  108370. if (lod === void 0) { lod = 0; }
  108371. };
  108372. /** @hidden */
  108373. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  108374. if (faceIndex === void 0) { faceIndex = 0; }
  108375. if (lod === void 0) { lod = 0; }
  108376. };
  108377. return NullEngine;
  108378. }(BABYLON.Engine));
  108379. BABYLON.NullEngine = NullEngine;
  108380. })(BABYLON || (BABYLON = {}));
  108381. //# sourceMappingURL=babylon.nullEngine.js.map
  108382. var BABYLON;
  108383. (function (BABYLON) {
  108384. /**
  108385. * This class can be used to get instrumentation data from a Babylon engine
  108386. */
  108387. var EngineInstrumentation = /** @class */ (function () {
  108388. function EngineInstrumentation(engine) {
  108389. this.engine = engine;
  108390. this._captureGPUFrameTime = false;
  108391. this._gpuFrameTime = new BABYLON.PerfCounter();
  108392. this._captureShaderCompilationTime = false;
  108393. this._shaderCompilationTime = new BABYLON.PerfCounter();
  108394. // Observers
  108395. this._onBeginFrameObserver = null;
  108396. this._onEndFrameObserver = null;
  108397. this._onBeforeShaderCompilationObserver = null;
  108398. this._onAfterShaderCompilationObserver = null;
  108399. }
  108400. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  108401. // Properties
  108402. /**
  108403. * Gets the perf counter used for GPU frame time
  108404. */
  108405. get: function () {
  108406. return this._gpuFrameTime;
  108407. },
  108408. enumerable: true,
  108409. configurable: true
  108410. });
  108411. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  108412. /**
  108413. * Gets the GPU frame time capture status
  108414. */
  108415. get: function () {
  108416. return this._captureGPUFrameTime;
  108417. },
  108418. /**
  108419. * Enable or disable the GPU frame time capture
  108420. */
  108421. set: function (value) {
  108422. var _this = this;
  108423. if (value === this._captureGPUFrameTime) {
  108424. return;
  108425. }
  108426. this._captureGPUFrameTime = value;
  108427. if (value) {
  108428. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  108429. if (!_this._gpuFrameTimeToken) {
  108430. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  108431. }
  108432. });
  108433. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  108434. if (!_this._gpuFrameTimeToken) {
  108435. return;
  108436. }
  108437. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  108438. if (time > -1) {
  108439. _this._gpuFrameTimeToken = null;
  108440. _this._gpuFrameTime.fetchNewFrame();
  108441. _this._gpuFrameTime.addCount(time, true);
  108442. }
  108443. });
  108444. }
  108445. else {
  108446. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  108447. this._onBeginFrameObserver = null;
  108448. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  108449. this._onEndFrameObserver = null;
  108450. }
  108451. },
  108452. enumerable: true,
  108453. configurable: true
  108454. });
  108455. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  108456. /**
  108457. * Gets the perf counter used for shader compilation time
  108458. */
  108459. get: function () {
  108460. return this._shaderCompilationTime;
  108461. },
  108462. enumerable: true,
  108463. configurable: true
  108464. });
  108465. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  108466. /**
  108467. * Gets the shader compilation time capture status
  108468. */
  108469. get: function () {
  108470. return this._captureShaderCompilationTime;
  108471. },
  108472. /**
  108473. * Enable or disable the shader compilation time capture
  108474. */
  108475. set: function (value) {
  108476. var _this = this;
  108477. if (value === this._captureShaderCompilationTime) {
  108478. return;
  108479. }
  108480. this._captureShaderCompilationTime = value;
  108481. if (value) {
  108482. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  108483. _this._shaderCompilationTime.fetchNewFrame();
  108484. _this._shaderCompilationTime.beginMonitoring();
  108485. });
  108486. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  108487. _this._shaderCompilationTime.endMonitoring();
  108488. });
  108489. }
  108490. else {
  108491. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  108492. this._onBeforeShaderCompilationObserver = null;
  108493. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  108494. this._onAfterShaderCompilationObserver = null;
  108495. }
  108496. },
  108497. enumerable: true,
  108498. configurable: true
  108499. });
  108500. EngineInstrumentation.prototype.dispose = function () {
  108501. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  108502. this._onBeginFrameObserver = null;
  108503. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  108504. this._onEndFrameObserver = null;
  108505. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  108506. this._onBeforeShaderCompilationObserver = null;
  108507. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  108508. this._onAfterShaderCompilationObserver = null;
  108509. this.engine = null;
  108510. };
  108511. return EngineInstrumentation;
  108512. }());
  108513. BABYLON.EngineInstrumentation = EngineInstrumentation;
  108514. })(BABYLON || (BABYLON = {}));
  108515. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  108516. var BABYLON;
  108517. (function (BABYLON) {
  108518. /**
  108519. * This class can be used to get instrumentation data from a Babylon engine
  108520. */
  108521. var SceneInstrumentation = /** @class */ (function () {
  108522. function SceneInstrumentation(scene) {
  108523. var _this = this;
  108524. this.scene = scene;
  108525. this._captureActiveMeshesEvaluationTime = false;
  108526. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  108527. this._captureRenderTargetsRenderTime = false;
  108528. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  108529. this._captureFrameTime = false;
  108530. this._frameTime = new BABYLON.PerfCounter();
  108531. this._captureRenderTime = false;
  108532. this._renderTime = new BABYLON.PerfCounter();
  108533. this._captureInterFrameTime = false;
  108534. this._interFrameTime = new BABYLON.PerfCounter();
  108535. this._captureParticlesRenderTime = false;
  108536. this._particlesRenderTime = new BABYLON.PerfCounter();
  108537. this._captureSpritesRenderTime = false;
  108538. this._spritesRenderTime = new BABYLON.PerfCounter();
  108539. this._capturePhysicsTime = false;
  108540. this._physicsTime = new BABYLON.PerfCounter();
  108541. this._captureAnimationsTime = false;
  108542. this._animationsTime = new BABYLON.PerfCounter();
  108543. this._captureCameraRenderTime = false;
  108544. this._cameraRenderTime = new BABYLON.PerfCounter();
  108545. // Observers
  108546. this._onBeforeActiveMeshesEvaluationObserver = null;
  108547. this._onAfterActiveMeshesEvaluationObserver = null;
  108548. this._onBeforeRenderTargetsRenderObserver = null;
  108549. this._onAfterRenderTargetsRenderObserver = null;
  108550. this._onAfterRenderObserver = null;
  108551. this._onBeforeDrawPhaseObserver = null;
  108552. this._onAfterDrawPhaseObserver = null;
  108553. this._onBeforeAnimationsObserver = null;
  108554. this._onBeforeParticlesRenderingObserver = null;
  108555. this._onAfterParticlesRenderingObserver = null;
  108556. this._onBeforeSpritesRenderingObserver = null;
  108557. this._onAfterSpritesRenderingObserver = null;
  108558. this._onBeforePhysicsObserver = null;
  108559. this._onAfterPhysicsObserver = null;
  108560. this._onAfterAnimationsObserver = null;
  108561. this._onBeforeCameraRenderObserver = null;
  108562. this._onAfterCameraRenderObserver = null;
  108563. // Before render
  108564. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  108565. if (_this._captureActiveMeshesEvaluationTime) {
  108566. _this._activeMeshesEvaluationTime.fetchNewFrame();
  108567. }
  108568. if (_this._captureRenderTargetsRenderTime) {
  108569. _this._renderTargetsRenderTime.fetchNewFrame();
  108570. }
  108571. if (_this._captureFrameTime) {
  108572. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  108573. _this._frameTime.beginMonitoring();
  108574. }
  108575. if (_this._captureInterFrameTime) {
  108576. _this._interFrameTime.endMonitoring();
  108577. }
  108578. if (_this._captureParticlesRenderTime) {
  108579. _this._particlesRenderTime.fetchNewFrame();
  108580. }
  108581. if (_this._captureSpritesRenderTime) {
  108582. _this._spritesRenderTime.fetchNewFrame();
  108583. }
  108584. if (_this._captureAnimationsTime) {
  108585. _this._animationsTime.beginMonitoring();
  108586. }
  108587. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  108588. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  108589. });
  108590. // After render
  108591. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  108592. if (_this._captureFrameTime) {
  108593. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  108594. _this._frameTime.endMonitoring();
  108595. }
  108596. if (_this._captureRenderTime) {
  108597. _this._renderTime.endMonitoring(false);
  108598. }
  108599. if (_this._captureInterFrameTime) {
  108600. _this._interFrameTime.beginMonitoring();
  108601. }
  108602. });
  108603. }
  108604. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  108605. // Properties
  108606. /**
  108607. * Gets the perf counter used for active meshes evaluation time
  108608. */
  108609. get: function () {
  108610. return this._activeMeshesEvaluationTime;
  108611. },
  108612. enumerable: true,
  108613. configurable: true
  108614. });
  108615. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  108616. /**
  108617. * Gets the active meshes evaluation time capture status
  108618. */
  108619. get: function () {
  108620. return this._captureActiveMeshesEvaluationTime;
  108621. },
  108622. /**
  108623. * Enable or disable the active meshes evaluation time capture
  108624. */
  108625. set: function (value) {
  108626. var _this = this;
  108627. if (value === this._captureActiveMeshesEvaluationTime) {
  108628. return;
  108629. }
  108630. this._captureActiveMeshesEvaluationTime = value;
  108631. if (value) {
  108632. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  108633. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  108634. _this._activeMeshesEvaluationTime.beginMonitoring();
  108635. });
  108636. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  108637. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  108638. _this._activeMeshesEvaluationTime.endMonitoring();
  108639. });
  108640. }
  108641. else {
  108642. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  108643. this._onBeforeActiveMeshesEvaluationObserver = null;
  108644. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  108645. this._onAfterActiveMeshesEvaluationObserver = null;
  108646. }
  108647. },
  108648. enumerable: true,
  108649. configurable: true
  108650. });
  108651. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  108652. /**
  108653. * Gets the perf counter used for render targets render time
  108654. */
  108655. get: function () {
  108656. return this._renderTargetsRenderTime;
  108657. },
  108658. enumerable: true,
  108659. configurable: true
  108660. });
  108661. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  108662. /**
  108663. * Gets the render targets render time capture status
  108664. */
  108665. get: function () {
  108666. return this._captureRenderTargetsRenderTime;
  108667. },
  108668. /**
  108669. * Enable or disable the render targets render time capture
  108670. */
  108671. set: function (value) {
  108672. var _this = this;
  108673. if (value === this._captureRenderTargetsRenderTime) {
  108674. return;
  108675. }
  108676. this._captureRenderTargetsRenderTime = value;
  108677. if (value) {
  108678. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  108679. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  108680. _this._renderTargetsRenderTime.beginMonitoring();
  108681. });
  108682. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  108683. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  108684. _this._renderTargetsRenderTime.endMonitoring(false);
  108685. });
  108686. }
  108687. else {
  108688. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  108689. this._onBeforeRenderTargetsRenderObserver = null;
  108690. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  108691. this._onAfterRenderTargetsRenderObserver = null;
  108692. }
  108693. },
  108694. enumerable: true,
  108695. configurable: true
  108696. });
  108697. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  108698. /**
  108699. * Gets the perf counter used for particles render time
  108700. */
  108701. get: function () {
  108702. return this._particlesRenderTime;
  108703. },
  108704. enumerable: true,
  108705. configurable: true
  108706. });
  108707. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  108708. /**
  108709. * Gets the particles render time capture status
  108710. */
  108711. get: function () {
  108712. return this._captureParticlesRenderTime;
  108713. },
  108714. /**
  108715. * Enable or disable the particles render time capture
  108716. */
  108717. set: function (value) {
  108718. var _this = this;
  108719. if (value === this._captureParticlesRenderTime) {
  108720. return;
  108721. }
  108722. this._captureParticlesRenderTime = value;
  108723. if (value) {
  108724. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  108725. BABYLON.Tools.StartPerformanceCounter("Particles");
  108726. _this._particlesRenderTime.beginMonitoring();
  108727. });
  108728. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  108729. BABYLON.Tools.EndPerformanceCounter("Particles");
  108730. _this._particlesRenderTime.endMonitoring(false);
  108731. });
  108732. }
  108733. else {
  108734. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  108735. this._onBeforeParticlesRenderingObserver = null;
  108736. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  108737. this._onAfterParticlesRenderingObserver = null;
  108738. }
  108739. },
  108740. enumerable: true,
  108741. configurable: true
  108742. });
  108743. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  108744. /**
  108745. * Gets the perf counter used for sprites render time
  108746. */
  108747. get: function () {
  108748. return this._spritesRenderTime;
  108749. },
  108750. enumerable: true,
  108751. configurable: true
  108752. });
  108753. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  108754. /**
  108755. * Gets the sprites render time capture status
  108756. */
  108757. get: function () {
  108758. return this._captureSpritesRenderTime;
  108759. },
  108760. /**
  108761. * Enable or disable the sprites render time capture
  108762. */
  108763. set: function (value) {
  108764. var _this = this;
  108765. if (value === this._captureSpritesRenderTime) {
  108766. return;
  108767. }
  108768. this._captureSpritesRenderTime = value;
  108769. if (!this.scene.spriteManagers) {
  108770. return;
  108771. }
  108772. if (value) {
  108773. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  108774. BABYLON.Tools.StartPerformanceCounter("Sprites");
  108775. _this._spritesRenderTime.beginMonitoring();
  108776. });
  108777. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  108778. BABYLON.Tools.EndPerformanceCounter("Sprites");
  108779. _this._spritesRenderTime.endMonitoring(false);
  108780. });
  108781. }
  108782. else {
  108783. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  108784. this._onBeforeSpritesRenderingObserver = null;
  108785. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  108786. this._onAfterSpritesRenderingObserver = null;
  108787. }
  108788. },
  108789. enumerable: true,
  108790. configurable: true
  108791. });
  108792. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  108793. /**
  108794. * Gets the perf counter used for physics time
  108795. */
  108796. get: function () {
  108797. return this._physicsTime;
  108798. },
  108799. enumerable: true,
  108800. configurable: true
  108801. });
  108802. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  108803. /**
  108804. * Gets the physics time capture status
  108805. */
  108806. get: function () {
  108807. return this._capturePhysicsTime;
  108808. },
  108809. /**
  108810. * Enable or disable the physics time capture
  108811. */
  108812. set: function (value) {
  108813. var _this = this;
  108814. if (value === this._capturePhysicsTime) {
  108815. return;
  108816. }
  108817. if (!this.scene.onBeforePhysicsObservable) {
  108818. return;
  108819. }
  108820. this._capturePhysicsTime = value;
  108821. if (value) {
  108822. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  108823. BABYLON.Tools.StartPerformanceCounter("Physics");
  108824. _this._physicsTime.beginMonitoring();
  108825. });
  108826. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  108827. BABYLON.Tools.EndPerformanceCounter("Physics");
  108828. _this._physicsTime.endMonitoring();
  108829. });
  108830. }
  108831. else {
  108832. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  108833. this._onBeforePhysicsObserver = null;
  108834. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  108835. this._onAfterPhysicsObserver = null;
  108836. }
  108837. },
  108838. enumerable: true,
  108839. configurable: true
  108840. });
  108841. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  108842. /**
  108843. * Gets the perf counter used for animations time
  108844. */
  108845. get: function () {
  108846. return this._animationsTime;
  108847. },
  108848. enumerable: true,
  108849. configurable: true
  108850. });
  108851. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  108852. /**
  108853. * Gets the animations time capture status
  108854. */
  108855. get: function () {
  108856. return this._captureAnimationsTime;
  108857. },
  108858. /**
  108859. * Enable or disable the animations time capture
  108860. */
  108861. set: function (value) {
  108862. var _this = this;
  108863. if (value === this._captureAnimationsTime) {
  108864. return;
  108865. }
  108866. this._captureAnimationsTime = value;
  108867. if (value) {
  108868. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  108869. _this._animationsTime.endMonitoring();
  108870. });
  108871. }
  108872. else {
  108873. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  108874. this._onAfterAnimationsObserver = null;
  108875. }
  108876. },
  108877. enumerable: true,
  108878. configurable: true
  108879. });
  108880. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  108881. /**
  108882. * Gets the perf counter used for frame time capture
  108883. */
  108884. get: function () {
  108885. return this._frameTime;
  108886. },
  108887. enumerable: true,
  108888. configurable: true
  108889. });
  108890. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  108891. /**
  108892. * Gets the frame time capture status
  108893. */
  108894. get: function () {
  108895. return this._captureFrameTime;
  108896. },
  108897. /**
  108898. * Enable or disable the frame time capture
  108899. */
  108900. set: function (value) {
  108901. this._captureFrameTime = value;
  108902. },
  108903. enumerable: true,
  108904. configurable: true
  108905. });
  108906. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  108907. /**
  108908. * Gets the perf counter used for inter-frames time capture
  108909. */
  108910. get: function () {
  108911. return this._interFrameTime;
  108912. },
  108913. enumerable: true,
  108914. configurable: true
  108915. });
  108916. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  108917. /**
  108918. * Gets the inter-frames time capture status
  108919. */
  108920. get: function () {
  108921. return this._captureInterFrameTime;
  108922. },
  108923. /**
  108924. * Enable or disable the inter-frames time capture
  108925. */
  108926. set: function (value) {
  108927. this._captureInterFrameTime = value;
  108928. },
  108929. enumerable: true,
  108930. configurable: true
  108931. });
  108932. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  108933. /**
  108934. * Gets the perf counter used for render time capture
  108935. */
  108936. get: function () {
  108937. return this._renderTime;
  108938. },
  108939. enumerable: true,
  108940. configurable: true
  108941. });
  108942. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  108943. /**
  108944. * Gets the render time capture status
  108945. */
  108946. get: function () {
  108947. return this._captureRenderTime;
  108948. },
  108949. /**
  108950. * Enable or disable the render time capture
  108951. */
  108952. set: function (value) {
  108953. var _this = this;
  108954. if (value === this._captureRenderTime) {
  108955. return;
  108956. }
  108957. this._captureRenderTime = value;
  108958. if (value) {
  108959. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  108960. _this._renderTime.beginMonitoring();
  108961. BABYLON.Tools.StartPerformanceCounter("Main render");
  108962. });
  108963. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  108964. _this._renderTime.endMonitoring(false);
  108965. BABYLON.Tools.EndPerformanceCounter("Main render");
  108966. });
  108967. }
  108968. else {
  108969. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  108970. this._onBeforeDrawPhaseObserver = null;
  108971. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  108972. this._onAfterDrawPhaseObserver = null;
  108973. }
  108974. },
  108975. enumerable: true,
  108976. configurable: true
  108977. });
  108978. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  108979. /**
  108980. * Gets the perf counter used for camera render time capture
  108981. */
  108982. get: function () {
  108983. return this._cameraRenderTime;
  108984. },
  108985. enumerable: true,
  108986. configurable: true
  108987. });
  108988. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  108989. /**
  108990. * Gets the camera render time capture status
  108991. */
  108992. get: function () {
  108993. return this._captureCameraRenderTime;
  108994. },
  108995. /**
  108996. * Enable or disable the camera render time capture
  108997. */
  108998. set: function (value) {
  108999. var _this = this;
  109000. if (value === this._captureCameraRenderTime) {
  109001. return;
  109002. }
  109003. this._captureCameraRenderTime = value;
  109004. if (value) {
  109005. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  109006. _this._cameraRenderTime.beginMonitoring();
  109007. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  109008. });
  109009. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  109010. _this._cameraRenderTime.endMonitoring(false);
  109011. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  109012. });
  109013. }
  109014. else {
  109015. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  109016. this._onBeforeCameraRenderObserver = null;
  109017. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  109018. this._onAfterCameraRenderObserver = null;
  109019. }
  109020. },
  109021. enumerable: true,
  109022. configurable: true
  109023. });
  109024. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  109025. /**
  109026. * Gets the perf counter used for draw calls
  109027. */
  109028. get: function () {
  109029. return this.scene.getEngine()._drawCalls;
  109030. },
  109031. enumerable: true,
  109032. configurable: true
  109033. });
  109034. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  109035. /**
  109036. * Gets the perf counter used for texture collisions
  109037. */
  109038. get: function () {
  109039. return this.scene.getEngine()._textureCollisions;
  109040. },
  109041. enumerable: true,
  109042. configurable: true
  109043. });
  109044. SceneInstrumentation.prototype.dispose = function () {
  109045. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  109046. this._onAfterRenderObserver = null;
  109047. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109048. this._onBeforeActiveMeshesEvaluationObserver = null;
  109049. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109050. this._onAfterActiveMeshesEvaluationObserver = null;
  109051. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109052. this._onBeforeRenderTargetsRenderObserver = null;
  109053. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109054. this._onAfterRenderTargetsRenderObserver = null;
  109055. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  109056. this._onBeforeAnimationsObserver = null;
  109057. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109058. this._onBeforeParticlesRenderingObserver = null;
  109059. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109060. this._onAfterParticlesRenderingObserver = null;
  109061. if (this._onBeforeSpritesRenderingObserver) {
  109062. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109063. this._onBeforeSpritesRenderingObserver = null;
  109064. }
  109065. if (this._onAfterSpritesRenderingObserver) {
  109066. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109067. this._onAfterSpritesRenderingObserver = null;
  109068. }
  109069. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  109070. this._onBeforeDrawPhaseObserver = null;
  109071. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  109072. this._onAfterDrawPhaseObserver = null;
  109073. if (this._onBeforePhysicsObserver) {
  109074. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  109075. this._onBeforePhysicsObserver = null;
  109076. }
  109077. if (this._onAfterPhysicsObserver) {
  109078. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  109079. this._onAfterPhysicsObserver = null;
  109080. }
  109081. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  109082. this._onAfterAnimationsObserver = null;
  109083. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  109084. this._onBeforeCameraRenderObserver = null;
  109085. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  109086. this._onAfterCameraRenderObserver = null;
  109087. this.scene = null;
  109088. };
  109089. return SceneInstrumentation;
  109090. }());
  109091. BABYLON.SceneInstrumentation = SceneInstrumentation;
  109092. })(BABYLON || (BABYLON = {}));
  109093. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  109094. var BABYLON;
  109095. (function (BABYLON) {
  109096. /**
  109097. * @hidden
  109098. **/
  109099. var _TimeToken = /** @class */ (function () {
  109100. function _TimeToken() {
  109101. this._timeElapsedQueryEnded = false;
  109102. }
  109103. return _TimeToken;
  109104. }());
  109105. BABYLON._TimeToken = _TimeToken;
  109106. })(BABYLON || (BABYLON = {}));
  109107. //# sourceMappingURL=babylon.timeToken.js.map
  109108. var BABYLON;
  109109. (function (BABYLON) {
  109110. /**
  109111. * Background material defines definition.
  109112. * @hidden Mainly internal Use
  109113. */
  109114. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  109115. __extends(BackgroundMaterialDefines, _super);
  109116. /**
  109117. * Constructor of the defines.
  109118. */
  109119. function BackgroundMaterialDefines() {
  109120. var _this = _super.call(this) || this;
  109121. /**
  109122. * True if the diffuse texture is in use.
  109123. */
  109124. _this.DIFFUSE = false;
  109125. /**
  109126. * The direct UV channel to use.
  109127. */
  109128. _this.DIFFUSEDIRECTUV = 0;
  109129. /**
  109130. * True if the diffuse texture is in gamma space.
  109131. */
  109132. _this.GAMMADIFFUSE = false;
  109133. /**
  109134. * True if the diffuse texture has opacity in the alpha channel.
  109135. */
  109136. _this.DIFFUSEHASALPHA = false;
  109137. /**
  109138. * True if you want the material to fade to transparent at grazing angle.
  109139. */
  109140. _this.OPACITYFRESNEL = false;
  109141. /**
  109142. * True if an extra blur needs to be added in the reflection.
  109143. */
  109144. _this.REFLECTIONBLUR = false;
  109145. /**
  109146. * True if you want the material to fade to reflection at grazing angle.
  109147. */
  109148. _this.REFLECTIONFRESNEL = false;
  109149. /**
  109150. * True if you want the material to falloff as far as you move away from the scene center.
  109151. */
  109152. _this.REFLECTIONFALLOFF = false;
  109153. /**
  109154. * False if the current Webgl implementation does not support the texture lod extension.
  109155. */
  109156. _this.TEXTURELODSUPPORT = false;
  109157. /**
  109158. * True to ensure the data are premultiplied.
  109159. */
  109160. _this.PREMULTIPLYALPHA = false;
  109161. /**
  109162. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  109163. */
  109164. _this.USERGBCOLOR = false;
  109165. /**
  109166. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  109167. * stays aligned with the desired configuration.
  109168. */
  109169. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  109170. /**
  109171. * True to add noise in order to reduce the banding effect.
  109172. */
  109173. _this.NOISE = false;
  109174. /**
  109175. * is the reflection texture in BGR color scheme?
  109176. * Mainly used to solve a bug in ios10 video tag
  109177. */
  109178. _this.REFLECTIONBGR = false;
  109179. _this.IMAGEPROCESSING = false;
  109180. _this.VIGNETTE = false;
  109181. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  109182. _this.VIGNETTEBLENDMODEOPAQUE = false;
  109183. _this.TONEMAPPING = false;
  109184. _this.TONEMAPPING_ACES = false;
  109185. _this.CONTRAST = false;
  109186. _this.COLORCURVES = false;
  109187. _this.COLORGRADING = false;
  109188. _this.COLORGRADING3D = false;
  109189. _this.SAMPLER3DGREENDEPTH = false;
  109190. _this.SAMPLER3DBGRMAP = false;
  109191. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  109192. _this.EXPOSURE = false;
  109193. // Reflection.
  109194. _this.REFLECTION = false;
  109195. _this.REFLECTIONMAP_3D = false;
  109196. _this.REFLECTIONMAP_SPHERICAL = false;
  109197. _this.REFLECTIONMAP_PLANAR = false;
  109198. _this.REFLECTIONMAP_CUBIC = false;
  109199. _this.REFLECTIONMAP_PROJECTION = false;
  109200. _this.REFLECTIONMAP_SKYBOX = false;
  109201. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  109202. _this.REFLECTIONMAP_EXPLICIT = false;
  109203. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  109204. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  109205. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  109206. _this.INVERTCUBICMAP = false;
  109207. _this.REFLECTIONMAP_OPPOSITEZ = false;
  109208. _this.LODINREFLECTIONALPHA = false;
  109209. _this.GAMMAREFLECTION = false;
  109210. _this.RGBDREFLECTION = false;
  109211. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  109212. // Default BJS.
  109213. _this.MAINUV1 = false;
  109214. _this.MAINUV2 = false;
  109215. _this.UV1 = false;
  109216. _this.UV2 = false;
  109217. _this.CLIPPLANE = false;
  109218. _this.CLIPPLANE2 = false;
  109219. _this.CLIPPLANE3 = false;
  109220. _this.CLIPPLANE4 = false;
  109221. _this.POINTSIZE = false;
  109222. _this.FOG = false;
  109223. _this.NORMAL = false;
  109224. _this.NUM_BONE_INFLUENCERS = 0;
  109225. _this.BonesPerMesh = 0;
  109226. _this.INSTANCES = false;
  109227. _this.SHADOWFLOAT = false;
  109228. _this.rebuild();
  109229. return _this;
  109230. }
  109231. return BackgroundMaterialDefines;
  109232. }(BABYLON.MaterialDefines));
  109233. /**
  109234. * Background material used to create an efficient environement around your scene.
  109235. */
  109236. var BackgroundMaterial = /** @class */ (function (_super) {
  109237. __extends(BackgroundMaterial, _super);
  109238. /**
  109239. * Instantiates a Background Material in the given scene
  109240. * @param name The friendly name of the material
  109241. * @param scene The scene to add the material to
  109242. */
  109243. function BackgroundMaterial(name, scene) {
  109244. var _this = _super.call(this, name, scene) || this;
  109245. /**
  109246. * Key light Color (multiply against the environement texture)
  109247. */
  109248. _this.primaryColor = BABYLON.Color3.White();
  109249. _this._primaryColorShadowLevel = 0;
  109250. _this._primaryColorHighlightLevel = 0;
  109251. /**
  109252. * Reflection Texture used in the material.
  109253. * Should be author in a specific way for the best result (refer to the documentation).
  109254. */
  109255. _this.reflectionTexture = null;
  109256. /**
  109257. * Reflection Texture level of blur.
  109258. *
  109259. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  109260. * texture twice.
  109261. */
  109262. _this.reflectionBlur = 0;
  109263. /**
  109264. * Diffuse Texture used in the material.
  109265. * Should be author in a specific way for the best result (refer to the documentation).
  109266. */
  109267. _this.diffuseTexture = null;
  109268. _this._shadowLights = null;
  109269. /**
  109270. * Specify the list of lights casting shadow on the material.
  109271. * All scene shadow lights will be included if null.
  109272. */
  109273. _this.shadowLights = null;
  109274. /**
  109275. * Helps adjusting the shadow to a softer level if required.
  109276. * 0 means black shadows and 1 means no shadows.
  109277. */
  109278. _this.shadowLevel = 0;
  109279. /**
  109280. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  109281. * It is usually zero but might be interesting to modify according to your setup.
  109282. */
  109283. _this.sceneCenter = BABYLON.Vector3.Zero();
  109284. /**
  109285. * This helps specifying that the material is falling off to the sky box at grazing angle.
  109286. * This helps ensuring a nice transition when the camera goes under the ground.
  109287. */
  109288. _this.opacityFresnel = true;
  109289. /**
  109290. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  109291. * This helps adding a mirror texture on the ground.
  109292. */
  109293. _this.reflectionFresnel = false;
  109294. /**
  109295. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  109296. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  109297. */
  109298. _this.reflectionFalloffDistance = 0.0;
  109299. /**
  109300. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  109301. */
  109302. _this.reflectionAmount = 1.0;
  109303. /**
  109304. * This specifies the weight of the reflection at grazing angle.
  109305. */
  109306. _this.reflectionReflectance0 = 0.05;
  109307. /**
  109308. * This specifies the weight of the reflection at a perpendicular point of view.
  109309. */
  109310. _this.reflectionReflectance90 = 0.5;
  109311. /**
  109312. * Helps to directly use the maps channels instead of their level.
  109313. */
  109314. _this.useRGBColor = true;
  109315. /**
  109316. * This helps reducing the banding effect that could occur on the background.
  109317. */
  109318. _this.enableNoise = false;
  109319. _this._fovMultiplier = 1.0;
  109320. /**
  109321. * Enable the FOV adjustment feature controlled by fovMultiplier.
  109322. */
  109323. _this.useEquirectangularFOV = false;
  109324. _this._maxSimultaneousLights = 4;
  109325. /**
  109326. * Number of Simultaneous lights allowed on the material.
  109327. */
  109328. _this.maxSimultaneousLights = 4;
  109329. /**
  109330. * Keep track of the image processing observer to allow dispose and replace.
  109331. */
  109332. _this._imageProcessingObserver = null;
  109333. /**
  109334. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  109335. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  109336. */
  109337. _this.switchToBGR = false;
  109338. // Temp values kept as cache in the material.
  109339. _this._renderTargets = new BABYLON.SmartArray(16);
  109340. _this._reflectionControls = BABYLON.Vector4.Zero();
  109341. _this._white = BABYLON.Color3.White();
  109342. _this._primaryShadowColor = BABYLON.Color3.Black();
  109343. _this._primaryHighlightColor = BABYLON.Color3.Black();
  109344. // Setup the default processing configuration to the scene.
  109345. _this._attachImageProcessingConfiguration(null);
  109346. _this.getRenderTargetTextures = function () {
  109347. _this._renderTargets.reset();
  109348. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  109349. _this._renderTargets.push(_this._diffuseTexture);
  109350. }
  109351. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  109352. _this._renderTargets.push(_this._reflectionTexture);
  109353. }
  109354. return _this._renderTargets;
  109355. };
  109356. return _this;
  109357. }
  109358. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  109359. /**
  109360. * Experimental Internal Use Only.
  109361. *
  109362. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  109363. * This acts as a helper to set the primary color to a more "human friendly" value.
  109364. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  109365. * output color as close as possible from the chosen value.
  109366. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  109367. * part of lighting setup.)
  109368. */
  109369. get: function () {
  109370. return this.__perceptualColor;
  109371. },
  109372. set: function (value) {
  109373. this.__perceptualColor = value;
  109374. this._computePrimaryColorFromPerceptualColor();
  109375. this._markAllSubMeshesAsLightsDirty();
  109376. },
  109377. enumerable: true,
  109378. configurable: true
  109379. });
  109380. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  109381. /**
  109382. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  109383. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  109384. */
  109385. get: function () {
  109386. return this._primaryColorShadowLevel;
  109387. },
  109388. set: function (value) {
  109389. this._primaryColorShadowLevel = value;
  109390. this._computePrimaryColors();
  109391. this._markAllSubMeshesAsLightsDirty();
  109392. },
  109393. enumerable: true,
  109394. configurable: true
  109395. });
  109396. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  109397. /**
  109398. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  109399. * The primary color is used at the level chosen to define what the white area would look.
  109400. */
  109401. get: function () {
  109402. return this._primaryColorHighlightLevel;
  109403. },
  109404. set: function (value) {
  109405. this._primaryColorHighlightLevel = value;
  109406. this._computePrimaryColors();
  109407. this._markAllSubMeshesAsLightsDirty();
  109408. },
  109409. enumerable: true,
  109410. configurable: true
  109411. });
  109412. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  109413. /**
  109414. * Sets the reflection reflectance fresnel values according to the default standard
  109415. * empirically know to work well :-)
  109416. */
  109417. set: function (value) {
  109418. var reflectionWeight = value;
  109419. if (reflectionWeight < 0.5) {
  109420. reflectionWeight = reflectionWeight * 2.0;
  109421. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  109422. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  109423. }
  109424. else {
  109425. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  109426. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  109427. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  109428. }
  109429. },
  109430. enumerable: true,
  109431. configurable: true
  109432. });
  109433. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  109434. /**
  109435. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109436. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  109437. * Recommended to be keep at 1.0 except for special cases.
  109438. */
  109439. get: function () {
  109440. return this._fovMultiplier;
  109441. },
  109442. set: function (value) {
  109443. if (isNaN(value)) {
  109444. value = 1.0;
  109445. }
  109446. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  109447. },
  109448. enumerable: true,
  109449. configurable: true
  109450. });
  109451. /**
  109452. * Attaches a new image processing configuration to the PBR Material.
  109453. * @param configuration (if null the scene configuration will be use)
  109454. */
  109455. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  109456. var _this = this;
  109457. if (configuration === this._imageProcessingConfiguration) {
  109458. return;
  109459. }
  109460. // Detaches observer.
  109461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  109462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  109463. }
  109464. // Pick the scene configuration if needed.
  109465. if (!configuration) {
  109466. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  109467. }
  109468. else {
  109469. this._imageProcessingConfiguration = configuration;
  109470. }
  109471. // Attaches observer.
  109472. if (this._imageProcessingConfiguration) {
  109473. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  109474. _this._computePrimaryColorFromPerceptualColor();
  109475. _this._markAllSubMeshesAsImageProcessingDirty();
  109476. });
  109477. }
  109478. };
  109479. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  109480. /**
  109481. * Gets the image processing configuration used either in this material.
  109482. */
  109483. get: function () {
  109484. return this._imageProcessingConfiguration;
  109485. },
  109486. /**
  109487. * Sets the Default image processing configuration used either in the this material.
  109488. *
  109489. * If sets to null, the scene one is in use.
  109490. */
  109491. set: function (value) {
  109492. this._attachImageProcessingConfiguration(value);
  109493. // Ensure the effect will be rebuilt.
  109494. this._markAllSubMeshesAsTexturesDirty();
  109495. },
  109496. enumerable: true,
  109497. configurable: true
  109498. });
  109499. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  109500. /**
  109501. * Gets wether the color curves effect is enabled.
  109502. */
  109503. get: function () {
  109504. return this.imageProcessingConfiguration.colorCurvesEnabled;
  109505. },
  109506. /**
  109507. * Sets wether the color curves effect is enabled.
  109508. */
  109509. set: function (value) {
  109510. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  109511. },
  109512. enumerable: true,
  109513. configurable: true
  109514. });
  109515. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  109516. /**
  109517. * Gets wether the color grading effect is enabled.
  109518. */
  109519. get: function () {
  109520. return this.imageProcessingConfiguration.colorGradingEnabled;
  109521. },
  109522. /**
  109523. * Gets wether the color grading effect is enabled.
  109524. */
  109525. set: function (value) {
  109526. this.imageProcessingConfiguration.colorGradingEnabled = value;
  109527. },
  109528. enumerable: true,
  109529. configurable: true
  109530. });
  109531. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  109532. /**
  109533. * Gets wether tonemapping is enabled or not.
  109534. */
  109535. get: function () {
  109536. return this._imageProcessingConfiguration.toneMappingEnabled;
  109537. },
  109538. /**
  109539. * Sets wether tonemapping is enabled or not
  109540. */
  109541. set: function (value) {
  109542. this._imageProcessingConfiguration.toneMappingEnabled = value;
  109543. },
  109544. enumerable: true,
  109545. configurable: true
  109546. });
  109547. ;
  109548. ;
  109549. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  109550. /**
  109551. * The camera exposure used on this material.
  109552. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  109553. * This corresponds to a photographic exposure.
  109554. */
  109555. get: function () {
  109556. return this._imageProcessingConfiguration.exposure;
  109557. },
  109558. /**
  109559. * The camera exposure used on this material.
  109560. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  109561. * This corresponds to a photographic exposure.
  109562. */
  109563. set: function (value) {
  109564. this._imageProcessingConfiguration.exposure = value;
  109565. },
  109566. enumerable: true,
  109567. configurable: true
  109568. });
  109569. ;
  109570. ;
  109571. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  109572. /**
  109573. * Gets The camera contrast used on this material.
  109574. */
  109575. get: function () {
  109576. return this._imageProcessingConfiguration.contrast;
  109577. },
  109578. /**
  109579. * Sets The camera contrast used on this material.
  109580. */
  109581. set: function (value) {
  109582. this._imageProcessingConfiguration.contrast = value;
  109583. },
  109584. enumerable: true,
  109585. configurable: true
  109586. });
  109587. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  109588. /**
  109589. * Gets the Color Grading 2D Lookup Texture.
  109590. */
  109591. get: function () {
  109592. return this._imageProcessingConfiguration.colorGradingTexture;
  109593. },
  109594. /**
  109595. * Sets the Color Grading 2D Lookup Texture.
  109596. */
  109597. set: function (value) {
  109598. this.imageProcessingConfiguration.colorGradingTexture = value;
  109599. },
  109600. enumerable: true,
  109601. configurable: true
  109602. });
  109603. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  109604. /**
  109605. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  109606. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  109607. * 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;
  109608. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  109609. */
  109610. get: function () {
  109611. return this.imageProcessingConfiguration.colorCurves;
  109612. },
  109613. /**
  109614. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  109615. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  109616. * 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;
  109617. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  109618. */
  109619. set: function (value) {
  109620. this.imageProcessingConfiguration.colorCurves = value;
  109621. },
  109622. enumerable: true,
  109623. configurable: true
  109624. });
  109625. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  109626. /**
  109627. * Gets a boolean indicating that current material needs to register RTT
  109628. */
  109629. get: function () {
  109630. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  109631. return true;
  109632. }
  109633. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  109634. return true;
  109635. }
  109636. return false;
  109637. },
  109638. enumerable: true,
  109639. configurable: true
  109640. });
  109641. /**
  109642. * The entire material has been created in order to prevent overdraw.
  109643. * @returns false
  109644. */
  109645. BackgroundMaterial.prototype.needAlphaTesting = function () {
  109646. return true;
  109647. };
  109648. /**
  109649. * The entire material has been created in order to prevent overdraw.
  109650. * @returns true if blending is enable
  109651. */
  109652. BackgroundMaterial.prototype.needAlphaBlending = function () {
  109653. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  109654. };
  109655. /**
  109656. * Checks wether the material is ready to be rendered for a given mesh.
  109657. * @param mesh The mesh to render
  109658. * @param subMesh The submesh to check against
  109659. * @param useInstances Specify wether or not the material is used with instances
  109660. * @returns true if all the dependencies are ready (Textures, Effects...)
  109661. */
  109662. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  109663. var _this = this;
  109664. if (useInstances === void 0) { useInstances = false; }
  109665. if (subMesh.effect && this.isFrozen) {
  109666. if (this._wasPreviouslyReady) {
  109667. return true;
  109668. }
  109669. }
  109670. if (!subMesh._materialDefines) {
  109671. subMesh._materialDefines = new BackgroundMaterialDefines();
  109672. }
  109673. var scene = this.getScene();
  109674. var defines = subMesh._materialDefines;
  109675. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  109676. if (defines._renderId === scene.getRenderId()) {
  109677. return true;
  109678. }
  109679. }
  109680. var engine = scene.getEngine();
  109681. // Lights
  109682. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  109683. defines._needNormals = true;
  109684. // Textures
  109685. if (defines._areTexturesDirty) {
  109686. defines._needUVs = false;
  109687. if (scene.texturesEnabled) {
  109688. if (scene.getEngine().getCaps().textureLOD) {
  109689. defines.TEXTURELODSUPPORT = true;
  109690. }
  109691. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  109692. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  109693. return false;
  109694. }
  109695. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  109696. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  109697. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  109698. defines.OPACITYFRESNEL = this._opacityFresnel;
  109699. }
  109700. else {
  109701. defines.DIFFUSE = false;
  109702. defines.DIFFUSEHASALPHA = false;
  109703. defines.GAMMADIFFUSE = false;
  109704. defines.OPACITYFRESNEL = false;
  109705. }
  109706. var reflectionTexture = this._reflectionTexture;
  109707. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  109708. if (!reflectionTexture.isReadyOrNotBlocking()) {
  109709. return false;
  109710. }
  109711. defines.REFLECTION = true;
  109712. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  109713. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  109714. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  109715. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  109716. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  109717. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  109718. defines.REFLECTIONBGR = this.switchToBGR;
  109719. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  109720. defines.INVERTCUBICMAP = true;
  109721. }
  109722. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  109723. switch (reflectionTexture.coordinatesMode) {
  109724. case BABYLON.Texture.EXPLICIT_MODE:
  109725. defines.REFLECTIONMAP_EXPLICIT = true;
  109726. break;
  109727. case BABYLON.Texture.PLANAR_MODE:
  109728. defines.REFLECTIONMAP_PLANAR = true;
  109729. break;
  109730. case BABYLON.Texture.PROJECTION_MODE:
  109731. defines.REFLECTIONMAP_PROJECTION = true;
  109732. break;
  109733. case BABYLON.Texture.SKYBOX_MODE:
  109734. defines.REFLECTIONMAP_SKYBOX = true;
  109735. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  109736. break;
  109737. case BABYLON.Texture.SPHERICAL_MODE:
  109738. defines.REFLECTIONMAP_SPHERICAL = true;
  109739. break;
  109740. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  109741. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  109742. break;
  109743. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  109744. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  109745. break;
  109746. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  109747. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  109748. break;
  109749. case BABYLON.Texture.CUBIC_MODE:
  109750. case BABYLON.Texture.INVCUBIC_MODE:
  109751. default:
  109752. defines.REFLECTIONMAP_CUBIC = true;
  109753. break;
  109754. }
  109755. if (this.reflectionFresnel) {
  109756. defines.REFLECTIONFRESNEL = true;
  109757. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  109758. this._reflectionControls.x = this.reflectionAmount;
  109759. this._reflectionControls.y = this.reflectionReflectance0;
  109760. this._reflectionControls.z = this.reflectionReflectance90;
  109761. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  109762. }
  109763. else {
  109764. defines.REFLECTIONFRESNEL = false;
  109765. defines.REFLECTIONFALLOFF = false;
  109766. }
  109767. }
  109768. else {
  109769. defines.REFLECTION = false;
  109770. defines.REFLECTIONFRESNEL = false;
  109771. defines.REFLECTIONFALLOFF = false;
  109772. defines.REFLECTIONBLUR = false;
  109773. defines.REFLECTIONMAP_3D = false;
  109774. defines.REFLECTIONMAP_SPHERICAL = false;
  109775. defines.REFLECTIONMAP_PLANAR = false;
  109776. defines.REFLECTIONMAP_CUBIC = false;
  109777. defines.REFLECTIONMAP_PROJECTION = false;
  109778. defines.REFLECTIONMAP_SKYBOX = false;
  109779. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  109780. defines.REFLECTIONMAP_EXPLICIT = false;
  109781. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  109782. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  109783. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  109784. defines.INVERTCUBICMAP = false;
  109785. defines.REFLECTIONMAP_OPPOSITEZ = false;
  109786. defines.LODINREFLECTIONALPHA = false;
  109787. defines.GAMMAREFLECTION = false;
  109788. defines.RGBDREFLECTION = false;
  109789. }
  109790. }
  109791. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  109792. defines.USERGBCOLOR = this._useRGBColor;
  109793. defines.NOISE = this._enableNoise;
  109794. }
  109795. if (defines._areLightsDirty) {
  109796. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  109797. }
  109798. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  109799. if (!this._imageProcessingConfiguration.isReady()) {
  109800. return false;
  109801. }
  109802. this._imageProcessingConfiguration.prepareDefines(defines);
  109803. }
  109804. // Misc.
  109805. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  109806. // Values that need to be evaluated on every frame
  109807. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  109808. // Attribs
  109809. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  109810. if (mesh) {
  109811. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  109812. mesh.createNormals(true);
  109813. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  109814. }
  109815. }
  109816. }
  109817. // Get correct effect
  109818. if (defines.isDirty) {
  109819. defines.markAsProcessed();
  109820. scene.resetCachedMaterial();
  109821. // Fallbacks
  109822. var fallbacks = new BABYLON.EffectFallbacks();
  109823. if (defines.FOG) {
  109824. fallbacks.addFallback(0, "FOG");
  109825. }
  109826. if (defines.POINTSIZE) {
  109827. fallbacks.addFallback(1, "POINTSIZE");
  109828. }
  109829. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  109830. if (defines.NUM_BONE_INFLUENCERS > 0) {
  109831. fallbacks.addCPUSkinningFallback(0, mesh);
  109832. }
  109833. //Attributes
  109834. var attribs = [BABYLON.VertexBuffer.PositionKind];
  109835. if (defines.NORMAL) {
  109836. attribs.push(BABYLON.VertexBuffer.NormalKind);
  109837. }
  109838. if (defines.UV1) {
  109839. attribs.push(BABYLON.VertexBuffer.UVKind);
  109840. }
  109841. if (defines.UV2) {
  109842. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109843. }
  109844. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  109845. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  109846. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  109847. "vFogInfos", "vFogColor", "pointSize",
  109848. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  109849. "vPrimaryColor", "vPrimaryColorShadow",
  109850. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  109851. "shadowLevel", "alpha",
  109852. "vBackgroundCenter", "vReflectionControl",
  109853. "vDiffuseInfos", "diffuseMatrix",
  109854. ];
  109855. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  109856. var uniformBuffers = ["Material", "Scene"];
  109857. if (BABYLON.ImageProcessingConfiguration) {
  109858. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  109859. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  109860. }
  109861. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  109862. uniformsNames: uniforms,
  109863. uniformBuffersNames: uniformBuffers,
  109864. samplers: samplers,
  109865. defines: defines,
  109866. maxSimultaneousLights: this._maxSimultaneousLights
  109867. });
  109868. var onCompiled = function (effect) {
  109869. if (_this.onCompiled) {
  109870. _this.onCompiled(effect);
  109871. }
  109872. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  109873. };
  109874. var join = defines.toString();
  109875. subMesh.setEffect(scene.getEngine().createEffect("background", {
  109876. attributes: attribs,
  109877. uniformsNames: uniforms,
  109878. uniformBuffersNames: uniformBuffers,
  109879. samplers: samplers,
  109880. defines: join,
  109881. fallbacks: fallbacks,
  109882. onCompiled: onCompiled,
  109883. onError: this.onError,
  109884. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  109885. }, engine), defines);
  109886. this.buildUniformLayout();
  109887. }
  109888. if (!subMesh.effect || !subMesh.effect.isReady()) {
  109889. return false;
  109890. }
  109891. defines._renderId = scene.getRenderId();
  109892. this._wasPreviouslyReady = true;
  109893. return true;
  109894. };
  109895. /**
  109896. * Compute the primary color according to the chosen perceptual color.
  109897. */
  109898. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  109899. if (!this.__perceptualColor) {
  109900. return;
  109901. }
  109902. this._primaryColor.copyFrom(this.__perceptualColor);
  109903. // Revert gamma space.
  109904. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  109905. // Revert image processing configuration.
  109906. if (this._imageProcessingConfiguration) {
  109907. // Revert Exposure.
  109908. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  109909. }
  109910. this._computePrimaryColors();
  109911. };
  109912. /**
  109913. * Compute the highlights and shadow colors according to their chosen levels.
  109914. */
  109915. BackgroundMaterial.prototype._computePrimaryColors = function () {
  109916. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  109917. return;
  109918. }
  109919. // Find the highlight color based on the configuration.
  109920. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  109921. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  109922. // Find the shadow color based on the configuration.
  109923. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  109924. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  109925. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  109926. };
  109927. /**
  109928. * Build the uniform buffer used in the material.
  109929. */
  109930. BackgroundMaterial.prototype.buildUniformLayout = function () {
  109931. // Order is important !
  109932. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  109933. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  109934. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  109935. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  109936. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  109937. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  109938. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  109939. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  109940. this._uniformBuffer.addUniform("pointSize", 1);
  109941. this._uniformBuffer.addUniform("shadowLevel", 1);
  109942. this._uniformBuffer.addUniform("alpha", 1);
  109943. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  109944. this._uniformBuffer.addUniform("vReflectionControl", 4);
  109945. this._uniformBuffer.create();
  109946. };
  109947. /**
  109948. * Unbind the material.
  109949. */
  109950. BackgroundMaterial.prototype.unbind = function () {
  109951. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  109952. this._uniformBuffer.setTexture("diffuseSampler", null);
  109953. }
  109954. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  109955. this._uniformBuffer.setTexture("reflectionSampler", null);
  109956. }
  109957. _super.prototype.unbind.call(this);
  109958. };
  109959. /**
  109960. * Bind only the world matrix to the material.
  109961. * @param world The world matrix to bind.
  109962. */
  109963. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  109964. this._activeEffect.setMatrix("world", world);
  109965. };
  109966. /**
  109967. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  109968. * @param world The world matrix to bind.
  109969. * @param subMesh The submesh to bind for.
  109970. */
  109971. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  109972. var scene = this.getScene();
  109973. var defines = subMesh._materialDefines;
  109974. if (!defines) {
  109975. return;
  109976. }
  109977. var effect = subMesh.effect;
  109978. if (!effect) {
  109979. return;
  109980. }
  109981. this._activeEffect = effect;
  109982. // Matrices
  109983. this.bindOnlyWorldMatrix(world);
  109984. // Bones
  109985. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  109986. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  109987. if (mustRebind) {
  109988. this._uniformBuffer.bindToEffect(effect, "Material");
  109989. this.bindViewProjection(effect);
  109990. var reflectionTexture = this._reflectionTexture;
  109991. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  109992. // Texture uniforms
  109993. if (scene.texturesEnabled) {
  109994. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  109995. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  109996. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  109997. }
  109998. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  109999. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  110000. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  110001. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  110002. }
  110003. }
  110004. if (this.shadowLevel > 0) {
  110005. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  110006. }
  110007. this._uniformBuffer.updateFloat("alpha", this.alpha);
  110008. // Point size
  110009. if (this.pointsCloud) {
  110010. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  110011. }
  110012. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  110013. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  110014. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  110015. }
  110016. else {
  110017. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  110018. }
  110019. }
  110020. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  110021. // Textures
  110022. if (scene.texturesEnabled) {
  110023. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110024. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  110025. }
  110026. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110027. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  110028. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  110029. }
  110030. else if (!defines.REFLECTIONBLUR) {
  110031. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  110032. }
  110033. else {
  110034. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  110035. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  110036. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  110037. }
  110038. if (defines.REFLECTIONFRESNEL) {
  110039. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  110040. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  110041. }
  110042. }
  110043. }
  110044. // Clip plane
  110045. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  110046. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  110047. }
  110048. if (mustRebind || !this.isFrozen) {
  110049. if (scene.lightsEnabled) {
  110050. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  110051. }
  110052. // View
  110053. this.bindView(effect);
  110054. // Fog
  110055. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  110056. // image processing
  110057. if (this._imageProcessingConfiguration) {
  110058. this._imageProcessingConfiguration.bind(this._activeEffect);
  110059. }
  110060. }
  110061. this._uniformBuffer.update();
  110062. this._afterBind(mesh, this._activeEffect);
  110063. };
  110064. /**
  110065. * Dispose the material.
  110066. * @param forceDisposeEffect Force disposal of the associated effect.
  110067. * @param forceDisposeTextures Force disposal of the associated textures.
  110068. */
  110069. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  110070. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  110071. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  110072. if (forceDisposeTextures) {
  110073. if (this.diffuseTexture) {
  110074. this.diffuseTexture.dispose();
  110075. }
  110076. if (this.reflectionTexture) {
  110077. this.reflectionTexture.dispose();
  110078. }
  110079. }
  110080. this._renderTargets.dispose();
  110081. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  110082. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  110083. }
  110084. _super.prototype.dispose.call(this, forceDisposeEffect);
  110085. };
  110086. /**
  110087. * Clones the material.
  110088. * @param name The cloned name.
  110089. * @returns The cloned material.
  110090. */
  110091. BackgroundMaterial.prototype.clone = function (name) {
  110092. var _this = this;
  110093. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  110094. };
  110095. /**
  110096. * Serializes the current material to its JSON representation.
  110097. * @returns The JSON representation.
  110098. */
  110099. BackgroundMaterial.prototype.serialize = function () {
  110100. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110101. serializationObject.customType = "BABYLON.BackgroundMaterial";
  110102. return serializationObject;
  110103. };
  110104. /**
  110105. * Gets the class name of the material
  110106. * @returns "BackgroundMaterial"
  110107. */
  110108. BackgroundMaterial.prototype.getClassName = function () {
  110109. return "BackgroundMaterial";
  110110. };
  110111. /**
  110112. * Parse a JSON input to create back a background material.
  110113. * @param source The JSON data to parse
  110114. * @param scene The scene to create the parsed material in
  110115. * @param rootUrl The root url of the assets the material depends upon
  110116. * @returns the instantiated BackgroundMaterial.
  110117. */
  110118. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  110119. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  110120. };
  110121. /**
  110122. * Standard reflectance value at parallel view angle.
  110123. */
  110124. BackgroundMaterial.StandardReflectance0 = 0.05;
  110125. /**
  110126. * Standard reflectance value at grazing angle.
  110127. */
  110128. BackgroundMaterial.StandardReflectance90 = 0.5;
  110129. __decorate([
  110130. BABYLON.serializeAsColor3()
  110131. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  110132. __decorate([
  110133. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  110134. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  110135. __decorate([
  110136. BABYLON.serializeAsColor3()
  110137. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  110138. __decorate([
  110139. BABYLON.serialize()
  110140. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  110141. __decorate([
  110142. BABYLON.serialize()
  110143. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  110144. __decorate([
  110145. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  110146. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  110147. __decorate([
  110148. BABYLON.serializeAsTexture()
  110149. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  110150. __decorate([
  110151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110152. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  110153. __decorate([
  110154. BABYLON.serialize()
  110155. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  110156. __decorate([
  110157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110158. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  110159. __decorate([
  110160. BABYLON.serializeAsTexture()
  110161. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  110162. __decorate([
  110163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110164. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  110165. __decorate([
  110166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110167. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  110168. __decorate([
  110169. BABYLON.serialize()
  110170. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  110171. __decorate([
  110172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110173. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  110174. __decorate([
  110175. BABYLON.serializeAsVector3()
  110176. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  110177. __decorate([
  110178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110179. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  110180. __decorate([
  110181. BABYLON.serialize()
  110182. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  110183. __decorate([
  110184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110185. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  110186. __decorate([
  110187. BABYLON.serialize()
  110188. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  110189. __decorate([
  110190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110191. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  110192. __decorate([
  110193. BABYLON.serialize()
  110194. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  110195. __decorate([
  110196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110197. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  110198. __decorate([
  110199. BABYLON.serialize()
  110200. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  110201. __decorate([
  110202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110203. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  110204. __decorate([
  110205. BABYLON.serialize()
  110206. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  110207. __decorate([
  110208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110209. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  110210. __decorate([
  110211. BABYLON.serialize()
  110212. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  110213. __decorate([
  110214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110215. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  110216. __decorate([
  110217. BABYLON.serialize()
  110218. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  110219. __decorate([
  110220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110221. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  110222. __decorate([
  110223. BABYLON.serialize()
  110224. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  110225. __decorate([
  110226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110227. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  110228. __decorate([
  110229. BABYLON.serialize()
  110230. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  110231. __decorate([
  110232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110233. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  110234. __decorate([
  110235. BABYLON.serializeAsImageProcessingConfiguration()
  110236. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  110237. return BackgroundMaterial;
  110238. }(BABYLON.PushMaterial));
  110239. BABYLON.BackgroundMaterial = BackgroundMaterial;
  110240. })(BABYLON || (BABYLON = {}));
  110241. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  110242. var __assign = (this && this.__assign) || function () {
  110243. __assign = Object.assign || function(t) {
  110244. for (var s, i = 1, n = arguments.length; i < n; i++) {
  110245. s = arguments[i];
  110246. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  110247. t[p] = s[p];
  110248. }
  110249. return t;
  110250. };
  110251. return __assign.apply(this, arguments);
  110252. };
  110253. var BABYLON;
  110254. (function (BABYLON) {
  110255. /**
  110256. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  110257. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  110258. * It also helps with the default setup of your imageProcessing configuration.
  110259. */
  110260. var EnvironmentHelper = /** @class */ (function () {
  110261. /**
  110262. * constructor
  110263. * @param options
  110264. * @param scene The scene to add the material to
  110265. */
  110266. function EnvironmentHelper(options, scene) {
  110267. var _this = this;
  110268. this._errorHandler = function (message, exception) {
  110269. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  110270. };
  110271. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  110272. this._scene = scene;
  110273. this.onErrorObservable = new BABYLON.Observable();
  110274. this._setupBackground();
  110275. this._setupImageProcessing();
  110276. }
  110277. /**
  110278. * Creates the default options for the helper.
  110279. */
  110280. EnvironmentHelper._getDefaultOptions = function () {
  110281. return {
  110282. createGround: true,
  110283. groundSize: 15,
  110284. groundTexture: this._groundTextureCDNUrl,
  110285. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  110286. groundOpacity: 0.9,
  110287. enableGroundShadow: true,
  110288. groundShadowLevel: 0.5,
  110289. enableGroundMirror: false,
  110290. groundMirrorSizeRatio: 0.3,
  110291. groundMirrorBlurKernel: 64,
  110292. groundMirrorAmount: 1,
  110293. groundMirrorFresnelWeight: 1,
  110294. groundMirrorFallOffDistance: 0,
  110295. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  110296. groundYBias: 0.00001,
  110297. createSkybox: true,
  110298. skyboxSize: 20,
  110299. skyboxTexture: this._skyboxTextureCDNUrl,
  110300. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  110301. backgroundYRotation: 0,
  110302. sizeAuto: true,
  110303. rootPosition: BABYLON.Vector3.Zero(),
  110304. setupImageProcessing: true,
  110305. environmentTexture: this._environmentTextureCDNUrl,
  110306. cameraExposure: 0.8,
  110307. cameraContrast: 1.2,
  110308. toneMappingEnabled: true,
  110309. };
  110310. };
  110311. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  110312. /**
  110313. * Gets the root mesh created by the helper.
  110314. */
  110315. get: function () {
  110316. return this._rootMesh;
  110317. },
  110318. enumerable: true,
  110319. configurable: true
  110320. });
  110321. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  110322. /**
  110323. * Gets the skybox created by the helper.
  110324. */
  110325. get: function () {
  110326. return this._skybox;
  110327. },
  110328. enumerable: true,
  110329. configurable: true
  110330. });
  110331. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  110332. /**
  110333. * Gets the skybox texture created by the helper.
  110334. */
  110335. get: function () {
  110336. return this._skyboxTexture;
  110337. },
  110338. enumerable: true,
  110339. configurable: true
  110340. });
  110341. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  110342. /**
  110343. * Gets the skybox material created by the helper.
  110344. */
  110345. get: function () {
  110346. return this._skyboxMaterial;
  110347. },
  110348. enumerable: true,
  110349. configurable: true
  110350. });
  110351. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  110352. /**
  110353. * Gets the ground mesh created by the helper.
  110354. */
  110355. get: function () {
  110356. return this._ground;
  110357. },
  110358. enumerable: true,
  110359. configurable: true
  110360. });
  110361. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  110362. /**
  110363. * Gets the ground texture created by the helper.
  110364. */
  110365. get: function () {
  110366. return this._groundTexture;
  110367. },
  110368. enumerable: true,
  110369. configurable: true
  110370. });
  110371. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  110372. /**
  110373. * Gets the ground mirror created by the helper.
  110374. */
  110375. get: function () {
  110376. return this._groundMirror;
  110377. },
  110378. enumerable: true,
  110379. configurable: true
  110380. });
  110381. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  110382. /**
  110383. * Gets the ground mirror render list to helps pushing the meshes
  110384. * you wish in the ground reflection.
  110385. */
  110386. get: function () {
  110387. if (this._groundMirror) {
  110388. return this._groundMirror.renderList;
  110389. }
  110390. return null;
  110391. },
  110392. enumerable: true,
  110393. configurable: true
  110394. });
  110395. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  110396. /**
  110397. * Gets the ground material created by the helper.
  110398. */
  110399. get: function () {
  110400. return this._groundMaterial;
  110401. },
  110402. enumerable: true,
  110403. configurable: true
  110404. });
  110405. /**
  110406. * Updates the background according to the new options
  110407. * @param options
  110408. */
  110409. EnvironmentHelper.prototype.updateOptions = function (options) {
  110410. var newOptions = __assign({}, this._options, options);
  110411. if (this._ground && !newOptions.createGround) {
  110412. this._ground.dispose();
  110413. this._ground = null;
  110414. }
  110415. if (this._groundMaterial && !newOptions.createGround) {
  110416. this._groundMaterial.dispose();
  110417. this._groundMaterial = null;
  110418. }
  110419. if (this._groundTexture) {
  110420. if (this._options.groundTexture != newOptions.groundTexture) {
  110421. this._groundTexture.dispose();
  110422. this._groundTexture = null;
  110423. }
  110424. }
  110425. if (this._skybox && !newOptions.createSkybox) {
  110426. this._skybox.dispose();
  110427. this._skybox = null;
  110428. }
  110429. if (this._skyboxMaterial && !newOptions.createSkybox) {
  110430. this._skyboxMaterial.dispose();
  110431. this._skyboxMaterial = null;
  110432. }
  110433. if (this._skyboxTexture) {
  110434. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  110435. this._skyboxTexture.dispose();
  110436. this._skyboxTexture = null;
  110437. }
  110438. }
  110439. if (this._groundMirror && !newOptions.enableGroundMirror) {
  110440. this._groundMirror.dispose();
  110441. this._groundMirror = null;
  110442. }
  110443. if (this._scene.environmentTexture) {
  110444. if (this._options.environmentTexture != newOptions.environmentTexture) {
  110445. this._scene.environmentTexture.dispose();
  110446. }
  110447. }
  110448. this._options = newOptions;
  110449. this._setupBackground();
  110450. this._setupImageProcessing();
  110451. };
  110452. /**
  110453. * Sets the primary color of all the available elements.
  110454. * @param color the main color to affect to the ground and the background
  110455. */
  110456. EnvironmentHelper.prototype.setMainColor = function (color) {
  110457. if (this.groundMaterial) {
  110458. this.groundMaterial.primaryColor = color;
  110459. }
  110460. if (this.skyboxMaterial) {
  110461. this.skyboxMaterial.primaryColor = color;
  110462. }
  110463. if (this.groundMirror) {
  110464. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  110465. }
  110466. };
  110467. /**
  110468. * Setup the image processing according to the specified options.
  110469. */
  110470. EnvironmentHelper.prototype._setupImageProcessing = function () {
  110471. if (this._options.setupImageProcessing) {
  110472. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  110473. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  110474. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  110475. this._setupEnvironmentTexture();
  110476. }
  110477. };
  110478. /**
  110479. * Setup the environment texture according to the specified options.
  110480. */
  110481. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  110482. if (this._scene.environmentTexture) {
  110483. return;
  110484. }
  110485. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  110486. this._scene.environmentTexture = this._options.environmentTexture;
  110487. return;
  110488. }
  110489. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  110490. this._scene.environmentTexture = environmentTexture;
  110491. };
  110492. /**
  110493. * Setup the background according to the specified options.
  110494. */
  110495. EnvironmentHelper.prototype._setupBackground = function () {
  110496. if (!this._rootMesh) {
  110497. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  110498. }
  110499. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  110500. var sceneSize = this._getSceneSize();
  110501. if (this._options.createGround) {
  110502. this._setupGround(sceneSize);
  110503. this._setupGroundMaterial();
  110504. this._setupGroundDiffuseTexture();
  110505. if (this._options.enableGroundMirror) {
  110506. this._setupGroundMirrorTexture(sceneSize);
  110507. }
  110508. this._setupMirrorInGroundMaterial();
  110509. }
  110510. if (this._options.createSkybox) {
  110511. this._setupSkybox(sceneSize);
  110512. this._setupSkyboxMaterial();
  110513. this._setupSkyboxReflectionTexture();
  110514. }
  110515. this._rootMesh.position.x = sceneSize.rootPosition.x;
  110516. this._rootMesh.position.z = sceneSize.rootPosition.z;
  110517. this._rootMesh.position.y = sceneSize.rootPosition.y;
  110518. };
  110519. /**
  110520. * Get the scene sizes according to the setup.
  110521. */
  110522. EnvironmentHelper.prototype._getSceneSize = function () {
  110523. var _this = this;
  110524. var groundSize = this._options.groundSize;
  110525. var skyboxSize = this._options.skyboxSize;
  110526. var rootPosition = this._options.rootPosition;
  110527. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  110528. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  110529. }
  110530. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  110531. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  110532. });
  110533. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  110534. if (this._options.sizeAuto) {
  110535. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  110536. this._scene.activeCamera.upperRadiusLimit) {
  110537. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  110538. skyboxSize = groundSize;
  110539. }
  110540. var sceneDiagonalLenght = sceneDiagonal.length();
  110541. if (sceneDiagonalLenght > groundSize) {
  110542. groundSize = sceneDiagonalLenght * 2;
  110543. skyboxSize = groundSize;
  110544. }
  110545. // 10 % bigger.
  110546. groundSize *= 1.1;
  110547. skyboxSize *= 1.5;
  110548. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  110549. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  110550. }
  110551. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  110552. };
  110553. /**
  110554. * Setup the ground according to the specified options.
  110555. */
  110556. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  110557. var _this = this;
  110558. if (!this._ground || this._ground.isDisposed()) {
  110559. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  110560. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  110561. this._ground.parent = this._rootMesh;
  110562. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  110563. }
  110564. this._ground.receiveShadows = this._options.enableGroundShadow;
  110565. };
  110566. /**
  110567. * Setup the ground material according to the specified options.
  110568. */
  110569. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  110570. if (!this._groundMaterial) {
  110571. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  110572. }
  110573. this._groundMaterial.alpha = this._options.groundOpacity;
  110574. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  110575. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  110576. this._groundMaterial.primaryColor = this._options.groundColor;
  110577. this._groundMaterial.useRGBColor = false;
  110578. this._groundMaterial.enableNoise = true;
  110579. if (this._ground) {
  110580. this._ground.material = this._groundMaterial;
  110581. }
  110582. };
  110583. /**
  110584. * Setup the ground diffuse texture according to the specified options.
  110585. */
  110586. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  110587. if (!this._groundMaterial) {
  110588. return;
  110589. }
  110590. if (this._groundTexture) {
  110591. return;
  110592. }
  110593. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  110594. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  110595. return;
  110596. }
  110597. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  110598. diffuseTexture.gammaSpace = false;
  110599. diffuseTexture.hasAlpha = true;
  110600. this._groundMaterial.diffuseTexture = diffuseTexture;
  110601. };
  110602. /**
  110603. * Setup the ground mirror texture according to the specified options.
  110604. */
  110605. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  110606. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110607. if (!this._groundMirror) {
  110608. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  110609. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  110610. this._groundMirror.anisotropicFilteringLevel = 1;
  110611. this._groundMirror.wrapU = wrapping;
  110612. this._groundMirror.wrapV = wrapping;
  110613. this._groundMirror.gammaSpace = false;
  110614. if (this._groundMirror.renderList) {
  110615. for (var i = 0; i < this._scene.meshes.length; i++) {
  110616. var mesh = this._scene.meshes[i];
  110617. if (mesh !== this._ground &&
  110618. mesh !== this._skybox &&
  110619. mesh !== this._rootMesh) {
  110620. this._groundMirror.renderList.push(mesh);
  110621. }
  110622. }
  110623. }
  110624. }
  110625. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  110626. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  110627. };
  110628. /**
  110629. * Setup the ground to receive the mirror texture.
  110630. */
  110631. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  110632. if (this._groundMaterial) {
  110633. this._groundMaterial.reflectionTexture = this._groundMirror;
  110634. this._groundMaterial.reflectionFresnel = true;
  110635. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  110636. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  110637. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  110638. }
  110639. };
  110640. /**
  110641. * Setup the skybox according to the specified options.
  110642. */
  110643. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  110644. var _this = this;
  110645. if (!this._skybox || this._skybox.isDisposed()) {
  110646. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  110647. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  110648. }
  110649. this._skybox.parent = this._rootMesh;
  110650. };
  110651. /**
  110652. * Setup the skybox material according to the specified options.
  110653. */
  110654. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  110655. if (!this._skybox) {
  110656. return;
  110657. }
  110658. if (!this._skyboxMaterial) {
  110659. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  110660. }
  110661. this._skyboxMaterial.useRGBColor = false;
  110662. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  110663. this._skyboxMaterial.enableNoise = true;
  110664. this._skybox.material = this._skyboxMaterial;
  110665. };
  110666. /**
  110667. * Setup the skybox reflection texture according to the specified options.
  110668. */
  110669. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  110670. if (!this._skyboxMaterial) {
  110671. return;
  110672. }
  110673. if (this._skyboxTexture) {
  110674. return;
  110675. }
  110676. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  110677. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  110678. return;
  110679. }
  110680. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  110681. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  110682. this._skyboxTexture.gammaSpace = false;
  110683. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  110684. };
  110685. /**
  110686. * Dispose all the elements created by the Helper.
  110687. */
  110688. EnvironmentHelper.prototype.dispose = function () {
  110689. if (this._groundMaterial) {
  110690. this._groundMaterial.dispose(true, true);
  110691. }
  110692. if (this._skyboxMaterial) {
  110693. this._skyboxMaterial.dispose(true, true);
  110694. }
  110695. this._rootMesh.dispose(false);
  110696. };
  110697. /**
  110698. * Default ground texture URL.
  110699. */
  110700. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  110701. /**
  110702. * Default skybox texture URL.
  110703. */
  110704. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  110705. /**
  110706. * Default environment texture URL.
  110707. */
  110708. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  110709. return EnvironmentHelper;
  110710. }());
  110711. BABYLON.EnvironmentHelper = EnvironmentHelper;
  110712. })(BABYLON || (BABYLON = {}));
  110713. //# sourceMappingURL=babylon.environmentHelper.js.map
  110714. var BABYLON;
  110715. (function (BABYLON) {
  110716. /** Internal class used to store shapes for emitters */
  110717. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  110718. function ParticleSystemSetEmitterCreationOptions() {
  110719. }
  110720. return ParticleSystemSetEmitterCreationOptions;
  110721. }());
  110722. /**
  110723. * Represents a set of particle systems working together to create a specific effect
  110724. */
  110725. var ParticleSystemSet = /** @class */ (function () {
  110726. function ParticleSystemSet() {
  110727. /**
  110728. * Gets the particle system list
  110729. */
  110730. this.systems = new Array();
  110731. }
  110732. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  110733. /**
  110734. * Gets the emitter node used with this set
  110735. */
  110736. get: function () {
  110737. return this._emitterNode;
  110738. },
  110739. enumerable: true,
  110740. configurable: true
  110741. });
  110742. /**
  110743. * Creates a new emitter mesh as a sphere
  110744. * @param options defines the options used to create the sphere
  110745. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  110746. * @param scene defines the hosting scene
  110747. */
  110748. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  110749. if (this._emitterNode) {
  110750. this._emitterNode.dispose();
  110751. }
  110752. this._emitterCreationOptions = {
  110753. kind: "Sphere",
  110754. options: options,
  110755. renderingGroupId: renderingGroupId
  110756. };
  110757. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  110758. emitterMesh.renderingGroupId = renderingGroupId;
  110759. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  110760. material.emissiveColor = options.color;
  110761. emitterMesh.material = material;
  110762. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  110763. var system = _a[_i];
  110764. system.emitter = emitterMesh;
  110765. }
  110766. this._emitterNode = emitterMesh;
  110767. };
  110768. /**
  110769. * Starts all particle systems of the set
  110770. * @param emitter defines an optional mesh to use as emitter for the particle systems
  110771. */
  110772. ParticleSystemSet.prototype.start = function (emitter) {
  110773. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  110774. var system = _a[_i];
  110775. if (emitter) {
  110776. system.emitter = emitter;
  110777. }
  110778. system.start();
  110779. }
  110780. };
  110781. /**
  110782. * Release all associated resources
  110783. */
  110784. ParticleSystemSet.prototype.dispose = function () {
  110785. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  110786. var system = _a[_i];
  110787. system.dispose();
  110788. }
  110789. this.systems = [];
  110790. if (this._emitterNode) {
  110791. this._emitterNode.dispose();
  110792. this._emitterNode = null;
  110793. }
  110794. };
  110795. /**
  110796. * Serialize the set into a JSON compatible object
  110797. * @returns a JSON compatible representation of the set
  110798. */
  110799. ParticleSystemSet.prototype.serialize = function () {
  110800. var result = {};
  110801. result.systems = [];
  110802. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  110803. var system = _a[_i];
  110804. result.systems.push(system.serialize());
  110805. }
  110806. if (this._emitterNode) {
  110807. result.emitter = this._emitterCreationOptions;
  110808. }
  110809. return result;
  110810. };
  110811. /**
  110812. * Parse a new ParticleSystemSet from a serialized source
  110813. * @param data defines a JSON compatible representation of the set
  110814. * @param scene defines the hosting scene
  110815. * @param gpu defines if we want GPU particles or CPU particles
  110816. * @returns a new ParticleSystemSet
  110817. */
  110818. ParticleSystemSet.Parse = function (data, scene, gpu) {
  110819. if (gpu === void 0) { gpu = false; }
  110820. var result = new ParticleSystemSet();
  110821. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  110822. scene = scene || BABYLON.Engine.LastCreatedScene;
  110823. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  110824. var system = _a[_i];
  110825. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  110826. }
  110827. if (data.emitter) {
  110828. var options = data.emitter.options;
  110829. switch (data.emitter.kind) {
  110830. case "Sphere":
  110831. result.setEmitterAsSphere({
  110832. diameter: options.diameter,
  110833. segments: options.segments,
  110834. color: BABYLON.Color3.FromArray(options.color)
  110835. }, data.emitter.renderingGroupId, scene);
  110836. break;
  110837. }
  110838. }
  110839. return result;
  110840. };
  110841. return ParticleSystemSet;
  110842. }());
  110843. BABYLON.ParticleSystemSet = ParticleSystemSet;
  110844. })(BABYLON || (BABYLON = {}));
  110845. //# sourceMappingURL=babylon.particleSystemSet.js.map
  110846. var BABYLON;
  110847. (function (BABYLON) {
  110848. /**
  110849. * This class is made for on one-liner static method to help creating particle system set.
  110850. */
  110851. var ParticleHelper = /** @class */ (function () {
  110852. function ParticleHelper() {
  110853. }
  110854. /**
  110855. * Create a default particle system that you can tweak
  110856. * @param emitter defines the emitter to use
  110857. * @param capacity defines the system capacity (default is 500 particles)
  110858. * @param scene defines the hosting scene
  110859. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  110860. * @returns the new Particle system
  110861. */
  110862. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  110863. if (capacity === void 0) { capacity = 500; }
  110864. if (useGPU === void 0) { useGPU = false; }
  110865. var system;
  110866. if (useGPU) {
  110867. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  110868. }
  110869. else {
  110870. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  110871. }
  110872. system.emitter = emitter;
  110873. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  110874. system.createConeEmitter(0.1, Math.PI / 4);
  110875. // Particle color
  110876. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  110877. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  110878. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  110879. // Particle Size
  110880. system.minSize = 0.1;
  110881. system.maxSize = 0.1;
  110882. // Emission speed
  110883. system.minEmitPower = 2;
  110884. system.maxEmitPower = 2;
  110885. // Update speed
  110886. system.updateSpeed = 1 / 60;
  110887. system.emitRate = 30;
  110888. return system;
  110889. };
  110890. /**
  110891. * This is the main static method (one-liner) of this helper to create different particle systems
  110892. * @param type This string represents the type to the particle system to create
  110893. * @param scene The scene where the particle system should live
  110894. * @param gpu If the system will use gpu
  110895. * @returns the ParticleSystemSet created
  110896. */
  110897. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  110898. if (gpu === void 0) { gpu = false; }
  110899. if (!scene) {
  110900. scene = BABYLON.Engine.LastCreatedScene;
  110901. ;
  110902. }
  110903. var token = {};
  110904. scene._addPendingData(token);
  110905. return new Promise(function (resolve, reject) {
  110906. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  110907. scene._removePendingData(token);
  110908. return reject("Particle system with GPU is not supported.");
  110909. }
  110910. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  110911. scene._removePendingData(token);
  110912. var newData = JSON.parse(data.toString());
  110913. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  110914. }, undefined, undefined, undefined, function (req, exception) {
  110915. scene._removePendingData(token);
  110916. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  110917. });
  110918. });
  110919. };
  110920. /**
  110921. * Static function used to export a particle system to a ParticleSystemSet variable.
  110922. * Please note that the emitter shape is not exported
  110923. * @param system defines the particle systems to export
  110924. */
  110925. ParticleHelper.ExportSet = function (systems) {
  110926. var set = new BABYLON.ParticleSystemSet();
  110927. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  110928. var system = systems_1[_i];
  110929. set.systems.push(system);
  110930. }
  110931. return set;
  110932. };
  110933. /**
  110934. * Gets or sets base Assets URL
  110935. */
  110936. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  110937. return ParticleHelper;
  110938. }());
  110939. BABYLON.ParticleHelper = ParticleHelper;
  110940. })(BABYLON || (BABYLON = {}));
  110941. //# sourceMappingURL=babylon.particleHelper.js.map
  110942. var BABYLON;
  110943. (function (BABYLON) {
  110944. /**
  110945. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  110946. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  110947. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  110948. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  110949. */
  110950. var VideoDome = /** @class */ (function (_super) {
  110951. __extends(VideoDome, _super);
  110952. /**
  110953. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  110954. * @param name Element's name, child elements will append suffixes for their own names.
  110955. * @param urlsOrVideo defines the url(s) or the video element to use
  110956. * @param options An object containing optional or exposed sub element properties
  110957. */
  110958. function VideoDome(name, urlsOrVideo, options, scene) {
  110959. var _this = _super.call(this, name, scene) || this;
  110960. _this._useDirectMapping = false;
  110961. // set defaults and manage values
  110962. name = name || "videoDome";
  110963. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  110964. options.clickToPlay = Boolean(options.clickToPlay);
  110965. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  110966. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  110967. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  110968. if (options.useDirectMapping === undefined) {
  110969. _this._useDirectMapping = true;
  110970. }
  110971. else {
  110972. _this._useDirectMapping = options.useDirectMapping;
  110973. }
  110974. _this._setReady(false);
  110975. // create
  110976. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  110977. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  110978. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  110979. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  110980. texture.onLoadObservable.addOnce(function () {
  110981. _this._setReady(true);
  110982. });
  110983. // configure material
  110984. material.useEquirectangularFOV = true;
  110985. material.fovMultiplier = 1.0;
  110986. material.opacityFresnel = false;
  110987. if (_this._useDirectMapping) {
  110988. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110989. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110990. material.diffuseTexture = texture;
  110991. }
  110992. else {
  110993. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  110994. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110995. material.reflectionTexture = texture;
  110996. }
  110997. // configure mesh
  110998. _this._mesh.material = material;
  110999. _this._mesh.parent = _this;
  111000. // optional configuration
  111001. if (options.clickToPlay) {
  111002. scene.onPointerUp = function () {
  111003. _this._videoTexture.video.play();
  111004. };
  111005. }
  111006. return _this;
  111007. }
  111008. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  111009. /**
  111010. * Gets the video texture being displayed on the sphere
  111011. */
  111012. get: function () {
  111013. return this._videoTexture;
  111014. },
  111015. enumerable: true,
  111016. configurable: true
  111017. });
  111018. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  111019. /**
  111020. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111021. * Also see the options.resolution property.
  111022. */
  111023. get: function () {
  111024. return this._material.fovMultiplier;
  111025. },
  111026. set: function (value) {
  111027. this._material.fovMultiplier = value;
  111028. },
  111029. enumerable: true,
  111030. configurable: true
  111031. });
  111032. /**
  111033. * Releases resources associated with this node.
  111034. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  111035. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  111036. */
  111037. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  111038. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  111039. this._videoTexture.dispose();
  111040. this._mesh.dispose();
  111041. this._material.dispose();
  111042. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  111043. };
  111044. return VideoDome;
  111045. }(BABYLON.TransformNode));
  111046. BABYLON.VideoDome = VideoDome;
  111047. })(BABYLON || (BABYLON = {}));
  111048. //# sourceMappingURL=babylon.videoDome.js.map
  111049. var BABYLON;
  111050. (function (BABYLON) {
  111051. /**
  111052. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  111053. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  111054. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  111055. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  111056. */
  111057. var PhotoDome = /** @class */ (function (_super) {
  111058. __extends(PhotoDome, _super);
  111059. /**
  111060. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  111061. * @param name Element's name, child elements will append suffixes for their own names.
  111062. * @param urlsOfPhoto defines the url of the photo to display
  111063. * @param options defines an object containing optional or exposed sub element properties
  111064. * @param onError defines a callback called when an error occured while loading the texture
  111065. */
  111066. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  111067. if (onError === void 0) { onError = null; }
  111068. var _this = _super.call(this, name, scene) || this;
  111069. _this._useDirectMapping = false;
  111070. /**
  111071. * Observable raised when an error occured while loading the 360 image
  111072. */
  111073. _this.onLoadErrorObservable = new BABYLON.Observable();
  111074. // set defaults and manage values
  111075. name = name || "photoDome";
  111076. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  111077. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  111078. if (options.useDirectMapping === undefined) {
  111079. _this._useDirectMapping = true;
  111080. }
  111081. else {
  111082. _this._useDirectMapping = options.useDirectMapping;
  111083. }
  111084. _this._setReady(false);
  111085. // create
  111086. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  111087. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  111088. // configure material
  111089. material.opacityFresnel = false;
  111090. material.useEquirectangularFOV = true;
  111091. material.fovMultiplier = 1.0;
  111092. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  111093. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  111094. if (onError) {
  111095. onError(message, exception);
  111096. }
  111097. });
  111098. _this.photoTexture.onLoadObservable.addOnce(function () {
  111099. _this._setReady(true);
  111100. });
  111101. // configure mesh
  111102. _this._mesh.material = material;
  111103. _this._mesh.parent = _this;
  111104. return _this;
  111105. }
  111106. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  111107. /**
  111108. * Gets or sets the texture being displayed on the sphere
  111109. */
  111110. get: function () {
  111111. return this._photoTexture;
  111112. },
  111113. set: function (value) {
  111114. if (this._photoTexture === value) {
  111115. return;
  111116. }
  111117. this._photoTexture = value;
  111118. if (this._useDirectMapping) {
  111119. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111120. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111121. this._material.diffuseTexture = this._photoTexture;
  111122. }
  111123. else {
  111124. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  111125. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111126. this._material.reflectionTexture = this._photoTexture;
  111127. }
  111128. },
  111129. enumerable: true,
  111130. configurable: true
  111131. });
  111132. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  111133. /**
  111134. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111135. * Also see the options.resolution property.
  111136. */
  111137. get: function () {
  111138. return this._material.fovMultiplier;
  111139. },
  111140. set: function (value) {
  111141. this._material.fovMultiplier = value;
  111142. },
  111143. enumerable: true,
  111144. configurable: true
  111145. });
  111146. /**
  111147. * Releases resources associated with this node.
  111148. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  111149. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  111150. */
  111151. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  111152. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  111153. this._photoTexture.dispose();
  111154. this._mesh.dispose();
  111155. this._material.dispose();
  111156. this.onLoadErrorObservable.clear();
  111157. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  111158. };
  111159. return PhotoDome;
  111160. }(BABYLON.TransformNode));
  111161. BABYLON.PhotoDome = PhotoDome;
  111162. })(BABYLON || (BABYLON = {}));
  111163. //# sourceMappingURL=babylon.photoDome.js.map
  111164. var BABYLON;
  111165. (function (BABYLON) {
  111166. BABYLON.Engine.prototype.createQuery = function () {
  111167. return this._gl.createQuery();
  111168. };
  111169. BABYLON.Engine.prototype.deleteQuery = function (query) {
  111170. this._gl.deleteQuery(query);
  111171. return this;
  111172. };
  111173. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  111174. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  111175. };
  111176. BABYLON.Engine.prototype.getQueryResult = function (query) {
  111177. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  111178. };
  111179. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  111180. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  111181. this._gl.beginQuery(glAlgorithm, query);
  111182. return this;
  111183. };
  111184. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  111185. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  111186. this._gl.endQuery(glAlgorithm);
  111187. return this;
  111188. };
  111189. BABYLON.Engine.prototype._createTimeQuery = function () {
  111190. var timerQuery = this.getCaps().timerQuery;
  111191. if (timerQuery.createQueryEXT) {
  111192. return timerQuery.createQueryEXT();
  111193. }
  111194. return this.createQuery();
  111195. };
  111196. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  111197. var timerQuery = this.getCaps().timerQuery;
  111198. if (timerQuery.deleteQueryEXT) {
  111199. timerQuery.deleteQueryEXT(query);
  111200. return;
  111201. }
  111202. this.deleteQuery(query);
  111203. };
  111204. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  111205. var timerQuery = this.getCaps().timerQuery;
  111206. if (timerQuery.getQueryObjectEXT) {
  111207. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  111208. }
  111209. return this.getQueryResult(query);
  111210. };
  111211. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  111212. var timerQuery = this.getCaps().timerQuery;
  111213. if (timerQuery.getQueryObjectEXT) {
  111214. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  111215. }
  111216. return this.isQueryResultAvailable(query);
  111217. };
  111218. BABYLON.Engine.prototype.startTimeQuery = function () {
  111219. var caps = this.getCaps();
  111220. var timerQuery = caps.timerQuery;
  111221. if (!timerQuery) {
  111222. return null;
  111223. }
  111224. var token = new BABYLON._TimeToken();
  111225. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  111226. if (caps.canUseTimestampForTimerQuery) {
  111227. token._startTimeQuery = this._createTimeQuery();
  111228. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  111229. }
  111230. else {
  111231. if (this._currentNonTimestampToken) {
  111232. return this._currentNonTimestampToken;
  111233. }
  111234. token._timeElapsedQuery = this._createTimeQuery();
  111235. if (timerQuery.beginQueryEXT) {
  111236. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  111237. }
  111238. else {
  111239. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  111240. }
  111241. this._currentNonTimestampToken = token;
  111242. }
  111243. return token;
  111244. };
  111245. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  111246. var caps = this.getCaps();
  111247. var timerQuery = caps.timerQuery;
  111248. if (!timerQuery || !token) {
  111249. return -1;
  111250. }
  111251. if (caps.canUseTimestampForTimerQuery) {
  111252. if (!token._startTimeQuery) {
  111253. return -1;
  111254. }
  111255. if (!token._endTimeQuery) {
  111256. token._endTimeQuery = this._createTimeQuery();
  111257. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  111258. }
  111259. }
  111260. else if (!token._timeElapsedQueryEnded) {
  111261. if (!token._timeElapsedQuery) {
  111262. return -1;
  111263. }
  111264. if (timerQuery.endQueryEXT) {
  111265. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  111266. }
  111267. else {
  111268. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  111269. }
  111270. token._timeElapsedQueryEnded = true;
  111271. }
  111272. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  111273. var available = false;
  111274. if (token._endTimeQuery) {
  111275. available = this._getTimeQueryAvailability(token._endTimeQuery);
  111276. }
  111277. else if (token._timeElapsedQuery) {
  111278. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  111279. }
  111280. if (available && !disjoint) {
  111281. var result = 0;
  111282. if (caps.canUseTimestampForTimerQuery) {
  111283. if (!token._startTimeQuery || !token._endTimeQuery) {
  111284. return -1;
  111285. }
  111286. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  111287. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  111288. result = timeEnd - timeStart;
  111289. this._deleteTimeQuery(token._startTimeQuery);
  111290. this._deleteTimeQuery(token._endTimeQuery);
  111291. token._startTimeQuery = null;
  111292. token._endTimeQuery = null;
  111293. }
  111294. else {
  111295. if (!token._timeElapsedQuery) {
  111296. return -1;
  111297. }
  111298. result = this._getTimeQueryResult(token._timeElapsedQuery);
  111299. this._deleteTimeQuery(token._timeElapsedQuery);
  111300. token._timeElapsedQuery = null;
  111301. token._timeElapsedQueryEnded = false;
  111302. this._currentNonTimestampToken = null;
  111303. }
  111304. return result;
  111305. }
  111306. return -1;
  111307. };
  111308. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  111309. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  111310. };
  111311. // We also need to update AbstractMesh as there is a portion of the code there
  111312. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  111313. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  111314. this._isOccluded = false;
  111315. return;
  111316. }
  111317. var engine = this.getEngine();
  111318. if (engine.webGLVersion < 2) {
  111319. this._isOccluded = false;
  111320. return;
  111321. }
  111322. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  111323. this._isOccluded = false;
  111324. return;
  111325. }
  111326. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  111327. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  111328. if (isOcclusionQueryAvailable) {
  111329. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  111330. this._isOcclusionQueryInProgress = false;
  111331. this._occlusionInternalRetryCounter = 0;
  111332. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  111333. }
  111334. else {
  111335. this._occlusionInternalRetryCounter++;
  111336. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  111337. this._isOcclusionQueryInProgress = false;
  111338. this._occlusionInternalRetryCounter = 0;
  111339. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  111340. // if strict continue the last state of the object.
  111341. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  111342. }
  111343. else {
  111344. return;
  111345. }
  111346. }
  111347. }
  111348. var scene = this.getScene();
  111349. if (scene.getBoundingBoxRenderer) {
  111350. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  111351. if (!this._occlusionQuery) {
  111352. this._occlusionQuery = engine.createQuery();
  111353. }
  111354. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  111355. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  111356. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  111357. this._isOcclusionQueryInProgress = true;
  111358. }
  111359. };
  111360. })(BABYLON || (BABYLON = {}));
  111361. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  111362. var BABYLON;
  111363. (function (BABYLON) {
  111364. /**
  111365. * Class used to generate noise procedural textures
  111366. */
  111367. var NoiseProceduralTexture = /** @class */ (function (_super) {
  111368. __extends(NoiseProceduralTexture, _super);
  111369. /**
  111370. * Creates a new NoiseProceduralTexture
  111371. * @param name defines the name fo the texture
  111372. * @param size defines the size of the texture (default is 256)
  111373. * @param scene defines the hosting scene
  111374. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  111375. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  111376. */
  111377. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  111378. if (size === void 0) { size = 256; }
  111379. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  111380. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  111381. _this._time = 0;
  111382. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  111383. _this.brightness = 0.2;
  111384. /** Defines the number of octaves to process */
  111385. _this.octaves = 3;
  111386. /** Defines the level of persistence (0.8 by default) */
  111387. _this.persistence = 0.8;
  111388. /** Gets or sets animation speed factor (default is 1) */
  111389. _this.animationSpeedFactor = 1;
  111390. _this._updateShaderUniforms();
  111391. return _this;
  111392. }
  111393. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  111394. var scene = this.getScene();
  111395. if (!scene) {
  111396. return;
  111397. }
  111398. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  111399. this.setFloat("brightness", this.brightness);
  111400. this.setFloat("persistence", this.persistence);
  111401. this.setFloat("timeScale", this._time);
  111402. };
  111403. NoiseProceduralTexture.prototype._getDefines = function () {
  111404. return "#define OCTAVES " + (this.octaves | 0);
  111405. };
  111406. /** Generate the current state of the procedural texture */
  111407. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  111408. this._updateShaderUniforms();
  111409. _super.prototype.render.call(this, useCameraPostProcess);
  111410. };
  111411. /**
  111412. * Serializes this noise procedural texture
  111413. * @returns a serialized noise procedural texture object
  111414. */
  111415. NoiseProceduralTexture.prototype.serialize = function () {
  111416. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  111417. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  111418. return serializationObject;
  111419. };
  111420. /**
  111421. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  111422. * @param parsedTexture defines parsed texture data
  111423. * @param scene defines the current scene
  111424. * @param rootUrl defines the root URL containing noise procedural texture information
  111425. * @returns a parsed NoiseProceduralTexture
  111426. */
  111427. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  111428. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  111429. return texture;
  111430. };
  111431. return NoiseProceduralTexture;
  111432. }(BABYLON.ProceduralTexture));
  111433. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  111434. })(BABYLON || (BABYLON = {}));
  111435. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  111436. var __assign = (this && this.__assign) || function () {
  111437. __assign = Object.assign || function(t) {
  111438. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111439. s = arguments[i];
  111440. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111441. t[p] = s[p];
  111442. }
  111443. return t;
  111444. };
  111445. return __assign.apply(this, arguments);
  111446. };
  111447. var BABYLON;
  111448. (function (BABYLON) {
  111449. /**
  111450. * This can helps recording videos from BabylonJS.
  111451. * This is based on the available WebRTC functionalities of the browser.
  111452. *
  111453. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  111454. */
  111455. var VideoRecorder = /** @class */ (function () {
  111456. /**
  111457. * Create a new VideoCapture object which can help converting what you see in Babylon to
  111458. * a video file.
  111459. * @param engine Defines the BabylonJS Engine you wish to record
  111460. * @param options Defines options that can be used to customized the capture
  111461. */
  111462. function VideoRecorder(engine, options) {
  111463. if (options === void 0) { options = null; }
  111464. if (!VideoRecorder.IsSupported(engine)) {
  111465. throw "Your browser does not support recording so far.";
  111466. }
  111467. var canvas = engine.getRenderingCanvas();
  111468. if (!canvas) {
  111469. throw "The babylon engine must have a canvas to be recorded";
  111470. }
  111471. this._canvas = canvas;
  111472. this._canvas.isRecording = false;
  111473. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  111474. var stream = this._canvas.captureStream(this._options.fps);
  111475. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  111476. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  111477. this._mediaRecorder.onerror = this._handleError.bind(this);
  111478. this._mediaRecorder.onstop = this._handleStop.bind(this);
  111479. }
  111480. /**
  111481. * Returns wehther or not the VideoRecorder is available in your browser.
  111482. * @param engine Defines the Babylon Engine to check the support for
  111483. * @returns true if supported otherwise false
  111484. */
  111485. VideoRecorder.IsSupported = function (engine) {
  111486. var canvas = engine.getRenderingCanvas();
  111487. return (!!canvas && typeof canvas.captureStream === "function");
  111488. };
  111489. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  111490. /**
  111491. * True wether a recording is already in progress.
  111492. */
  111493. get: function () {
  111494. return !!this._canvas && this._canvas.isRecording;
  111495. },
  111496. enumerable: true,
  111497. configurable: true
  111498. });
  111499. /**
  111500. * Stops the current recording before the default capture timeout passed in the startRecording
  111501. * functions.
  111502. */
  111503. VideoRecorder.prototype.stopRecording = function () {
  111504. if (!this._canvas || !this._mediaRecorder) {
  111505. return;
  111506. }
  111507. if (!this.isRecording) {
  111508. return;
  111509. }
  111510. this._canvas.isRecording = false;
  111511. this._mediaRecorder.stop();
  111512. };
  111513. /**
  111514. * Starts recording the canvas for a max duration specified in parameters.
  111515. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  111516. * @param maxDuration Defines the maximum recording time in seconds.
  111517. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  111518. * @return a promise callback at the end of the recording with the video data in Blob.
  111519. */
  111520. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  111521. var _this = this;
  111522. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  111523. if (maxDuration === void 0) { maxDuration = 7; }
  111524. if (!this._canvas || !this._mediaRecorder) {
  111525. throw "Recorder has already been disposed";
  111526. }
  111527. if (this.isRecording) {
  111528. throw "Recording already in progress";
  111529. }
  111530. if (maxDuration > 0) {
  111531. setTimeout(function () {
  111532. _this.stopRecording();
  111533. }, maxDuration * 1000);
  111534. }
  111535. this._fileName = fileName;
  111536. this._recordedChunks = [];
  111537. this._resolve = null;
  111538. this._reject = null;
  111539. this._canvas.isRecording = true;
  111540. this._mediaRecorder.start(this._options.recordChunckSize);
  111541. return new Promise(function (resolve, reject) {
  111542. _this._resolve = resolve;
  111543. _this._reject = reject;
  111544. });
  111545. };
  111546. /**
  111547. * Releases internal resources used during the recording.
  111548. */
  111549. VideoRecorder.prototype.dispose = function () {
  111550. this._canvas = null;
  111551. this._mediaRecorder = null;
  111552. this._recordedChunks = [];
  111553. this._fileName = null;
  111554. this._resolve = null;
  111555. this._reject = null;
  111556. };
  111557. VideoRecorder.prototype._handleDataAvailable = function (event) {
  111558. if (event.data.size > 0) {
  111559. this._recordedChunks.push(event.data);
  111560. }
  111561. };
  111562. VideoRecorder.prototype._handleError = function (event) {
  111563. this.stopRecording();
  111564. if (this._reject) {
  111565. this._reject(event.error);
  111566. }
  111567. else {
  111568. throw new event.error;
  111569. }
  111570. };
  111571. VideoRecorder.prototype._handleStop = function () {
  111572. this.stopRecording();
  111573. var superBuffer = new Blob(this._recordedChunks);
  111574. if (this._resolve) {
  111575. this._resolve(superBuffer);
  111576. }
  111577. window.URL.createObjectURL(superBuffer);
  111578. if (this._fileName) {
  111579. BABYLON.Tools.Download(superBuffer, this._fileName);
  111580. }
  111581. };
  111582. VideoRecorder._defaultOptions = {
  111583. mimeType: "video/webm",
  111584. fps: 25,
  111585. recordChunckSize: 3000
  111586. };
  111587. return VideoRecorder;
  111588. }());
  111589. BABYLON.VideoRecorder = VideoRecorder;
  111590. })(BABYLON || (BABYLON = {}));
  111591. //# sourceMappingURL=babylon.videoRecorder.js.map
  111592. var BABYLON;
  111593. (function (BABYLON) {
  111594. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  111595. if (replace === void 0) { replace = false; }
  111596. // Dispose existing light in replace mode.
  111597. if (replace) {
  111598. if (this.lights) {
  111599. for (var i = 0; i < this.lights.length; i++) {
  111600. this.lights[i].dispose();
  111601. }
  111602. }
  111603. }
  111604. // Light
  111605. if (this.lights.length === 0) {
  111606. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  111607. }
  111608. };
  111609. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  111610. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  111611. if (replace === void 0) { replace = false; }
  111612. if (attachCameraControls === void 0) { attachCameraControls = false; }
  111613. // Dispose existing camera in replace mode.
  111614. if (replace) {
  111615. if (this.activeCamera) {
  111616. this.activeCamera.dispose();
  111617. this.activeCamera = null;
  111618. }
  111619. }
  111620. // Camera
  111621. if (!this.activeCamera) {
  111622. var worldExtends = this.getWorldExtends();
  111623. var worldSize = worldExtends.max.subtract(worldExtends.min);
  111624. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  111625. var camera;
  111626. var radius = worldSize.length() * 1.5;
  111627. // empty scene scenario!
  111628. if (!isFinite(radius)) {
  111629. radius = 1;
  111630. worldCenter.copyFromFloats(0, 0, 0);
  111631. }
  111632. if (createArcRotateCamera) {
  111633. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  111634. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  111635. arcRotateCamera.wheelPrecision = 100 / radius;
  111636. camera = arcRotateCamera;
  111637. }
  111638. else {
  111639. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  111640. freeCamera.setTarget(worldCenter);
  111641. camera = freeCamera;
  111642. }
  111643. camera.minZ = radius * 0.01;
  111644. camera.maxZ = radius * 1000;
  111645. camera.speed = radius * 0.2;
  111646. this.activeCamera = camera;
  111647. var canvas = this.getEngine().getRenderingCanvas();
  111648. if (attachCameraControls && canvas) {
  111649. camera.attachControl(canvas);
  111650. }
  111651. }
  111652. };
  111653. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  111654. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  111655. if (replace === void 0) { replace = false; }
  111656. if (attachCameraControls === void 0) { attachCameraControls = false; }
  111657. this.createDefaultLight(replace);
  111658. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  111659. };
  111660. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  111661. if (pbr === void 0) { pbr = false; }
  111662. if (scale === void 0) { scale = 1000; }
  111663. if (blur === void 0) { blur = 0; }
  111664. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  111665. if (!environmentTexture) {
  111666. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  111667. return null;
  111668. }
  111669. if (setGlobalEnvTexture) {
  111670. if (environmentTexture) {
  111671. this.environmentTexture = environmentTexture;
  111672. }
  111673. }
  111674. // Skybox
  111675. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  111676. if (pbr) {
  111677. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  111678. hdrSkyboxMaterial.backFaceCulling = false;
  111679. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  111680. if (hdrSkyboxMaterial.reflectionTexture) {
  111681. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111682. }
  111683. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  111684. hdrSkyboxMaterial.disableLighting = true;
  111685. hdrSkyboxMaterial.twoSidedLighting = true;
  111686. hdrSkybox.infiniteDistance = true;
  111687. hdrSkybox.material = hdrSkyboxMaterial;
  111688. }
  111689. else {
  111690. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  111691. skyboxMaterial.backFaceCulling = false;
  111692. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  111693. if (skyboxMaterial.reflectionTexture) {
  111694. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111695. }
  111696. skyboxMaterial.disableLighting = true;
  111697. hdrSkybox.infiniteDistance = true;
  111698. hdrSkybox.material = skyboxMaterial;
  111699. }
  111700. return hdrSkybox;
  111701. };
  111702. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  111703. if (BABYLON.EnvironmentHelper) {
  111704. return new BABYLON.EnvironmentHelper(options, this);
  111705. }
  111706. return null;
  111707. };
  111708. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  111709. if (webVROptions === void 0) { webVROptions = {}; }
  111710. return new BABYLON.VRExperienceHelper(this, webVROptions);
  111711. };
  111712. })(BABYLON || (BABYLON = {}));
  111713. //# sourceMappingURL=babylon.sceneHelpers.js.map
  111714. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\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<helperFunctions>\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>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\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\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\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#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\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#ifdef ALPHATEST\nuniform float alphaCutOff;\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>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\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<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\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) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\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;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\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;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\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;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\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#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\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\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\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<helperFunctions>\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(USESPHERICALINVERTEX)\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\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\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\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) || defined(SPECULARAA)\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(USESPHERICALINVERTEX)\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#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\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\nnormalW*=sign(dot(normalW,faceNormal));\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#include<depthPrePass>\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#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\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;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\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#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\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 RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\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.rgb*=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\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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\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#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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 AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\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\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\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 vec3 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.z*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}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying 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":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\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","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\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=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\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,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\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(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\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);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\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);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/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;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\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#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\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{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\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#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\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}","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)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,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#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\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\n#include<logDepthDeclaration>\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#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\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}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\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#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\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\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","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\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#endif\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\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\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 TEXTURELODSUPPORT\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\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\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#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\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#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  111715. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","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\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\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 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\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}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\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}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{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}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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 REFLECTION\nuniform mat4 reflectionMatrix;\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 vec2 vTangentSpaceParams;\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#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \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;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\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 vTangentSpaceParams;\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 computeShadowWithPoissonSamplingCube(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 computeShadowWithPoissonSampling(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#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\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":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\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\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\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\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\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\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\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;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\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#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\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 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\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\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>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\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\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#elif defined(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#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,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#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\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\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 vec4 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 vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\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#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \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 vec2 vTangentSpaceParams;\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,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\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 DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  111716. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  111717. globalObject["BABYLON"] = BABYLON;
  111718. //backwards compatibility
  111719. if(typeof earcut !== 'undefined') {
  111720. globalObject["Earcut"] = {
  111721. earcut: earcut
  111722. };
  111723. }
  111724. return BABYLON;
  111725. });